code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* IGraph library. Copyright (C) 2021 The igraph development team <igraph@igraph.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <igraph.h> #include "test_utilities.inc" int main() { igraph_t g_empty, g_lm; igraph_vector_t result; igraph_vs_t vids; igraph_rng_seed(igraph_rng_default(), 42); igraph_vector_init(&result, 0); igraph_vs_all(&vids); igraph_small(&g_empty, 0, 0, -1); igraph_small(&g_lm, 6, 1, 0,1, 0,2, 1,1, 1,3, 2,0, 2,3, 3,4, 3,4, -1); printf("No vertices:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_empty, &result, vids, /*order*/ 1, /*mode*/ IGRAPH_ALL, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 0:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 0, /*mode*/ IGRAPH_ALL, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 1, ignoring direction:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 1, /*mode*/ IGRAPH_ALL, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 1, only checking IGRAPH_IN:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 1, /*mode*/ IGRAPH_IN, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 10, ignoring direction:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 10, /*mode*/ IGRAPH_ALL, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 2, mindist 2, IGRAPH_OUT:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 2, /*mode*/ IGRAPH_OUT, /*mindist*/ 2) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 4, mindist 4, IGRAPH_ALL:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 4, /*mode*/ IGRAPH_ALL, /*mindist*/ 4) == IGRAPH_SUCCESS); print_vector(&result); VERIFY_FINALLY_STACK(); igraph_set_error_handler(igraph_error_handler_ignore); printf("Negative order.\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ -4, /*mode*/ IGRAPH_ALL, /*mindist*/ 4) == IGRAPH_EINVAL); printf("Negative mindist.\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 4, /*mode*/ IGRAPH_ALL, /*mindist*/ -4) == IGRAPH_EINVAL); igraph_vector_destroy(&result); igraph_destroy(&g_empty); igraph_destroy(&g_lm); VERIFY_FINALLY_STACK(); return 0; }
igraph/igraph
tests/unit/igraph_neighborhood_size.c
C
gpl-2.0
3,528
/* * linux/mm/vmscan.c * * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds * * Swap reorganised 29.12.95, Stephen Tweedie. * kswapd added: 7.1.96 sct * Removed kswapd_ctl limits, and swap out as many pages as needed * to bring the system back to freepages.high: 2.4.97, Rik van Riel. * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com). * Multiqueue VM started 5.8.00, Rik van Riel. */ #include <linux/mm.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/kernel_stat.h> #include <linux/swap.h> #include <linux/pagemap.h> #include <linux/init.h> #include <linux/highmem.h> #include <linux/vmstat.h> #include <linux/file.h> #include <linux/writeback.h> #include <linux/blkdev.h> #include <linux/buffer_head.h> /* for try_to_release_page(), buffer_heads_over_limit */ #include <linux/mm_inline.h> #include <linux/pagevec.h> #include <linux/backing-dev.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/notifier.h> #include <linux/rwsem.h> #include <linux/delay.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <asm/tlbflush.h> #include <asm/div64.h> #include <linux/swapops.h> #include "internal.h" struct scan_control { /* Incremented by the number of inactive pages that were scanned */ unsigned long nr_scanned; /* This context's GFP mask */ gfp_t gfp_mask; int may_writepage; /* Can pages be swapped as part of reclaim? */ int may_swap; /* This context's SWAP_CLUSTER_MAX. If freeing memory for * suspend, we effectively ignore SWAP_CLUSTER_MAX. * In this context, it doesn't matter that we scan the * whole list at once. */ int swap_cluster_max; int swappiness; int all_unreclaimable; }; /* * The list of shrinker callbacks used by to apply pressure to * ageable caches. */ struct shrinker { shrinker_t shrinker; struct list_head list; int seeks; /* seeks to recreate an obj */ long nr; /* objs pending delete */ }; #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru)) #ifdef ARCH_HAS_PREFETCH #define prefetch_prev_lru_page(_page, _base, _field) \ do { \ if ((_page)->lru.prev != _base) { \ struct page *prev; \ \ prev = lru_to_page(&(_page->lru)); \ prefetch(&prev->_field); \ } \ } while (0) #else #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0) #endif #ifdef ARCH_HAS_PREFETCHW #define prefetchw_prev_lru_page(_page, _base, _field) \ do { \ if ((_page)->lru.prev != _base) { \ struct page *prev; \ \ prev = lru_to_page(&(_page->lru)); \ prefetchw(&prev->_field); \ } \ } while (0) #else #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0) #endif /* * From 0 .. 100. Higher means more swappy. */ int vm_swappiness = 60; long vm_total_pages; /* The total number of pages which the VM controls */ static LIST_HEAD(shrinker_list); static DECLARE_RWSEM(shrinker_rwsem); /* * Add a shrinker callback to be called from the vm */ struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker) { struct shrinker *shrinker; shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL); if (shrinker) { shrinker->shrinker = theshrinker; shrinker->seeks = seeks; shrinker->nr = 0; down_write(&shrinker_rwsem); list_add_tail(&shrinker->list, &shrinker_list); up_write(&shrinker_rwsem); } return shrinker; } EXPORT_SYMBOL(set_shrinker); /* * Remove one */ void remove_shrinker(struct shrinker *shrinker) { down_write(&shrinker_rwsem); list_del(&shrinker->list); up_write(&shrinker_rwsem); kfree(shrinker); } EXPORT_SYMBOL(remove_shrinker); #define SHRINK_BATCH 128 /* * Call the shrink functions to age shrinkable caches * * Here we assume it costs one seek to replace a lru page and that it also * takes a seek to recreate a cache object. With this in mind we age equal * percentages of the lru and ageable caches. This should balance the seeks * generated by these structures. * * If the vm encounted mapped pages on the LRU it increase the pressure on * slab to avoid swapping. * * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits. * * `lru_pages' represents the number of on-LRU pages in all the zones which * are eligible for the caller's allocation attempt. It is used for balancing * slab reclaim versus page reclaim. * * Returns the number of slab objects which we shrunk. */ unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask, unsigned long lru_pages) { struct shrinker *shrinker; unsigned long ret = 0; if (scanned == 0) scanned = SWAP_CLUSTER_MAX; if (!down_read_trylock(&shrinker_rwsem)) return 1; /* Assume we'll be able to shrink next time */ list_for_each_entry(shrinker, &shrinker_list, list) { unsigned long long delta; unsigned long total_scan; unsigned long max_pass = (*shrinker->shrinker)(0, gfp_mask); delta = (4 * scanned) / shrinker->seeks; delta *= max_pass; do_div(delta, lru_pages + 1); shrinker->nr += delta; if (shrinker->nr < 0) { printk(KERN_ERR "%s: nr=%ld\n", __FUNCTION__, shrinker->nr); shrinker->nr = max_pass; } /* * Avoid risking looping forever due to too large nr value: * never try to free more than twice the estimate number of * freeable entries. */ if (shrinker->nr > max_pass * 2) shrinker->nr = max_pass * 2; total_scan = shrinker->nr; shrinker->nr = 0; while (total_scan >= SHRINK_BATCH) { long this_scan = SHRINK_BATCH; int shrink_ret; int nr_before; nr_before = (*shrinker->shrinker)(0, gfp_mask); shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask); if (shrink_ret == -1) break; if (shrink_ret < nr_before) ret += nr_before - shrink_ret; count_vm_events(SLABS_SCANNED, this_scan); total_scan -= this_scan; cond_resched(); } shrinker->nr += total_scan; } up_read(&shrinker_rwsem); return ret; } /* Called without lock on whether page is mapped, so answer is unstable */ static inline int page_mapping_inuse(struct page *page) { struct address_space *mapping; /* Page is in somebody's page tables. */ if (page_mapped(page)) return 1; /* Be more reluctant to reclaim swapcache than pagecache */ if (PageSwapCache(page)) return 1; mapping = page_mapping(page); if (!mapping) return 0; /* File is mmap'd by somebody? */ return mapping_mapped(mapping); } static inline int is_page_cache_freeable(struct page *page) { return page_count(page) - !!PagePrivate(page) == 2; } static int may_write_to_queue(struct backing_dev_info *bdi) { if (current->flags & PF_SWAPWRITE) return 1; if (!bdi_write_congested(bdi)) return 1; if (bdi == current->backing_dev_info) return 1; return 0; } /* * We detected a synchronous write error writing a page out. Probably * -ENOSPC. We need to propagate that into the address_space for a subsequent * fsync(), msync() or close(). * * The tricky part is that after writepage we cannot touch the mapping: nothing * prevents it from being freed up. But we have a ref on the page and once * that page is locked, the mapping is pinned. * * We're allowed to run sleeping lock_page() here because we know the caller has * __GFP_FS. */ static void handle_write_error(struct address_space *mapping, struct page *page, int error) { lock_page(page); if (page_mapping(page) == mapping) { if (error == -ENOSPC) set_bit(AS_ENOSPC, &mapping->flags); else set_bit(AS_EIO, &mapping->flags); } unlock_page(page); } /* possible outcome of pageout() */ typedef enum { /* failed to write page out, page is locked */ PAGE_KEEP, /* move page to the active list, page is locked */ PAGE_ACTIVATE, /* page has been sent to the disk successfully, page is unlocked */ PAGE_SUCCESS, /* page is clean and locked */ PAGE_CLEAN, } pageout_t; /* * pageout is called by shrink_page_list() for each dirty page. * Calls ->writepage(). */ static pageout_t pageout(struct page *page, struct address_space *mapping) { /* * If the page is dirty, only perform writeback if that write * will be non-blocking. To prevent this allocation from being * stalled by pagecache activity. But note that there may be * stalls if we need to run get_block(). We could test * PagePrivate for that. * * If this process is currently in generic_file_write() against * this page's queue, we can perform writeback even if that * will block. * * If the page is swapcache, write it back even if that would * block, for some throttling. This happens by accident, because * swap_backing_dev_info is bust: it doesn't reflect the * congestion state of the swapdevs. Easy to fix, if needed. * See swapfile.c:page_queue_congested(). */ if (!is_page_cache_freeable(page)) return PAGE_KEEP; if (!mapping) { /* * Some data journaling orphaned pages can have * page->mapping == NULL while being dirty with clean buffers. */ if (PagePrivate(page)) { if (try_to_free_buffers(page)) { ClearPageDirty(page); printk("%s: orphaned page\n", __FUNCTION__); return PAGE_CLEAN; } } return PAGE_KEEP; } if (mapping->a_ops->writepage == NULL) return PAGE_ACTIVATE; if (!may_write_to_queue(mapping->backing_dev_info)) return PAGE_KEEP; if (clear_page_dirty_for_io(page)) { int res; struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = SWAP_CLUSTER_MAX, .range_start = 0, .range_end = LLONG_MAX, .nonblocking = 1, .for_reclaim = 1, }; SetPageReclaim(page); res = mapping->a_ops->writepage(page, &wbc); if (res < 0) handle_write_error(mapping, page, res); if (res == AOP_WRITEPAGE_ACTIVATE) { ClearPageReclaim(page); return PAGE_ACTIVATE; } if (!PageWriteback(page)) { /* synchronous write or broken a_ops? */ ClearPageReclaim(page); } inc_zone_page_state(page, NR_VMSCAN_WRITE); return PAGE_SUCCESS; } return PAGE_CLEAN; } /* * Attempt to detach a locked page from its ->mapping. If it is dirty or if * someone else has a ref on the page, abort and return 0. If it was * successfully detached, return 1. Assumes the caller has a single ref on * this page. */ int remove_mapping(struct address_space *mapping, struct page *page) { BUG_ON(!PageLocked(page)); BUG_ON(mapping != page_mapping(page)); write_lock_irq(&mapping->tree_lock); /* * The non racy check for a busy page. * * Must be careful with the order of the tests. When someone has * a ref to the page, it may be possible that they dirty it then * drop the reference. So if PageDirty is tested before page_count * here, then the following race may occur: * * get_user_pages(&page); * [user mapping goes away] * write_to(page); * !PageDirty(page) [good] * SetPageDirty(page); * put_page(page); * !page_count(page) [good, discard it] * * [oops, our write_to data is lost] * * Reversing the order of the tests ensures such a situation cannot * escape unnoticed. The smp_rmb is needed to ensure the page->flags * load is not satisfied before that of page->_count. * * Note that if SetPageDirty is always performed via set_page_dirty, * and thus under tree_lock, then this ordering is not required. */ if (unlikely(page_count(page) != 2)) goto cannot_free; smp_rmb(); if (unlikely(PageDirty(page))) goto cannot_free; if (PageSwapCache(page)) { swp_entry_t swap = { .val = page_private(page) }; __delete_from_swap_cache(page); write_unlock_irq(&mapping->tree_lock); swap_free(swap); __put_page(page); /* The pagecache ref */ return 1; } __remove_from_page_cache(page); write_unlock_irq(&mapping->tree_lock); __put_page(page); return 1; cannot_free: write_unlock_irq(&mapping->tree_lock); return 0; } /* * shrink_page_list() returns the number of reclaimed pages */ static unsigned long shrink_page_list(struct list_head *page_list, struct scan_control *sc) { LIST_HEAD(ret_pages); struct pagevec freed_pvec; int pgactivate = 0; unsigned long nr_reclaimed = 0; cond_resched(); pagevec_init(&freed_pvec, 1); while (!list_empty(page_list)) { struct address_space *mapping; struct page *page; int may_enter_fs; int referenced; cond_resched(); page = lru_to_page(page_list); list_del(&page->lru); if (TestSetPageLocked(page)) goto keep; VM_BUG_ON(PageActive(page)); sc->nr_scanned++; if (!sc->may_swap && page_mapped(page)) goto keep_locked; /* Double the slab pressure for mapped and swapcache pages */ if (page_mapped(page) || PageSwapCache(page)) sc->nr_scanned++; if (PageWriteback(page)) goto keep_locked; referenced = page_referenced(page, 1); /* In active use or really unfreeable? Activate it. */ if (referenced && page_mapping_inuse(page)) goto activate_locked; #ifdef CONFIG_SWAP /* * Anonymous process memory has backing store? * Try to allocate it some swap space here. */ if (PageAnon(page) && !PageSwapCache(page)) if (!add_to_swap(page, GFP_ATOMIC)) goto activate_locked; #endif /* CONFIG_SWAP */ mapping = page_mapping(page); may_enter_fs = (sc->gfp_mask & __GFP_FS) || (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO)); /* * The page is mapped into the page tables of one or more * processes. Try to unmap it here. */ if (page_mapped(page) && mapping) { switch (try_to_unmap(page, 0)) { case SWAP_FAIL: goto activate_locked; case SWAP_AGAIN: goto keep_locked; case SWAP_SUCCESS: ; /* try to free the page below */ } } if (PageDirty(page)) { if (referenced) goto keep_locked; if (!may_enter_fs) goto keep_locked; if (!sc->may_writepage) goto keep_locked; /* Page is dirty, try to write it out here */ switch(pageout(page, mapping)) { case PAGE_KEEP: goto keep_locked; case PAGE_ACTIVATE: goto activate_locked; case PAGE_SUCCESS: if (PageWriteback(page) || PageDirty(page)) goto keep; /* * A synchronous write - probably a ramdisk. Go * ahead and try to reclaim the page. */ if (TestSetPageLocked(page)) goto keep; if (PageDirty(page) || PageWriteback(page)) goto keep_locked; mapping = page_mapping(page); case PAGE_CLEAN: ; /* try to free the page below */ } } /* * If the page has buffers, try to free the buffer mappings * associated with this page. If we succeed we try to free * the page as well. * * We do this even if the page is PageDirty(). * try_to_release_page() does not perform I/O, but it is * possible for a page to have PageDirty set, but it is actually * clean (all its buffers are clean). This happens if the * buffers were written out directly, with submit_bh(). ext3 * will do this, as well as the blockdev mapping. * try_to_release_page() will discover that cleanness and will * drop the buffers and mark the page clean - it can be freed. * * Rarely, pages can have buffers and no ->mapping. These are * the pages which were not successfully invalidated in * truncate_complete_page(). We try to drop those buffers here * and if that worked, and the page is no longer mapped into * process address space (page_count == 1) it can be freed. * Otherwise, leave the page on the LRU so it is swappable. */ if (PagePrivate(page)) { if (!try_to_release_page(page, sc->gfp_mask)) goto activate_locked; if (!mapping && page_count(page) == 1) goto free_it; } if (!mapping || !remove_mapping(mapping, page)) goto keep_locked; free_it: unlock_page(page); nr_reclaimed++; if (!pagevec_add(&freed_pvec, page)) __pagevec_release_nonlru(&freed_pvec); continue; activate_locked: SetPageActive(page); pgactivate++; keep_locked: unlock_page(page); keep: list_add(&page->lru, &ret_pages); VM_BUG_ON(PageLRU(page)); } list_splice(&ret_pages, page_list); if (pagevec_count(&freed_pvec)) __pagevec_release_nonlru(&freed_pvec); count_vm_events(PGACTIVATE, pgactivate); return nr_reclaimed; } /* * zone->lru_lock is heavily contended. Some of the functions that * shrink the lists perform better by taking out a batch of pages * and working on them outside the LRU lock. * * For pagecache intensive workloads, this function is the hottest * spot in the kernel (apart from copy_*_user functions). * * Appropriate locks must be held before calling this function. * * @nr_to_scan: The number of pages to look through on the list. * @src: The LRU list to pull pages off. * @dst: The temp list to put pages on to. * @scanned: The number of pages that were scanned. * * returns how many pages were moved onto *@dst. */ static unsigned long isolate_lru_pages(unsigned long nr_to_scan, struct list_head *src, struct list_head *dst, unsigned long *scanned) { unsigned long nr_taken = 0; struct page *page; unsigned long scan; for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) { struct list_head *target; page = lru_to_page(src); prefetchw_prev_lru_page(page, src, flags); VM_BUG_ON(!PageLRU(page)); list_del(&page->lru); target = src; if (likely(get_page_unless_zero(page))) { /* * Be careful not to clear PageLRU until after we're * sure the page is not being freed elsewhere -- the * page release code relies on it. */ ClearPageLRU(page); target = dst; nr_taken++; } /* else it is being freed elsewhere */ list_add(&page->lru, target); } *scanned = scan; return nr_taken; } /* * shrink_inactive_list() is a helper for shrink_zone(). It returns the number * of reclaimed pages */ static unsigned long shrink_inactive_list(unsigned long max_scan, struct zone *zone, struct scan_control *sc) { LIST_HEAD(page_list); struct pagevec pvec; unsigned long nr_scanned = 0; unsigned long nr_reclaimed = 0; pagevec_init(&pvec, 1); lru_add_drain(); spin_lock_irq(&zone->lru_lock); do { struct page *page; unsigned long nr_taken; unsigned long nr_scan; unsigned long nr_freed; nr_taken = isolate_lru_pages(sc->swap_cluster_max, &zone->inactive_list, &page_list, &nr_scan); __mod_zone_page_state(zone, NR_INACTIVE, -nr_taken); zone->pages_scanned += nr_scan; spin_unlock_irq(&zone->lru_lock); nr_scanned += nr_scan; nr_freed = shrink_page_list(&page_list, sc); nr_reclaimed += nr_freed; local_irq_disable(); if (current_is_kswapd()) { __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scan); __count_vm_events(KSWAPD_STEAL, nr_freed); } else __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scan); __count_zone_vm_events(PGSTEAL, zone, nr_freed); if (nr_taken == 0) goto done; spin_lock(&zone->lru_lock); /* * Put back any unfreeable pages. */ while (!list_empty(&page_list)) { page = lru_to_page(&page_list); VM_BUG_ON(PageLRU(page)); SetPageLRU(page); list_del(&page->lru); if (PageActive(page)) add_page_to_active_list(zone, page); else add_page_to_inactive_list(zone, page); if (!pagevec_add(&pvec, page)) { spin_unlock_irq(&zone->lru_lock); __pagevec_release(&pvec); spin_lock_irq(&zone->lru_lock); } } } while (nr_scanned < max_scan); spin_unlock(&zone->lru_lock); done: local_irq_enable(); pagevec_release(&pvec); return nr_reclaimed; } /* * We are about to scan this zone at a certain priority level. If that priority * level is smaller (ie: more urgent) than the previous priority, then note * that priority level within the zone. This is done so that when the next * process comes in to scan this zone, it will immediately start out at this * priority level rather than having to build up its own scanning priority. * Here, this priority affects only the reclaim-mapped threshold. */ static inline void note_zone_scanning_priority(struct zone *zone, int priority) { if (priority < zone->prev_priority) zone->prev_priority = priority; } static inline int zone_is_near_oom(struct zone *zone) { return zone->pages_scanned >= (zone_page_state(zone, NR_ACTIVE) + zone_page_state(zone, NR_INACTIVE))*3; } /* * This moves pages from the active list to the inactive list. * * We move them the other way if the page is referenced by one or more * processes, from rmap. * * If the pages are mostly unmapped, the processing is fast and it is * appropriate to hold zone->lru_lock across the whole operation. But if * the pages are mapped, the processing is slow (page_referenced()) so we * should drop zone->lru_lock around each page. It's impossible to balance * this, so instead we remove the pages from the LRU while processing them. * It is safe to rely on PG_active against the non-LRU pages in here because * nobody will play with that bit on a non-LRU page. * * The downside is that we have to touch page->_count against each page. * But we had to alter page->flags anyway. */ static void shrink_active_list(unsigned long nr_pages, struct zone *zone, struct scan_control *sc, int priority) { unsigned long pgmoved; int pgdeactivate = 0; unsigned long pgscanned; LIST_HEAD(l_hold); /* The pages which were snipped off */ LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */ LIST_HEAD(l_active); /* Pages to go onto the active_list */ struct page *page; struct pagevec pvec; int reclaim_mapped = 0; if (sc->may_swap) { long mapped_ratio; long distress; long swap_tendency; if (zone_is_near_oom(zone)) goto force_reclaim_mapped; /* * `distress' is a measure of how much trouble we're having * reclaiming pages. 0 -> no problems. 100 -> great trouble. */ distress = 100 >> min(zone->prev_priority, priority); /* * The point of this algorithm is to decide when to start * reclaiming mapped memory instead of just pagecache. Work out * how much memory * is mapped. */ mapped_ratio = ((global_page_state(NR_FILE_MAPPED) + global_page_state(NR_ANON_PAGES)) * 100) / vm_total_pages; /* * Now decide how much we really want to unmap some pages. The * mapped ratio is downgraded - just because there's a lot of * mapped memory doesn't necessarily mean that page reclaim * isn't succeeding. * * The distress ratio is important - we don't want to start * going oom. * * A 100% value of vm_swappiness overrides this algorithm * altogether. */ swap_tendency = mapped_ratio / 2 + distress + sc->swappiness; /* * Now use this metric to decide whether to start moving mapped * memory onto the inactive list. */ if (swap_tendency >= 100) force_reclaim_mapped: reclaim_mapped = 1; } lru_add_drain(); spin_lock_irq(&zone->lru_lock); pgmoved = isolate_lru_pages(nr_pages, &zone->active_list, &l_hold, &pgscanned); zone->pages_scanned += pgscanned; __mod_zone_page_state(zone, NR_ACTIVE, -pgmoved); spin_unlock_irq(&zone->lru_lock); while (!list_empty(&l_hold)) { cond_resched(); page = lru_to_page(&l_hold); list_del(&page->lru); if (page_mapped(page)) { if (!reclaim_mapped || (total_swap_pages == 0 && PageAnon(page)) || page_referenced(page, 0)) { list_add(&page->lru, &l_active); continue; } } list_add(&page->lru, &l_inactive); } pagevec_init(&pvec, 1); pgmoved = 0; spin_lock_irq(&zone->lru_lock); while (!list_empty(&l_inactive)) { page = lru_to_page(&l_inactive); prefetchw_prev_lru_page(page, &l_inactive, flags); VM_BUG_ON(PageLRU(page)); SetPageLRU(page); VM_BUG_ON(!PageActive(page)); ClearPageActive(page); list_move(&page->lru, &zone->inactive_list); pgmoved++; if (!pagevec_add(&pvec, page)) { __mod_zone_page_state(zone, NR_INACTIVE, pgmoved); spin_unlock_irq(&zone->lru_lock); pgdeactivate += pgmoved; pgmoved = 0; if (buffer_heads_over_limit) pagevec_strip(&pvec); __pagevec_release(&pvec); spin_lock_irq(&zone->lru_lock); } } __mod_zone_page_state(zone, NR_INACTIVE, pgmoved); pgdeactivate += pgmoved; if (buffer_heads_over_limit) { spin_unlock_irq(&zone->lru_lock); pagevec_strip(&pvec); spin_lock_irq(&zone->lru_lock); } pgmoved = 0; while (!list_empty(&l_active)) { page = lru_to_page(&l_active); prefetchw_prev_lru_page(page, &l_active, flags); VM_BUG_ON(PageLRU(page)); SetPageLRU(page); VM_BUG_ON(!PageActive(page)); list_move(&page->lru, &zone->active_list); pgmoved++; if (!pagevec_add(&pvec, page)) { __mod_zone_page_state(zone, NR_ACTIVE, pgmoved); pgmoved = 0; spin_unlock_irq(&zone->lru_lock); __pagevec_release(&pvec); spin_lock_irq(&zone->lru_lock); } } __mod_zone_page_state(zone, NR_ACTIVE, pgmoved); __count_zone_vm_events(PGREFILL, zone, pgscanned); __count_vm_events(PGDEACTIVATE, pgdeactivate); spin_unlock_irq(&zone->lru_lock); pagevec_release(&pvec); } /* * This is a basic per-zone page freer. Used by both kswapd and direct reclaim. */ static unsigned long shrink_zone(int priority, struct zone *zone, struct scan_control *sc) { unsigned long nr_active; unsigned long nr_inactive; unsigned long nr_to_scan; unsigned long nr_reclaimed = 0; atomic_inc(&zone->reclaim_in_progress); /* * Add one to `nr_to_scan' just to make sure that the kernel will * slowly sift through the active list. */ zone->nr_scan_active += (zone_page_state(zone, NR_ACTIVE) >> priority) + 1; nr_active = zone->nr_scan_active; if (nr_active >= sc->swap_cluster_max) zone->nr_scan_active = 0; else nr_active = 0; zone->nr_scan_inactive += (zone_page_state(zone, NR_INACTIVE) >> priority) + 1; nr_inactive = zone->nr_scan_inactive; if (nr_inactive >= sc->swap_cluster_max) zone->nr_scan_inactive = 0; else nr_inactive = 0; while (nr_active || nr_inactive) { if (nr_active) { nr_to_scan = min(nr_active, (unsigned long)sc->swap_cluster_max); nr_active -= nr_to_scan; shrink_active_list(nr_to_scan, zone, sc, priority); } if (nr_inactive) { nr_to_scan = min(nr_inactive, (unsigned long)sc->swap_cluster_max); nr_inactive -= nr_to_scan; nr_reclaimed += shrink_inactive_list(nr_to_scan, zone, sc); } } throttle_vm_writeout(sc->gfp_mask); atomic_dec(&zone->reclaim_in_progress); return nr_reclaimed; } /* * This is the direct reclaim path, for page-allocating processes. We only * try to reclaim pages from zones which will satisfy the caller's allocation * request. * * We reclaim from a zone even if that zone is over pages_high. Because: * a) The caller may be trying to free *extra* pages to satisfy a higher-order * allocation or * b) The zones may be over pages_high but they must go *over* pages_high to * satisfy the `incremental min' zone defense algorithm. * * Returns the number of reclaimed pages. * * If a zone is deemed to be full of pinned pages then just give it a light * scan then give up on it. */ static unsigned long shrink_zones(int priority, struct zone **zones, struct scan_control *sc) { unsigned long nr_reclaimed = 0; int i; sc->all_unreclaimable = 1; for (i = 0; zones[i] != NULL; i++) { struct zone *zone = zones[i]; if (!populated_zone(zone)) continue; if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) continue; note_zone_scanning_priority(zone, priority); if (zone->all_unreclaimable && priority != DEF_PRIORITY) continue; /* Let kswapd poll it */ sc->all_unreclaimable = 0; nr_reclaimed += shrink_zone(priority, zone, sc); } return nr_reclaimed; } /* * This is the main entry point to direct page reclaim. * * If a full scan of the inactive list fails to free enough memory then we * are "out of memory" and something needs to be killed. * * If the caller is !__GFP_FS then the probability of a failure is reasonably * high - the zone may be full of dirty or under-writeback pages, which this * caller can't do much about. We kick pdflush and take explicit naps in the * hope that some of these pages can be written. But if the allocating task * holds filesystem locks which prevent writeout this might not work, and the * allocation attempt will fail. */ unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask) { int priority; int ret = 0; unsigned long total_scanned = 0; unsigned long nr_reclaimed = 0; struct reclaim_state *reclaim_state = current->reclaim_state; unsigned long lru_pages = 0; int i; struct scan_control sc = { .gfp_mask = gfp_mask, .may_writepage = !laptop_mode, .swap_cluster_max = SWAP_CLUSTER_MAX, .may_swap = 1, .swappiness = vm_swappiness, }; count_vm_event(ALLOCSTALL); for (i = 0; zones[i] != NULL; i++) { struct zone *zone = zones[i]; if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) continue; lru_pages += zone_page_state(zone, NR_ACTIVE) + zone_page_state(zone, NR_INACTIVE); } for (priority = DEF_PRIORITY; priority >= 0; priority--) { sc.nr_scanned = 0; if (!priority) disable_swap_token(); nr_reclaimed += shrink_zones(priority, zones, &sc); shrink_slab(sc.nr_scanned, gfp_mask, lru_pages); if (reclaim_state) { nr_reclaimed += reclaim_state->reclaimed_slab; reclaim_state->reclaimed_slab = 0; } total_scanned += sc.nr_scanned; if (nr_reclaimed >= sc.swap_cluster_max) { ret = 1; goto out; } /* * Try to write back as many pages as we just scanned. This * tends to cause slow streaming writers to write data to the * disk smoothly, at the dirtying rate, which is nice. But * that's undesirable in laptop mode, where we *want* lumpy * writeout. So in laptop mode, write out the whole world. */ if (total_scanned > sc.swap_cluster_max + sc.swap_cluster_max / 2) { wakeup_pdflush(laptop_mode ? 0 : total_scanned); sc.may_writepage = 1; } /* Take a nap, wait for some writeback to complete */ if (sc.nr_scanned && priority < DEF_PRIORITY - 2) congestion_wait(WRITE, HZ/10); } /* top priority shrink_caches still had more to do? don't OOM, then */ if (!sc.all_unreclaimable) ret = 1; out: /* * Now that we've scanned all the zones at this priority level, note * that level within the zone so that the next thread which performs * scanning of this zone will immediately start out at this priority * level. This affects only the decision whether or not to bring * mapped pages onto the inactive list. */ if (priority < 0) priority = 0; for (i = 0; zones[i] != 0; i++) { struct zone *zone = zones[i]; if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) continue; zone->prev_priority = priority; } return ret; } /* * For kswapd, balance_pgdat() will work across all this node's zones until * they are all at pages_high. * * Returns the number of pages which were actually freed. * * There is special handling here for zones which are full of pinned pages. * This can happen if the pages are all mlocked, or if they are all used by * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb. * What we do is to detect the case where all pages in the zone have been * scanned twice and there has been zero successful reclaim. Mark the zone as * dead and from now on, only perform a short scan. Basically we're polling * the zone for when the problem goes away. * * kswapd scans the zones in the highmem->normal->dma direction. It skips * zones which have free_pages > pages_high, but once a zone is found to have * free_pages <= pages_high, we scan that zone and the lower zones regardless * of the number of free pages in the lower zones. This interoperates with * the page allocator fallback scheme to ensure that aging of pages is balanced * across the zones. */ static unsigned long balance_pgdat(pg_data_t *pgdat, int order) { int all_zones_ok; int priority; int i; unsigned long total_scanned; unsigned long nr_reclaimed; struct reclaim_state *reclaim_state = current->reclaim_state; struct scan_control sc = { .gfp_mask = GFP_KERNEL, .may_swap = 1, .swap_cluster_max = SWAP_CLUSTER_MAX, .swappiness = vm_swappiness, }; /* * temp_priority is used to remember the scanning priority at which * this zone was successfully refilled to free_pages == pages_high. */ int temp_priority[MAX_NR_ZONES]; loop_again: total_scanned = 0; nr_reclaimed = 0; sc.may_writepage = !laptop_mode; count_vm_event(PAGEOUTRUN); for (i = 0; i < pgdat->nr_zones; i++) temp_priority[i] = DEF_PRIORITY; for (priority = DEF_PRIORITY; priority >= 0; priority--) { int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */ unsigned long lru_pages = 0; /* The swap token gets in the way of swapout... */ if (!priority) disable_swap_token(); all_zones_ok = 1; /* * Scan in the highmem->dma direction for the highest * zone which needs scanning */ for (i = pgdat->nr_zones - 1; i >= 0; i--) { struct zone *zone = pgdat->node_zones + i; if (!populated_zone(zone)) continue; if (zone->all_unreclaimable && priority != DEF_PRIORITY) continue; if (!zone_watermark_ok(zone, order, zone->pages_high, 0, 0)) { end_zone = i; break; } } if (i < 0) goto out; for (i = 0; i <= end_zone; i++) { struct zone *zone = pgdat->node_zones + i; lru_pages += zone_page_state(zone, NR_ACTIVE) + zone_page_state(zone, NR_INACTIVE); } /* * Now scan the zone in the dma->highmem direction, stopping * at the last zone which needs scanning. * * We do this because the page allocator works in the opposite * direction. This prevents the page allocator from allocating * pages behind kswapd's direction of progress, which would * cause too much scanning of the lower zones. */ for (i = 0; i <= end_zone; i++) { struct zone *zone = pgdat->node_zones + i; int nr_slab; if (!populated_zone(zone)) continue; if (zone->all_unreclaimable && priority != DEF_PRIORITY) continue; if (!zone_watermark_ok(zone, order, zone->pages_high, end_zone, 0)) all_zones_ok = 0; temp_priority[i] = priority; sc.nr_scanned = 0; note_zone_scanning_priority(zone, priority); nr_reclaimed += shrink_zone(priority, zone, &sc); reclaim_state->reclaimed_slab = 0; nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages); nr_reclaimed += reclaim_state->reclaimed_slab; total_scanned += sc.nr_scanned; if (zone->all_unreclaimable) continue; if (nr_slab == 0 && zone->pages_scanned >= (zone_page_state(zone, NR_ACTIVE) + zone_page_state(zone, NR_INACTIVE)) * 6) zone->all_unreclaimable = 1; /* * If we've done a decent amount of scanning and * the reclaim ratio is low, start doing writepage * even in laptop mode */ if (total_scanned > SWAP_CLUSTER_MAX * 2 && total_scanned > nr_reclaimed + nr_reclaimed / 2) sc.may_writepage = 1; } if (all_zones_ok) break; /* kswapd: all done */ /* * OK, kswapd is getting into trouble. Take a nap, then take * another pass across the zones. */ if (total_scanned && priority < DEF_PRIORITY - 2) congestion_wait(WRITE, HZ/10); /* * We do this so kswapd doesn't build up large priorities for * example when it is freeing in parallel with allocators. It * matches the direct reclaim path behaviour in terms of impact * on zone->*_priority. */ if (nr_reclaimed >= SWAP_CLUSTER_MAX) break; } out: /* * Note within each zone the priority level at which this zone was * brought into a happy state. So that the next thread which scans this * zone will start out at that priority level. */ for (i = 0; i < pgdat->nr_zones; i++) { struct zone *zone = pgdat->node_zones + i; zone->prev_priority = temp_priority[i]; } if (!all_zones_ok) { cond_resched(); try_to_freeze(); goto loop_again; } return nr_reclaimed; } /* * The background pageout daemon, started as a kernel thread * from the init process. * * This basically trickles out pages so that we have _some_ * free memory available even if there is no other activity * that frees anything up. This is needed for things like routing * etc, where we otherwise might have all activity going on in * asynchronous contexts that cannot page things out. * * If there are applications that are active memory-allocators * (most normal use), this basically shouldn't matter. */ static int kswapd(void *p) { unsigned long order; pg_data_t *pgdat = (pg_data_t*)p; struct task_struct *tsk = current; DEFINE_WAIT(wait); struct reclaim_state reclaim_state = { .reclaimed_slab = 0, }; cpumask_t cpumask; cpumask = node_to_cpumask(pgdat->node_id); if (!cpus_empty(cpumask)) set_cpus_allowed(tsk, cpumask); current->reclaim_state = &reclaim_state; /* * Tell the memory management that we're a "memory allocator", * and that if we need more memory we should get access to it * regardless (see "__alloc_pages()"). "kswapd" should * never get caught in the normal page freeing logic. * * (Kswapd normally doesn't need memory anyway, but sometimes * you need a small amount of memory in order to be able to * page out something else, and this flag essentially protects * us from recursively trying to free more memory as we're * trying to free the first piece of memory in the first place). */ tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD; order = 0; for ( ; ; ) { unsigned long new_order; try_to_freeze(); prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); new_order = pgdat->kswapd_max_order; pgdat->kswapd_max_order = 0; if (order < new_order) { /* * Don't sleep if someone wants a larger 'order' * allocation */ order = new_order; } else { schedule(); order = pgdat->kswapd_max_order; } finish_wait(&pgdat->kswapd_wait, &wait); balance_pgdat(pgdat, order); } return 0; } /* * A zone is low on free memory, so wake its kswapd task to service it. */ void wakeup_kswapd(struct zone *zone, int order) { pg_data_t *pgdat; if (!populated_zone(zone)) return; pgdat = zone->zone_pgdat; if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0)) return; if (pgdat->kswapd_max_order < order) pgdat->kswapd_max_order = order; if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) return; if (!waitqueue_active(&pgdat->kswapd_wait)) return; wake_up_interruptible(&pgdat->kswapd_wait); } #ifdef CONFIG_PM /* * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages * from LRU lists system-wide, for given pass and priority, and returns the * number of reclaimed pages * * For pass > 3 we also try to shrink the LRU lists that contain a few pages */ static unsigned long shrink_all_zones(unsigned long nr_pages, int prio, int pass, struct scan_control *sc) { struct zone *zone; unsigned long nr_to_scan, ret = 0; for_each_zone(zone) { if (!populated_zone(zone)) continue; if (zone->all_unreclaimable && prio != DEF_PRIORITY) continue; /* For pass = 0 we don't shrink the active list */ if (pass > 0) { zone->nr_scan_active += (zone_page_state(zone, NR_ACTIVE) >> prio) + 1; if (zone->nr_scan_active >= nr_pages || pass > 3) { zone->nr_scan_active = 0; nr_to_scan = min(nr_pages, zone_page_state(zone, NR_ACTIVE)); shrink_active_list(nr_to_scan, zone, sc, prio); } } zone->nr_scan_inactive += (zone_page_state(zone, NR_INACTIVE) >> prio) + 1; if (zone->nr_scan_inactive >= nr_pages || pass > 3) { zone->nr_scan_inactive = 0; nr_to_scan = min(nr_pages, zone_page_state(zone, NR_INACTIVE)); ret += shrink_inactive_list(nr_to_scan, zone, sc); if (ret >= nr_pages) return ret; } } return ret; } static unsigned long count_lru_pages(void) { return global_page_state(NR_ACTIVE) + global_page_state(NR_INACTIVE); } /* * Try to free `nr_pages' of memory, system-wide, and return the number of * freed pages. * * Rather than trying to age LRUs the aim is to preserve the overall * LRU order by reclaiming preferentially * inactive > active > active referenced > active mapped */ unsigned long shrink_all_memory(unsigned long nr_pages) { unsigned long lru_pages, nr_slab; unsigned long ret = 0; int pass; struct reclaim_state reclaim_state; struct scan_control sc = { .gfp_mask = GFP_KERNEL, .may_swap = 0, .swap_cluster_max = nr_pages, .may_writepage = 1, .swappiness = vm_swappiness, }; current->reclaim_state = &reclaim_state; lru_pages = count_lru_pages(); nr_slab = global_page_state(NR_SLAB_RECLAIMABLE); /* If slab caches are huge, it's better to hit them first */ while (nr_slab >= lru_pages) { reclaim_state.reclaimed_slab = 0; shrink_slab(nr_pages, sc.gfp_mask, lru_pages); if (!reclaim_state.reclaimed_slab) break; ret += reclaim_state.reclaimed_slab; if (ret >= nr_pages) goto out; nr_slab -= reclaim_state.reclaimed_slab; } /* * We try to shrink LRUs in 5 passes: * 0 = Reclaim from inactive_list only * 1 = Reclaim from active list but don't reclaim mapped * 2 = 2nd pass of type 1 * 3 = Reclaim mapped (normal reclaim) * 4 = 2nd pass of type 3 */ for (pass = 0; pass < 5; pass++) { int prio; /* Force reclaiming mapped pages in the passes #3 and #4 */ if (pass > 2) { sc.may_swap = 1; sc.swappiness = 100; } for (prio = DEF_PRIORITY; prio >= 0; prio--) { unsigned long nr_to_scan = nr_pages - ret; sc.nr_scanned = 0; ret += shrink_all_zones(nr_to_scan, prio, pass, &sc); if (ret >= nr_pages) goto out; reclaim_state.reclaimed_slab = 0; shrink_slab(sc.nr_scanned, sc.gfp_mask, count_lru_pages()); ret += reclaim_state.reclaimed_slab; if (ret >= nr_pages) goto out; if (sc.nr_scanned && prio < DEF_PRIORITY - 2) congestion_wait(WRITE, HZ / 10); } } /* * If ret = 0, we could not shrink LRUs, but there may be something * in slab caches */ if (!ret) { do { reclaim_state.reclaimed_slab = 0; shrink_slab(nr_pages, sc.gfp_mask, count_lru_pages()); ret += reclaim_state.reclaimed_slab; } while (ret < nr_pages && reclaim_state.reclaimed_slab > 0); } out: current->reclaim_state = NULL; return ret; } #endif /* It's optimal to keep kswapds on the same CPUs as their memory, but not required for correctness. So if the last cpu in a node goes away, we get changed to run anywhere: as the first one comes back, restore their cpu bindings. */ static int __devinit cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { pg_data_t *pgdat; cpumask_t mask; if (action == CPU_ONLINE) { for_each_online_pgdat(pgdat) { mask = node_to_cpumask(pgdat->node_id); if (any_online_cpu(mask) != NR_CPUS) /* One of our CPUs online: restore mask */ set_cpus_allowed(pgdat->kswapd, mask); } } return NOTIFY_OK; } /* * This kswapd start function will be called by init and node-hot-add. * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added. */ int kswapd_run(int nid) { pg_data_t *pgdat = NODE_DATA(nid); int ret = 0; if (pgdat->kswapd) return 0; pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid); if (IS_ERR(pgdat->kswapd)) { /* failure at boot is fatal */ BUG_ON(system_state == SYSTEM_BOOTING); printk("Failed to start kswapd on node %d\n",nid); ret = -1; } return ret; } static int __init kswapd_init(void) { int nid; swap_setup(); for_each_online_node(nid) kswapd_run(nid); hotcpu_notifier(cpu_callback, 0); return 0; } module_init(kswapd_init) #ifdef CONFIG_NUMA /* * Zone reclaim mode * * If non-zero call zone_reclaim when the number of free pages falls below * the watermarks. */ int zone_reclaim_mode __read_mostly; #define RECLAIM_OFF 0 #define RECLAIM_ZONE (1<<0) /* Run shrink_cache on the zone */ #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */ #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */ /* * Priority for ZONE_RECLAIM. This determines the fraction of pages * of a node considered for each zone_reclaim. 4 scans 1/16th of * a zone. */ #define ZONE_RECLAIM_PRIORITY 4 /* * Percentage of pages in a zone that must be unmapped for zone_reclaim to * occur. */ int sysctl_min_unmapped_ratio = 1; /* * If the number of slab pages in a zone grows beyond this percentage then * slab reclaim needs to occur. */ int sysctl_min_slab_ratio = 5; /* * Try to free up some pages from this zone through reclaim. */ static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order) { /* Minimum pages needed in order to stay on node */ const unsigned long nr_pages = 1 << order; struct task_struct *p = current; struct reclaim_state reclaim_state; int priority; unsigned long nr_reclaimed = 0; struct scan_control sc = { .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE), .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP), .swap_cluster_max = max_t(unsigned long, nr_pages, SWAP_CLUSTER_MAX), .gfp_mask = gfp_mask, .swappiness = vm_swappiness, }; unsigned long slab_reclaimable; disable_swap_token(); cond_resched(); /* * We need to be able to allocate from the reserves for RECLAIM_SWAP * and we also need to be able to write out pages for RECLAIM_WRITE * and RECLAIM_SWAP. */ p->flags |= PF_MEMALLOC | PF_SWAPWRITE; reclaim_state.reclaimed_slab = 0; p->reclaim_state = &reclaim_state; if (zone_page_state(zone, NR_FILE_PAGES) - zone_page_state(zone, NR_FILE_MAPPED) > zone->min_unmapped_pages) { /* * Free memory by calling shrink zone with increasing * priorities until we have enough memory freed. */ priority = ZONE_RECLAIM_PRIORITY; do { note_zone_scanning_priority(zone, priority); nr_reclaimed += shrink_zone(priority, zone, &sc); priority--; } while (priority >= 0 && nr_reclaimed < nr_pages); } slab_reclaimable = zone_page_state(zone, NR_SLAB_RECLAIMABLE); if (slab_reclaimable > zone->min_slab_pages) { /* * shrink_slab() does not currently allow us to determine how * many pages were freed in this zone. So we take the current * number of slab pages and shake the slab until it is reduced * by the same nr_pages that we used for reclaiming unmapped * pages. * * Note that shrink_slab will free memory on all zones and may * take a long time. */ while (shrink_slab(sc.nr_scanned, gfp_mask, order) && zone_page_state(zone, NR_SLAB_RECLAIMABLE) > slab_reclaimable - nr_pages) ; /* * Update nr_reclaimed by the number of slab pages we * reclaimed from this zone. */ nr_reclaimed += slab_reclaimable - zone_page_state(zone, NR_SLAB_RECLAIMABLE); } p->reclaim_state = NULL; current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE); return nr_reclaimed >= nr_pages; } int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order) { cpumask_t mask; int node_id; /* * Zone reclaim reclaims unmapped file backed pages and * slab pages if we are over the defined limits. * * A small portion of unmapped file backed pages is needed for * file I/O otherwise pages read by file I/O will be immediately * thrown out if the zone is overallocated. So we do not reclaim * if less than a specified percentage of the zone is used by * unmapped file backed pages. */ if (zone_page_state(zone, NR_FILE_PAGES) - zone_page_state(zone, NR_FILE_MAPPED) <= zone->min_unmapped_pages && zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages) return 0; /* * Avoid concurrent zone reclaims, do not reclaim in a zone that does * not have reclaimable pages and if we should not delay the allocation * then do not scan. */ if (!(gfp_mask & __GFP_WAIT) || zone->all_unreclaimable || atomic_read(&zone->reclaim_in_progress) > 0 || (current->flags & PF_MEMALLOC)) return 0; /* * Only run zone reclaim on the local zone or on zones that do not * have associated processors. This will favor the local processor * over remote processors and spread off node memory allocations * as wide as possible. */ node_id = zone_to_nid(zone); mask = node_to_cpumask(node_id); if (!cpus_empty(mask) && node_id != numa_node_id()) return 0; return __zone_reclaim(zone, gfp_mask, order); } #endif
philenotfound/belkin-wemo-linux-2.6.21.x
mm/vmscan.c
C
gpl-2.0
48,319
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. 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. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { MemoryInputStream::MemoryInputStream (const void* sourceData, size_t sourceDataSize, bool keepCopy) : data (sourceData), dataSize (sourceDataSize) { if (keepCopy) { internalCopy = MemoryBlock (sourceData, sourceDataSize); data = internalCopy.getData(); } } MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData, bool keepCopy) : data (sourceData.getData()), dataSize (sourceData.getSize()) { if (keepCopy) { internalCopy = sourceData; data = internalCopy.getData(); } } MemoryInputStream::MemoryInputStream (MemoryBlock&& source) : internalCopy (std::move (source)) { data = internalCopy.getData(); } MemoryInputStream::~MemoryInputStream() { } int64 MemoryInputStream::getTotalLength() { return (int64) dataSize; } int MemoryInputStream::read (void* buffer, int howMany) { jassert (buffer != nullptr && howMany >= 0); if (howMany <= 0 || position >= dataSize) return 0; auto num = jmin ((size_t) howMany, dataSize - position); if (num > 0) { memcpy (buffer, addBytesToPointer (data, position), num); position += num; } return (int) num; } bool MemoryInputStream::isExhausted() { return position >= dataSize; } bool MemoryInputStream::setPosition (const int64 pos) { position = (size_t) jlimit ((int64) 0, (int64) dataSize, pos); return true; } int64 MemoryInputStream::getPosition() { return (int64) position; } void MemoryInputStream::skipNextBytes (int64 numBytesToSkip) { if (numBytesToSkip > 0) setPosition (getPosition() + numBytesToSkip); } //============================================================================== //============================================================================== #if JUCE_UNIT_TESTS class MemoryStreamTests : public UnitTest { public: MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream", UnitTestCategories::streams) {} void runTest() override { beginTest ("Basics"); Random r = getRandom(); int randomInt = r.nextInt(); int64 randomInt64 = r.nextInt64(); double randomDouble = r.nextDouble(); String randomString (createRandomWideCharString (r)); MemoryOutputStream mo; mo.writeInt (randomInt); mo.writeIntBigEndian (randomInt); mo.writeCompressedInt (randomInt); mo.writeString (randomString); mo.writeInt64 (randomInt64); mo.writeInt64BigEndian (randomInt64); mo.writeDouble (randomDouble); mo.writeDoubleBigEndian (randomDouble); MemoryInputStream mi (mo.getData(), mo.getDataSize(), false); expect (mi.readInt() == randomInt); expect (mi.readIntBigEndian() == randomInt); expect (mi.readCompressedInt() == randomInt); expectEquals (mi.readString(), randomString); expect (mi.readInt64() == randomInt64); expect (mi.readInt64BigEndian() == randomInt64); expect (mi.readDouble() == randomDouble); expect (mi.readDoubleBigEndian() == randomDouble); const MemoryBlock data ("abcdefghijklmnopqrstuvwxyz", 26); MemoryInputStream stream (data, true); beginTest ("Read"); expectEquals (stream.getPosition(), (int64) 0); expectEquals (stream.getTotalLength(), (int64) data.getSize()); expectEquals (stream.getNumBytesRemaining(), stream.getTotalLength()); expect (! stream.isExhausted()); size_t numBytesRead = 0; MemoryBlock readBuffer (data.getSize()); while (numBytesRead < data.getSize()) { numBytesRead += (size_t) stream.read (&readBuffer[numBytesRead], 3); expectEquals (stream.getPosition(), (int64) numBytesRead); expectEquals (stream.getNumBytesRemaining(), (int64) (data.getSize() - numBytesRead)); expect (stream.isExhausted() == (numBytesRead == data.getSize())); } expectEquals (stream.getPosition(), (int64) data.getSize()); expectEquals (stream.getNumBytesRemaining(), (int64) 0); expect (stream.isExhausted()); expect (readBuffer == data); beginTest ("Skip"); stream.setPosition (0); expectEquals (stream.getPosition(), (int64) 0); expectEquals (stream.getTotalLength(), (int64) data.getSize()); expectEquals (stream.getNumBytesRemaining(), stream.getTotalLength()); expect (! stream.isExhausted()); numBytesRead = 0; const int numBytesToSkip = 5; while (numBytesRead < data.getSize()) { stream.skipNextBytes (numBytesToSkip); numBytesRead += numBytesToSkip; numBytesRead = std::min (numBytesRead, data.getSize()); expectEquals (stream.getPosition(), (int64) numBytesRead); expectEquals (stream.getNumBytesRemaining(), (int64) (data.getSize() - numBytesRead)); expect (stream.isExhausted() == (numBytesRead == data.getSize())); } expectEquals (stream.getPosition(), (int64) data.getSize()); expectEquals (stream.getNumBytesRemaining(), (int64) 0); expect (stream.isExhausted()); } static String createRandomWideCharString (Random& r) { juce_wchar buffer [50] = { 0 }; for (int i = 0; i < numElementsInArray (buffer) - 1; ++i) { if (r.nextBool()) { do { buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1)); } while (! CharPointer_UTF16::canRepresent (buffer[i])); } else buffer[i] = (juce_wchar) (1 + r.nextInt (0xff)); } return CharPointer_UTF32 (buffer); } }; static MemoryStreamTests memoryInputStreamUnitTests; #endif } // namespace juce
liamlacey/Shuttertone
JuceLibraryCode/modules/juce_core/streams/juce_MemoryInputStream.cpp
C++
gpl-2.0
7,049
/* Install given floating-point environment and raise exceptions. Copyright (C) 2000 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by David Huggins-Daines <dhd@debian.org>, 2000 The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <fenv.h> #include <string.h> int feupdateenv (const fenv_t *envp) { union { unsigned long long l; unsigned int sw[2]; } s; fenv_t temp; /* Get the current exception status */ __asm__ ("fstd %%fr0,0(%1) \n\t" "fldd 0(%1),%%fr0 \n\t" : "=m" (s.l) : "r" (&s.l)); memcpy(&temp, envp, sizeof(fenv_t)); /* Currently raised exceptions not cleared */ temp.__status_word |= s.sw[0] & (FE_ALL_EXCEPT << 27); /* Install new environment. */ fesetenv (&temp); /* Success. */ return 0; }
ystk/debian-eglibc
ports/sysdeps/hppa/fpu/feupdateenv.c
C
gpl-2.0
1,504
# (c) 2017 - Copyright Red Hat Inc # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # version 2 as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # Authors: # Pierre-Yves Chibon <pingou@pingoured.fr> """This test module contains tests for the migration system.""" import os import subprocess import unittest REPO_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) class TestAlembic(unittest.TestCase): """This test class contains tests pertaining to alembic.""" def test_alembic_history(self): """Enforce a linear alembic history. This test runs the `alembic history | grep ' (head), '` command, and ensure it returns only one line. """ proc1 = subprocess.Popen( ["alembic", "history"], cwd=REPO_PATH, stdout=subprocess.PIPE ) proc2 = subprocess.Popen( ["grep", " (head), "], stdin=proc1.stdout, stdout=subprocess.PIPE ) stdout = proc2.communicate()[0] stdout = stdout.strip().split(b"\n") self.assertEqual(len(stdout), 1) proc1.communicate()
release-monitoring/anitya
anitya/tests/test_alembic.py
Python
gpl-2.0
1,640
import pybedtools import os testdir = os.path.dirname(__file__) test_tempdir = os.path.join(os.path.abspath(testdir), 'tmp') unwriteable = os.path.join(os.path.abspath(testdir), 'unwriteable') def setup(): if not os.path.exists(test_tempdir): os.system('mkdir -p %s' % test_tempdir) pybedtools.set_tempdir(test_tempdir) def teardown(): if os.path.exists(test_tempdir): os.system('rm -r %s' % test_tempdir) pybedtools.cleanup()
jos4uke/getSeqFlankBlatHit
lib/python2.7/site-packages/pybedtools/test/tfuncs.py
Python
gpl-2.0
462
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2006 Donald N. Allingham # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # $Id$ __all__ = ["LinkBox"] #------------------------------------------------------------------------- # # Standard python modules # #------------------------------------------------------------------------- import logging _LOG = logging.getLogger(".widgets.linkbox") #------------------------------------------------------------------------- # # GTK/Gnome modules # #------------------------------------------------------------------------- from gi.repository import GObject from gi.repository import Gtk #------------------------------------------------------------------------- # # LinkBox class # #------------------------------------------------------------------------- class LinkBox(Gtk.HBox): def __init__(self, link, button): GObject.GObject.__init__(self) self.set_spacing(6) self.pack_start(link, False, True, 0) if button: self.pack_start(button, False, True, 0) self.show()
Forage/Gramps
gramps/gui/widgets/linkbox.py
Python
gpl-2.0
1,754
/* Copyright_License { Top Hat Soaring Glide Computer - http://www.tophatsoaring.org/ Copyright (C) 2000-2016 The Top Hat Soaring Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "ConditionMonitors.hpp" #include "ConditionMonitorAATTime.hpp" #include "ConditionMonitorFinalGlide.hpp" #include "ConditionMonitorGlideTerrain.hpp" #include "ConditionMonitorLandableReachable.hpp" #include "ConditionMonitorSunset.hpp" #include "ConditionMonitorWind.hpp" static ConditionMonitorWind cm_wind; static ConditionMonitorFinalGlide cm_finalglide; static ConditionMonitorSunset cm_sunset; static ConditionMonitorAATTime cm_aattime; static ConditionMonitorGlideTerrain cm_glideterrain; static ConditionMonitorLandableReachable cm_landablereachable; void ConditionMonitorsUpdate(const NMEAInfo &basic, const DerivedInfo &calculated, const ComputerSettings &settings) { cm_wind.Update(basic, calculated, settings); cm_finalglide.Update(basic, calculated, settings); cm_sunset.Update(basic, calculated, settings); cm_aattime.Update(basic, calculated, settings); cm_glideterrain.Update(basic, calculated, settings); cm_landablereachable.Update(basic, calculated, settings); }
rdunning0823/tophat
src/Computer/ConditionMonitor/ConditionMonitors.cpp
C++
gpl-2.0
1,954
/* * Automatically generated C config: don't edit * Linux/arm 3.0.36 Kernel Configuration */ #define CONFIG_RING_BUFFER 1 #define CONFIG_NF_CONNTRACK_H323 1 #define CONFIG_SCSI_DMA 1 #define CONFIG_SND_RK29_SOC_I2S 1 #define CONFIG_RTC_DRV_WM831X 1 #define CONFIG_INPUT_KEYBOARD 1 #define CONFIG_RFS_ACCEL 1 #define CONFIG_IP_NF_TARGET_REDIRECT 1 #define CONFIG_CRC32 1 #define CONFIG_I2C_BOARDINFO 1 #define CONFIG_NF_NAT_PROTO_SCTP 1 #define CONFIG_HAVE_AOUT 1 #define CONFIG_MFD_WM831X_I2C 1 #define CONFIG_VFP 1 #define CONFIG_IR_JVC_DECODER 1 #define CONFIG_AEABI 1 #define CONFIG_APANIC 1 #define CONFIG_CPU_FREQ_GOV_CONSERVATIVE 1 #define CONFIG_HIGH_RES_TIMERS 1 #define CONFIG_BLK_DEV_DM 1 #define CONFIG_IP_MULTIPLE_TABLES 1 #define CONFIG_FLATMEM_MANUAL 1 #define CONFIG_BT_RFCOMM 1 #define CONFIG_EXT3_DEFAULTS_TO_ORDERED 1 #define CONFIG_HID_ROCCAT_PYRA 1 #define CONFIG_INOTIFY_USER 1 #define CONFIG_NF_CONNTRACK_NETBIOS_NS 1 #define CONFIG_MODULE_FORCE_UNLOAD 1 #define CONFIG_CPU_FREQ_GOV_ONDEMAND 1 #define CONFIG_DEINTERLACE 1 #define CONFIG_EXPERIMENTAL 1 #define CONFIG_PPP_SYNC_TTY 1 #define CONFIG_ARCH_SUSPEND_POSSIBLE 1 #define CONFIG_RC_CORE 1 #define CONFIG_ARM_UNWIND 1 #define CONFIG_HID_ROCCAT_KOVAPLUS 1 #define CONFIG_I2C3_CONTROLLER_RK30 1 #define CONFIG_NETFILTER_XT_MATCH_HELPER 1 #define CONFIG_SSB_POSSIBLE 1 #define CONFIG_NF_NAT_SIP 1 #define CONFIG_MTD_RKNAND 1 #define CONFIG_NETFILTER_XT_MATCH_STATISTIC 1 #define CONFIG_UART3_RK29 1 #define CONFIG_MTD_CMDLINE_PARTS 1 #define CONFIG_NET_SCH_FIFO 1 #define CONFIG_FSNOTIFY 1 #define CONFIG_STP 1 #define CONFIG_MFD_TPS65910 1 #define CONFIG_INET6_TUNNEL 1 #define CONFIG_NF_CONNTRACK_SIP 1 #define CONFIG_CRYPTO_MANAGER_DISABLE_TESTS 1 #define CONFIG_SND_RK29_SOC_RT3261 1 #define CONFIG_HAVE_KERNEL_LZMA 1 #define CONFIG_DEFAULT_SECURITY_DAC 1 #define CONFIG_FIB_RULES 1 #define CONFIG_HID_ACRUX_FF 1 #define CONFIG_VIDEO_RK29_DIGITALZOOM_IPP_ON 1 #define CONFIG_RT_GROUP_SCHED 1 #define CONFIG_HID_EMS_FF 1 #define CONFIG_KTIME_SCALAR 1 #define CONFIG_IP6_NF_MANGLE 1 #define CONFIG_LCDC1_RK30 1 #define CONFIG_IPV6 1 #define CONFIG_USB_SERIAL_QUALCOMM 1 #define CONFIG_CRYPTO_AEAD 1 #define CONFIG_DEFAULT_TCP_CONG "cubic" #define CONFIG_UEVENT_HELPER_PATH "" #define CONFIG_USB_DEVICEFS 1 #define CONFIG_SND_RK29_CODEC_SOC_SLAVE 1 #define CONFIG_DEVTMPFS 1 #define CONFIG_TOUCHSCREEN_GT82X_IIC 1 #define CONFIG_NF_NAT_PROTO_GRE 1 #define CONFIG_ANDROID_BINDER_IPC 1 #define CONFIG_IP6_NF_TARGET_REJECT 1 #define CONFIG_IR_NEC_DECODER 1 #define CONFIG_HOTPLUG_CPU 1 #define CONFIG_WLAN 1 #define CONFIG_DEFAULT_MESSAGE_LOGLEVEL 4 #define CONFIG_HAVE_ARM_SCU 1 #define CONFIG_BLK_DEV_BSG 1 #define CONFIG_I2C0_CONTROLLER_RK30 1 #define CONFIG_NETFILTER_XT_MATCH_QUOTA2_LOG 1 #define CONFIG_I2C2_CONTROLLER_RK30 1 #define CONFIG_SOC_CAMERA_HI704 1 #define CONFIG_XFRM_IPCOMP 1 #define CONFIG_CRYPTO_RNG2 1 #define CONFIG_NETFILTER_NETLINK_QUEUE 1 #define CONFIG_TUN 1 #define CONFIG_BATTERY_RK30_AC_CHARGE 1 #define CONFIG_FIQ_DEBUGGER_CONSOLE 1 #define CONFIG_TREE_PREEMPT_RCU 1 #define CONFIG_DM_CRYPT 1 #define CONFIG_HAVE_PROC_CPU 1 #define CONFIG_HID_BELKIN 1 #define CONFIG_VIDEO_IR_I2C 1 #define CONFIG_SND_RK_SOC_I2S2_2CH 1 #define CONFIG_WIRELESS_EXT_SYSFS 1 #define CONFIG_USB_SERIAL_OPTION 1 #define CONFIG_HID_ACRUX 1 #define CONFIG_BT_AUTOSLEEP 1 #define CONFIG_USB 1 #define CONFIG_SWITCH_GPIO 1 #define CONFIG_CRYPTO_HMAC 1 #define CONFIG_HID_ROCCAT_KONEPLUS 1 #define CONFIG_BP_AUTO_MT6229 1 #define CONFIG_BRANCH_PROFILE_NONE 1 #define CONFIG_IP6_NF_TARGET_LOG 1 #define CONFIG_IP_NF_ARPTABLES 1 #define CONFIG_USB_SERIAL_GENERIC 1 #define CONFIG_HID_CHERRY 1 #define CONFIG_I2C0_RK30 1 #define CONFIG_HID_SUNPLUS 1 #define CONFIG_HID_PICOLCD 1 #define CONFIG_BCMA_POSSIBLE 1 #define CONFIG_FORCE_MAX_ZONEORDER 11 #define CONFIG_SND_SOC 1 #define CONFIG_CAN_PM_TRACE 1 #define CONFIG_MEDIA_TUNER_XC5000_MODULE 1 #define CONFIG_I2C3_RK30 1 #define CONFIG_PRINTK 1 #define CONFIG_FIQ_GLUE 1 #define CONFIG_NF_CONNTRACK_PROC_COMPAT 1 #define CONFIG_WIFI_CONTROL_FUNC 1 #define CONFIG_TIMERFD 1 #define CONFIG_HID_THRUSTMASTER 1 #define CONFIG_RK_PL330_DMA 1 #define CONFIG_TRACEPOINTS 1 #define CONFIG_MTD_CFI_I2 1 #define CONFIG_CRYPTO_AUTHENC 1 #define CONFIG_NET_EMATCH_STACK 32 #define CONFIG_BOUNCE 1 #define CONFIG_SHMEM 1 #define CONFIG_MIGRATION 1 #define CONFIG_MTD 1 #define CONFIG_MMC_BLOCK_MINORS 8 #define CONFIG_DWC_CONN_EN 1 #define CONFIG_DEVTMPFS_MOUNT 1 #define CONFIG_CRYPTO_DES 1 #define CONFIG_ENABLE_MUST_CHECK 1 #define CONFIG_NLS_CODEPAGE_437 1 #define CONFIG_MTD_NAND_IDS 1 #define CONFIG_NET_CLS_U32 1 #define CONFIG_FIQ_DEBUGGER 1 #define CONFIG_SOC_CAMERA_GT2005 1 #define CONFIG_ARM_GIC 1 #define CONFIG_SERIO 1 #define CONFIG_SCHEDSTATS 1 #define CONFIG_RTC_INTF_SYSFS 1 #define CONFIG_NET_EMATCH_U32 1 #define CONFIG_BLK_DEV_INITRD 1 #define CONFIG_COMPASS_AK8975 1 #define CONFIG_REGULATOR_WM831X 1 #define CONFIG_NF_CONNTRACK_SANE 1 #define CONFIG_NF_CT_PROTO_DCCP 1 #define CONFIG_ZLIB_INFLATE 1 #define CONFIG_MEDIA_TUNER_QT1010_MODULE 1 #define CONFIG_GPIO_WM831X 1 #define CONFIG_USB_G_ANDROID 1 #define CONFIG_ARM_ERRATA_764369 1 #define CONFIG_CRYPTO_TWOFISH_COMMON 1 #define CONFIG_LOGO_LINUX_CLUT224 1 #define CONFIG_RTC_INTF_PROC 1 #define CONFIG_CPU_IDLE_GOV_MENU 1 #define CONFIG_STACKTRACE_SUPPORT 1 #define CONFIG_USB_DEVICE_CLASS 1 #define CONFIG_ANDROID_TIMED_GPIO 1 #define CONFIG_ARM 1 #define CONFIG_ARM_L1_CACHE_SHIFT 5 #define CONFIG_BT_RFCOMM_TTY 1 #define CONFIG_DISPLAY_SUPPORT 1 #define CONFIG_VIDEO_RK29_WORK_IPP 1 #define CONFIG_NETFILTER_XT_MATCH_STRING 1 #define CONFIG_INPUT_TABLET 1 #define CONFIG_IP_NF_TARGET_LOG 1 #define CONFIG_MEDIA_TUNER_MAX2165_MODULE 1 #define CONFIG_HAS_WAKELOCK 1 #define CONFIG_LOGO 1 #define CONFIG_USB_STORAGE 1 #define CONFIG_STANDALONE 1 #define CONFIG_CPU_FREQ_GOV_PERFORMANCE 1 #define CONFIG_IR_LIRC_CODEC 1 #define CONFIG_THREE_FB_BUFFER 1 #define CONFIG_MMC_EMBEDDED_SDIO 1 #define CONFIG_ARCH_HAS_CPUFREQ 1 #define CONFIG_I2C1_CONTROLLER_RK30 1 #define CONFIG_I2C2_RK30 1 #define CONFIG_ASHMEM 1 #define CONFIG_BLOCK 1 #define CONFIG_HAVE_IDE 1 #define CONFIG_HID_APPLE 1 #define CONFIG_MEDIA_TUNER_TDA827X_MODULE 1 #define CONFIG_INIT_ENV_ARG_LIMIT 32 #define CONFIG_IP_NF_ARP_MANGLE 1 #define CONFIG_GENERIC_GPIO 1 #define CONFIG_NF_CONNTRACK_PPTP 1 #define CONFIG_BUG 1 #define CONFIG_CONTEXT_SWITCH_TRACER 1 #define CONFIG_SND_I2S_DMA_EVENT_STATIC 1 #define CONFIG_PANTHERLORD_FF 1 #define CONFIG_PM 1 #define CONFIG_NF_CONNTRACK_IRC 1 #define CONFIG_SWITCH 1 #define CONFIG_DEVKMEM 1 #define CONFIG_PPP_DEFLATE 1 #define CONFIG_TEXTSEARCH_KMP 1 #define CONFIG_RK_SN 1 #define CONFIG_VT 1 #define CONFIG_USB_NET_NET1080 1 #define CONFIG_NETFILTER_XT_TARGET_CLASSIFY 1 #define CONFIG_SPLIT_PTLOCK_CPUS 4 #define CONFIG_BT_SCO 1 #define CONFIG_POWER_SUPPLY 1 #define CONFIG_CPU_CACHE_VIPT 1 #define CONFIG_NETFILTER_XT_TARGET_NFQUEUE 1 #define CONFIG_V4L_USB_DRIVERS 1 #define CONFIG_WEXT_CORE 1 #define CONFIG_NLS 1 #define CONFIG_USB_GADGET_DWC_OTG 1 #define CONFIG_HID_MAGICMOUSE 1 #define CONFIG_MFD_SUPPORT 1 #define CONFIG_IP_ADVANCED_ROUTER 1 #define CONFIG_ENABLE_WARN_DEPRECATED 1 #define CONFIG_MEDIA_TUNER_TDA18271_MODULE 1 #define CONFIG_IP6_NF_IPTABLES 1 #define CONFIG_CPU_FREQ_GOV_USERSPACE 1 #define CONFIG_EVENT_TRACING 1 #define CONFIG_HID_KEYTOUCH 1 #define CONFIG_HID_CYPRESS 1 #define CONFIG_NLS_ISO8859_1 1 #define CONFIG_CRYPTO_WORKQUEUE 1 #define CONFIG_HID_KENSINGTON 1 #define CONFIG_CPU_FREQ_TABLE 1 #define CONFIG_TEXTSEARCH_BM 1 #define CONFIG_BT_HCIUART_LL 1 #define CONFIG_HID_ZYDACRON 1 #define CONFIG_PPP_MPPE 1 #define CONFIG_INPUT_KEYRESET 1 #define CONFIG_USB_NET_SR9700 1 #define CONFIG_RFKILL 1 #define CONFIG_NETDEVICES 1 #define CONFIG_NET_KEY 1 #define CONFIG_IOSCHED_DEADLINE 1 #define CONFIG_USB_SERIAL_USI 1 #define CONFIG_CGROUP_FREEZER 1 #define CONFIG_CPU_TLB_V7 1 #define CONFIG_EVENTFD 1 #define CONFIG_IPV6_SIT 1 #define CONFIG_XFRM 1 #define CONFIG_DEFCONFIG_LIST "/lib/modules/$UNAME_RELEASE/.config" #define CONFIG_IPV6_MULTIPLE_TABLES 1 #define CONFIG_USB_ANNOUNCE_NEW_DEVICES 1 #define CONFIG_IP_NF_TARGET_MASQUERADE 1 #define CONFIG_NF_CONNTRACK_BROADCAST 1 #define CONFIG_IR_RC5_SZ_DECODER 1 #define CONFIG_PROC_PAGE_MONITOR 1 #define CONFIG_NF_NAT_PROTO_DCCP 1 #define CONFIG_USB_VIDEO_CLASS_INPUT_EVDEV 1 #define CONFIG_SDMMC0_RK29_SDCARD_DET_FROM_GPIO 1 #define CONFIG_ANDROID_LOW_MEMORY_KILLER 1 #define CONFIG_ARCH_HAS_CPU_IDLE_WAIT 1 #define CONFIG_GREENASIA_FF 1 #define CONFIG_SND_RK29_SOC_I2S_8CH 1 #define CONFIG_SOC_CAMERA_HI253 1 #define CONFIG_PHONET 1 #define CONFIG_SCSI_WAIT_SCAN_MODULE 1 #define CONFIG_BACKLIGHT_CLASS_DEVICE 1 #define CONFIG_NF_DEFRAG_IPV4 1 #define CONFIG_SELECT_MEMORY_MODEL 1 #define CONFIG_HID_LCPOWER 1 #define CONFIG_MMC_UNSAFE_RESUME 1 #define CONFIG_HAVE_ARCH_PFN_VALID 1 #define CONFIG_CPU_COPY_V6 1 #define CONFIG_PM_DEBUG 1 #define CONFIG_NETFILTER_ADVANCED 1 #define CONFIG_CRYPTO_DEFLATE 1 #define CONFIG_IPV6_ROUTER_PREF 1 #define CONFIG_SPI_FPGA_GPIO_NUM 0 #define CONFIG_NETFILTER_NETLINK_LOG 1 #define CONFIG_HAVE_DYNAMIC_FTRACE 1 #define CONFIG_MAGIC_SYSRQ 1 #define CONFIG_VIDEO_RKCIF_WORK_ONEFRAME 1 #define CONFIG_NETFILTER_XT_MATCH_MARK 1 #define CONFIG_HAVE_ARM_TWD 1 #define CONFIG_IP_NF_MANGLE 1 #define CONFIG_DEFAULT_CFQ 1 #define CONFIG_DUAL_LCDC_DUAL_DISP_IN_KERNEL 1 #define CONFIG_INET6_XFRM_MODE_TUNNEL 1 #define CONFIG_MEDIA_SUPPORT 1 #define CONFIG_DEBUG_BUGVERBOSE 1 #define CONFIG_IP_NF_FILTER 1 #define CONFIG_HID_ZEROPLUS 1 #define CONFIG_EXT3_FS 1 #define CONFIG_NETFILTER_XT_MATCH_LENGTH 1 #define CONFIG_FAT_FS 1 #define CONFIG_TEXTSEARCH_FSM 1 #define CONFIG_HIGHMEM 1 #define CONFIG_IP6_NF_RAW 1 #define CONFIG_INET_TUNNEL 1 #define CONFIG_WM8326_VBAT_LOW_DETECTION 1 #define CONFIG_MMC_BLOCK_BOUNCE 1 #define CONFIG_GENERIC_CLOCKEVENTS 1 #define CONFIG_IOSCHED_CFQ 1 #define CONFIG_MFD_CORE 1 #define CONFIG_CPU_CP15_MMU 1 #define CONFIG_STOP_MACHINE 1 #define CONFIG_CPU_FREQ 1 #define CONFIG_USB_GSPCA_MODULE 1 #define CONFIG_DUMMY_CONSOLE 1 #define CONFIG_NLS_ASCII 1 #define CONFIG_SDMMC0_RK29 1 #define CONFIG_TRACE_IRQFLAGS_SUPPORT 1 #define CONFIG_USB_NET_CDC_SUBSET 1 #define CONFIG_NETFILTER_XT_MATCH_CONNMARK 1 #define CONFIG_SND_USB 1 #define CONFIG_LOGIG940_FF 1 #define CONFIG_RD_GZIP 1 #define CONFIG_HAVE_REGS_AND_STACK_ACCESS_API 1 #define CONFIG_THRUSTMASTER_FF 1 #define CONFIG_LBDAF 1 #define CONFIG_BP_AUTO 1 #define CONFIG_HID_ROCCAT 1 #define CONFIG_INET_XFRM_MODE_TRANSPORT 1 #define CONFIG_CRYPTO_MD5 1 #define CONFIG_MEDIA_TUNER_TEA5767_MODULE 1 #define CONFIG_HAVE_GENERIC_HARDIRQS 1 #define CONFIG_BINFMT_ELF 1 #define CONFIG_SCSI_PROC_FS 1 #define CONFIG_HOTPLUG 1 #define CONFIG_INET6_AH 1 #define CONFIG_CPU_CP15 1 #define CONFIG_USB_SERIAL 1 #define CONFIG_I2C_RK30 1 #define CONFIG_NETFILTER_XT_MARK 1 #define CONFIG_NETFILTER_XTABLES 1 #define CONFIG_RESOURCE_COUNTERS 1 #define CONFIG_SOC_CAMERA_GC0308 1 #define CONFIG_PM_SLEEP_SMP 1 #define CONFIG_CRYPTO_HW 1 #define CONFIG_ION 1 #define CONFIG_HID_GREENASIA 1 #define CONFIG_EXPANDED_GPIO_IRQ_NUM 0 #define CONFIG_HARDIRQS_SW_RESEND 1 #define CONFIG_BACKLIGHT_RK29_BL 1 #define CONFIG_HID_ROCCAT_COMMON 1 #define CONFIG_NET_ACT_GACT 1 #define CONFIG_HID_GYRATION 1 #define CONFIG_MACH_RK3066_SDK 1 #define CONFIG_VIDEO_RKCIF_WORK_SIMUL_OFF 1 #define CONFIG_NETFILTER_XT_TARGET_TPROXY 1 #define CONFIG_EARLYSUSPEND 1 #define CONFIG_USB_ACM 1 #define CONFIG_CRC16 1 #define CONFIG_USB_NET_AX8817X 1 #define CONFIG_GENERIC_CALIBRATE_DELAY 1 #define CONFIG_NET_CLS 1 #define CONFIG_CPU_HAS_PMU 1 #define CONFIG_ARCH_REQUIRE_GPIOLIB 1 #define CONFIG_TMPFS 1 #define CONFIG_LS_ISL29023 1 #define CONFIG_ANON_INODES 1 #define CONFIG_SUSPEND_SYNC_WORKQUEUE 1 #define CONFIG_FUTEX 1 #define CONFIG_JOYSTICK_XPAD_FF 1 #define CONFIG_VMSPLIT_3G 1 #define CONFIG_RTC_HCTOSYS 1 #define CONFIG_LCDC_RK30 1 #define CONFIG_USB_HID 1 #define CONFIG_RTL8192CU 1 #define CONFIG_ANDROID 1 #define CONFIG_NET_SCH_INGRESS 1 #define CONFIG_RK29_VPU_MODULE 1 #define CONFIG_NF_CONNTRACK_EVENTS 1 #define CONFIG_IPV6_NDISC_NODETYPE 1 #define CONFIG_CGROUP_SCHED 1 #define CONFIG_CRYPTO_PCOMP2 1 #define CONFIG_NF_CONNTRACK_FTP 1 #define CONFIG_MODULES 1 #define CONFIG_IP_NF_MATCH_ECN 1 #define CONFIG_CPU_HAS_ASID 1 #define CONFIG_USB_GADGET 1 #define CONFIG_MEDIA_TUNER_MXL5005S_MODULE 1 #define CONFIG_SOUND 1 #define CONFIG_MEDIA_TUNER_TDA9887_MODULE 1 #define CONFIG_UNIX 1 #define CONFIG_HAVE_CLK 1 #define CONFIG_CRYPTO_HASH2 1 #define CONFIG_DEFAULT_HOSTNAME "(none)" #define CONFIG_CPU_FREQ_GOV_POWERSAVE 1 #define CONFIG_XPS 1 #define CONFIG_INET_ESP 1 #define CONFIG_HID_QUANTA 1 #define CONFIG_NF_CONNTRACK_IPV6 1 #define CONFIG_MD 1 #define CONFIG_CRYPTO_ALGAPI 1 #define CONFIG_RK_HDMI_CTL_CODEC 1 #define CONFIG_BRIDGE 1 #define CONFIG_MEDIA_TUNER 1 #define CONFIG_TABLET_USB_GTCO 1 #define CONFIG_MISC_DEVICES 1 #define CONFIG_INPUT_UINPUT 1 #define CONFIG_MEDIA_TUNER_SIMPLE_MODULE 1 #define CONFIG_UART0_DMA_RK29 0 #define CONFIG_MTD_CFI_I1 1 #define CONFIG_NF_NAT 1 #define CONFIG_CPU_IDLE 1 #define CONFIG_DWC_OTG_BOTH_HOST_SLAVE 1 #define CONFIG_REGULATOR 1 #define CONFIG_FAIR_GROUP_SCHED 1 #define CONFIG_RK_HEADSET_IRQ_HOOK_ADC_DET 1 #define CONFIG_SND_RK29_SOC 1 #define CONFIG_CRYPTO_HASH 1 #define CONFIG_EFI_PARTITION 1 #define CONFIG_GS_MMA7660 1 #define CONFIG_LOG_BUF_SHIFT 19 #define CONFIG_SOC_CAMERA_GC2035 1 #define CONFIG_EXTRA_FIRMWARE "" #define CONFIG_CACHE_L2X0 1 #define CONFIG_CPU_FREQ_GOV_INTERACTIVE 1 #define CONFIG_VIRT_TO_BUS 1 #define CONFIG_VFAT_FS 1 #define CONFIG_UART1_CTS_RTS_RK29 1 #define CONFIG_CPU_RMAP 1 #define CONFIG_BLK_DEV_LOOP 1 #define CONFIG_WAKELOCK 1 #define CONFIG_NF_NAT_IRC 1 #define CONFIG_MEDIA_TUNER_CUSTOMISE 1 #define CONFIG_MEDIA_TUNER_XC2028_MODULE 1 #define CONFIG_INPUT_MISC 1 #define CONFIG_CPU_PABRT_V7 1 #define CONFIG_SOC_CAMERA 1 #define CONFIG_SUSPEND 1 #define CONFIG_CRYPTO_CBC 1 #define CONFIG_DDR_TYPE_DDR3_DEFAULT 1 #define CONFIG_UART1_RK29 1 #define CONFIG_RTC_CLASS 1 #define CONFIG_USB20_HOST 1 #define CONFIG_CPU_PM 1 #define CONFIG_HDMI_RK30 1 #define CONFIG_ARCH_RK30 1 #define CONFIG_HAVE_FUNCTION_TRACER 1 #define CONFIG_NF_NAT_TFTP 1 #define CONFIG_OUTER_CACHE 1 #define CONFIG_EXPANDED_GPIO_NUM 0 #define CONFIG_CPU_CACHE_V7 1 #define CONFIG_ZEROPLUS_FF 1 #define CONFIG_CRYPTO_MANAGER2 1 #define CONFIG_USB_GADGET_VBUS_DRAW 2 #define CONFIG_DRAGONRISE_FF 1 #define CONFIG_SLUB 1 #define CONFIG_PM_SLEEP 1 #define CONFIG_I2C 1 #define CONFIG_PPP_MULTILINK 1 #define CONFIG_ES603_PROTOCOL_DRIVER 1 #define CONFIG_UART1_DMA_RK29 0 #define CONFIG_BT_HIDP 1 #define CONFIG_RK_EARLY_PRINTK 1 #define CONFIG_CPU_ABRT_EV7 1 #define CONFIG_WLAN_80211 1 #define CONFIG_VM_EVENT_COUNTERS 1 #define CONFIG_CRYPTO_ECB 1 #define CONFIG_NF_CONNTRACK_AMANDA 1 #define CONFIG_DEBUG_FS 1 #define CONFIG_UART3_CTS_RTS_RK29 1 #define CONFIG_BASE_FULL 1 #define CONFIG_FB_CFB_IMAGEBLIT 1 #define CONFIG_ZLIB_DEFLATE 1 #define CONFIG_GPIO_SYSFS 1 #define CONFIG_FW_LOADER 1 #define CONFIG_KALLSYMS 1 #define CONFIG_RTC_HCTOSYS_DEVICE "rtc0" #define CONFIG_NETFILTER_XT_MATCH_PKTTYPE 1 #define CONFIG_MII 1 #define CONFIG_SIGNALFD 1 #define CONFIG_IP_NF_TARGET_REJECT_SKERR 1 #define CONFIG_SOC_CAMERA_SP0838 1 #define CONFIG_EXT4_FS 1 #define CONFIG_CRYPTO_SHA1 1 #define CONFIG_ARM_DMA_MEM_BUFFERABLE 1 #define CONFIG_SUSPEND_TIME 1 #define CONFIG_IPV6_PRIVACY 1 #define CONFIG_USB_BELKIN 1 #define CONFIG_USB_GADGET_DUALSPEED 1 #define CONFIG_HAS_IOMEM 1 #define CONFIG_PPPOPNS 1 #define CONFIG_KERNEL_LZO 1 #define CONFIG_GENERIC_IRQ_PROBE 1 #define CONFIG_IP_NF_MATCH_TTL 1 #define CONFIG_NETFILTER_XT_TARGET_TRACE 1 #define CONFIG_MTD_MAP_BANK_WIDTH_1 1 #define CONFIG_EPOLL 1 #define CONFIG_SND_PCM 1 #define CONFIG_PM_RUNTIME 1 #define CONFIG_PARTITION_ADVANCED 1 #define CONFIG_RK30_I2C_INSRAM 1 #define CONFIG_IR_SONY_DECODER 1 #define CONFIG_NETFILTER_XT_MATCH_COMMENT 1 #define CONFIG_NET 1 #define CONFIG_INPUT_EVDEV 1 #define CONFIG_SND_JACK 1 #define CONFIG_HAVE_SPARSE_IRQ 1 #define CONFIG_TABLET_USB_WACOM 1 #define CONFIG_HID_DRAGONRISE 1 #define CONFIG_NETFILTER_XT_MATCH_CONNTRACK 1 #define CONFIG_MMC_PARANOID_SD_INIT 1 #define CONFIG_VFPv3 1 #define CONFIG_RFKILL_RK 1 #define CONFIG_USB_NET_CDCETHER 1 #define CONFIG_PACKET 1 #define CONFIG_NETFILTER_XT_MATCH_IPRANGE 1 #define CONFIG_RK30_PWM_REGULATOR 1 #define CONFIG_NF_CONNTRACK_TFTP 1 #define CONFIG_NOP_TRACER 1 #define CONFIG_BACKLIGHT_LCD_SUPPORT 1 #define CONFIG_INET 1 #define CONFIG_PREVENT_FIRMWARE_BUILD 1 #define CONFIG_CRYPTO_TWOFISH 1 #define CONFIG_FREEZER 1 #define CONFIG_BT 1 #define CONFIG_RFKILL_PM 1 #define CONFIG_NET_CLS_ACT 1 #define CONFIG_I2C4_RK30 1 #define CONFIG_HID_WACOM 1 #define CONFIG_RTC_LIB 1 #define CONFIG_NETFILTER_XT_MATCH_POLICY 1 #define CONFIG_HAVE_KPROBES 1 #define CONFIG_CRYPTO_AES 1 #define CONFIG_BATTERY_RK30_ADC_FAC 1 #define CONFIG_GPIOLIB 1 #define CONFIG_EXT4_USE_FOR_EXT23 1 #define CONFIG_BT_HCIUART_H4 1 #define CONFIG_HID_WALTOP 1 #define CONFIG_IP6_NF_TARGET_REJECT_SKERR 1 #define CONFIG_NF_CONNTRACK_MARK 1 #define CONFIG_NETFILTER 1 #define CONFIG_NETFILTER_XT_MATCH_HASHLIMIT 1 #define CONFIG_SENSOR_DEVICE 1 #define CONFIG_USE_GENERIC_SMP_HELPERS 1 #define CONFIG_DVFS 1 #define CONFIG_DWC_OTG 1 #define CONFIG_SERIO_SERPORT 1 #define CONFIG_LIRC 1 #define CONFIG_BT_BNEP 1 #define CONFIG_FB_ROCKCHIP 1 #define CONFIG_INET_XFRM_MODE_TUNNEL 1 #define CONFIG_FIQ_DEBUGGER_CONSOLE_DEFAULT_ENABLE 1 #define CONFIG_PREEMPT_RCU 1 #define CONFIG_NF_NAT_NEEDED 1 #define CONFIG_SERIAL_RK29 1 #define CONFIG_GS_MMA8452 1 #define CONFIG_MEDIA_TUNER_MT2266_MODULE 1 #define CONFIG_LOCKDEP_SUPPORT 1 #define CONFIG_NO_HZ 1 #define CONFIG_RTC_INTF_ALARM 1 #define CONFIG_RK_BOARD_ID 1 #define CONFIG_CPU_FREQ_STAT 1 #define CONFIG_SND_SOC_RT3261 1 #define CONFIG_MTD_BLKDEVS 1 #define CONFIG_VIDEO_CAPTURE_DRIVERS 1 #define CONFIG_INET6_ESP 1 #define CONFIG_BT_HCIBCM4325 1 #define CONFIG_IP6_NF_FILTER 1 #define CONFIG_NEED_DMA_MAP_STATE 1 #define CONFIG_NETFILTER_XT_MATCH_CONNBYTES 1 #define CONFIG_ANDROID_PARANOID_NETWORK 1 #define CONFIG_PAGE_OFFSET 0xC0000000 #define CONFIG_CPU_V7 1 #define CONFIG_GS_LIS3DH 1 #define CONFIG_HID_TWINHAN 1 #define CONFIG_PANIC_TIMEOUT 1 #define CONFIG_ZBOOT_ROM_BSS 0x0 #define CONFIG_INPUT_JOYSTICK 1 #define CONFIG_USB20_HOST_EN 1 #define CONFIG_SMP 1 #define CONFIG_NETFILTER_XT_MATCH_TIME 1 #define CONFIG_HAVE_KERNEL_GZIP 1 #define CONFIG_DM_UEVENT 1 #define CONFIG_NETFILTER_XT_MATCH_MAC 1 #define CONFIG_NETFILTER_XT_TARGET_NFLOG 1 #define CONFIG_GENERIC_ALLOCATOR 1 #define CONFIG_ANDROID_TIMED_OUTPUT 1 #define CONFIG_LIBCRC32C 1 #define CONFIG_CRYPTO_SHA256 1 #define CONFIG_HAVE_FTRACE_MCOUNT_RECORD 1 #define CONFIG_INET_TCP_DIAG 1 #define CONFIG_HID_SONY 1 #define CONFIG_HW_CONSOLE 1 #define CONFIG_DEVMEM 1 #define CONFIG_HID_MONTEREY 1 #define CONFIG_HID_EZKEY 1 #define CONFIG_IOSCHED_NOOP 1 #define CONFIG_LCD_MR13 1 #define CONFIG_JOYSTICK_XPAD_LEDS 1 #define CONFIG_NEON 1 #define CONFIG_DEBUG_KERNEL 1 #define CONFIG_ARCH_RK30XX 1 #define CONFIG_COMPAT_BRK 1 #define CONFIG_LOCALVERSION "+" #define CONFIG_RADIO_ADAPTERS 1 #define CONFIG_MACH_NO_WESTBRIDGE 1 #define CONFIG_DDR_TEST 1 #define CONFIG_CRYPTO 1 #define CONFIG_I2C4_CONTROLLER_RK30 1 #define CONFIG_MTD_RKNAND_BUFFER 1 #define CONFIG_LEDS_GPIO_PLATFORM 1 #define CONFIG_DEFAULT_MMAP_MIN_ADDR 32768 #define CONFIG_MEDIA_TUNER_TDA18218_MODULE 1 #define CONFIG_IP_NF_IPTABLES 1 #define CONFIG_CMDLINE "console=ttyFIQ0 androidboot.console=ttyFIQ0 init=/init" #define CONFIG_HAVE_DMA_API_DEBUG 1 #define CONFIG_REGULATOR_TPS65910 1 #define CONFIG_HID_SAMSUNG 1 #define CONFIG_USB_ARCH_HAS_HCD 1 #define CONFIG_GENERIC_IRQ_SHOW 1 #define CONFIG_IPV6_OPTIMISTIC_DAD 1 #define CONFIG_ALIGNMENT_TRAP 1 #define CONFIG_SCSI_MOD 1 #define CONFIG_CRYPTO_CRC32C 1 #define CONFIG_SERIAL_CORE 1 #define CONFIG_FUSE_FS 1 #define CONFIG_UID16 1 #define CONFIG_EMBEDDED 1 #define CONFIG_HID_MICROSOFT 1 #define CONFIG_HAVE_KRETPROBES 1 #define CONFIG_NF_DEFRAG_IPV6 1 #define CONFIG_VIDEO_DEV 1 #define CONFIG_MFD_WM831X 1 #define CONFIG_PPP_FILTER 1 #define CONFIG_HAS_DMA 1 #define CONFIG_NF_CT_PROTO_SCTP 1 #define CONFIG_BT_L2CAP 1 #define CONFIG_SCSI 1 #define CONFIG_FB_CFB_FILLRECT 1 #define CONFIG_NF_NAT_PPTP 1 #define CONFIG_HID_CHICONY 1 #define CONFIG_HID 1 #define CONFIG_LOGIWII_FF 1 #define CONFIG_USB_ARMLINUX 1 #define CONFIG_CLKDEV_LOOKUP 1 #define CONFIG_KEYS_RK29 1 #define CONFIG_MEDIA_TUNER_TDA8290_MODULE 1 #define CONFIG_MEDIA_TUNER_TDA18212_MODULE 1 #define CONFIG_JBD2 1 #define CONFIG_LCDC0_RK30 1 #define CONFIG_INET6_IPCOMP 1 #define CONFIG_PHYLIB 1 #define CONFIG_IPV6_TUNNEL 1 #define CONFIG_MEDIA_TUNER_MT20XX_MODULE 1 #define CONFIG_FTRACE 1 #define CONFIG_NETFILTER_XT_MATCH_CONNLIMIT 1 #define CONFIG_IP_NF_RAW 1 #define CONFIG_IP_NF_ARPFILTER 1 #define CONFIG_MIGHT_HAVE_CACHE_L2X0 1 #define CONFIG_NETFILTER_XT_MATCH_SOCKET 1 #define CONFIG_HID_TOPSEED 1 #define CONFIG_CLK_SWITCH_TO_32K 1 #define CONFIG_NF_NAT_H323 1 #define CONFIG_HID_A4TECH 1 #define CONFIG_MEDIA_TUNER_MC44S803_MODULE 1 #define CONFIG_BP_AUTO_MU509 1 #define CONFIG_IP_NF_TARGET_NETMAP 1 #define CONFIG_RCU_CPU_STALL_TIMEOUT 60 #define CONFIG_SPI_FPGA_GPIO_IRQ_NUM 0 #define CONFIG_INPUT_FF_MEMLESS 1 #define CONFIG_SOC_RK3066 1 #define CONFIG_UART0_CTS_RTS_RK29 1 #define CONFIG_NF_NAT_AMANDA 1 #define CONFIG_CACHE_PL310 1 #define CONFIG_INET6_XFRM_MODE_TRANSPORT 1 #define CONFIG_CRYPTO_ARC4 1 #define CONFIG_SLHC 1 #define CONFIG_HAVE_SMP 1 #define CONFIG_RGA_RK30 1 #define CONFIG_CRYPTO_MANAGER 1 #define CONFIG_NET_SCH_HTB 1 #define CONFIG_PPP_BSDCOMP 1 #define CONFIG_RT_MUTEXES 1 #define CONFIG_VECTORS_BASE 0xffff0000 #define CONFIG_HID_ORTEK 1 #define CONFIG_NETFILTER_XT_TARGET_MARK 1 #define CONFIG_MEDIA_TUNER_MXL5007T_MODULE 1 #define CONFIG_MMC_BLOCK 1 #define CONFIG_EXPERT 1 #define CONFIG_WIRELESS 1 #define CONFIG_WEXT_PROC 1 #define CONFIG_PERF_USE_VMALLOC 1 #define CONFIG_FAT_DEFAULT_IOCHARSET "iso8859-1" #define CONFIG_FRAME_WARN 1024 #define CONFIG_USB_NET_CDC_NCM 1 #define CONFIG_RCU_CPU_STALL_VERBOSE 1 #define CONFIG_GENERIC_HWEIGHT 1 #define CONFIG_INITRAMFS_SOURCE "" #define CONFIG_GYRO_L3G4200D 1 #define CONFIG_CGROUPS 1 #define CONFIG_MMC 1 #define CONFIG_SDMMC1_RK29 1 #define CONFIG_HID_LOGITECH 1 #define CONFIG_RK_CLOCK_PROC 1 #define CONFIG_STACKTRACE 1 #define CONFIG_PPPOLAC 1 #define CONFIG_APANIC_PLABEL "kpanic" #define CONFIG_VIDEO_RK29 1 #define CONFIG_NETFILTER_XT_TARGET_IDLETIMER 1 #define CONFIG_UART0_RK29 1 #define CONFIG_HAS_IOPORT 1 #define CONFIG_VIDEOBUF_DMA_CONTIG 1 #define CONFIG_CGROUP_CPUACCT 1 #define CONFIG_FB_EARLYSUSPEND 1 #define CONFIG_HZ 100 #define CONFIG_USB20_OTG_EN 1 #define CONFIG_I2C_HELPER_AUTO 1 #define CONFIG_NETFILTER_XT_MATCH_U32 1 #define CONFIG_COMPASS_DEVICE 1 #define CONFIG_GENERIC_LOCKBREAK 1 #define CONFIG_DEFAULT_IOSCHED "cfq" #define CONFIG_TABLET_USB_KBTAB 1 #define CONFIG_IPV6_MIP6 1 #define CONFIG_RK29_IPP_MODULE 1 #define CONFIG_NLATTR 1 #define CONFIG_TCP_CONG_CUBIC 1 #define CONFIG_PM_RUNTIME_CLK 1 #define CONFIG_NR_CPUS 2 #define CONFIG_SUSPEND_FREEZER 1 #define CONFIG_NETFILTER_XT_CONNMARK 1 #define CONFIG_LOGITECH_FF 1 #define CONFIG_HID_KYE 1 #define CONFIG_SYSFS 1 #define CONFIG_INPUT_TOUCHSCREEN 1 #define CONFIG_OUTER_CACHE_SYNC 1 #define CONFIG_ARM_THUMB 1 #define CONFIG_IP_NF_MATCH_AH 1 #define CONFIG_NETFILTER_XT_MATCH_LIMIT 1 #define CONFIG_DWC_OTG_DEFAULT_ID 1 #define CONFIG_ARM_ERRATA_754322 1 #define CONFIG_FB 1 #define CONFIG_TRACING 1 #define CONFIG_CPU_32v7 1 #define CONFIG_ADC 1 #define CONFIG_MSDOS_PARTITION 1 #define CONFIG_RK_DEBUG_UART 2 #define CONFIG_BT_HCIUART 1 #define CONFIG_SND_RK29_SOC_RT5623 1 #define CONFIG_HAVE_OPROFILE 1 #define CONFIG_HAVE_GENERIC_DMA_COHERENT 1 #define CONFIG_CPU_IDLE_GOV_LADDER 1 #define CONFIG_HID_PETALYNX 1 #define CONFIG_NET_ACT_MIRRED 1 #define CONFIG_HAVE_ARCH_KGDB 1 #define CONFIG_NF_CONNTRACK_IPV4 1 #define CONFIG_ZONE_DMA_FLAG 0 #define CONFIG_FIQ_DEBUGGER_NO_SLEEP 1 #define CONFIG_RPS 1 #define CONFIG_USB_NET_ZAURUS 1 #define CONFIG_INET6_XFRM_TUNNEL 1 #define CONFIG_MTD_MAP_BANK_WIDTH_2 1 #define CONFIG_MTD_NAND_RK29XX 1 #define CONFIG_TABLET_USB_ACECAD 1 #define CONFIG_VIDEO_MEDIA 1 #define CONFIG_IP_MULTICAST 1 #define CONFIG_WAKELOCK_STAT 1 #define CONFIG_INPUT_KEYCHORD 1 #define CONFIG_HAS_EARLYSUSPEND 1 #define CONFIG_CPU_32v6K 1 #define CONFIG_DEFAULT_SECURITY "" #define CONFIG_TICK_ONESHOT 1 #define CONFIG_NF_NAT_PROTO_UDPLITE 1 #define CONFIG_CGROUP_DEBUG 1 #define CONFIG_WIRELESS_EXT 1 #define CONFIG_MEDIA_TUNER_MT2060_MODULE 1 #define CONFIG_GPIO_TPS65910 1 #define CONFIG_ANDROID_LOGGER 1 #define CONFIG_MUTEX_SPIN_ON_OWNER 1 #define CONFIG_RWSEM_GENERIC_SPINLOCK 1 #define CONFIG_HAVE_FUNCTION_GRAPH_TRACER 1 #define CONFIG_VIDEOBUF2_CORE 1 #define CONFIG_BASE_SMALL 0 #define CONFIG_CRYPTO_BLKCIPHER2 1 #define CONFIG_COMPACTION 1 #define CONFIG_PROC_FS 1 #define CONFIG_MTD_BLOCK 1 #define CONFIG_RC_MAP 1 #define CONFIG_WEXT_PRIV 1 #define CONFIG_SCSI_LOWLEVEL 1 #define CONFIG_HID_PANTHERLORD 1 #define CONFIG_SND 1 #define CONFIG_FLATMEM 1 #define CONFIG_IR_RC6_DECODER 1 #define CONFIG_UART3_DMA_RK29 0 #define CONFIG_PAGEFLAGS_EXTENDED 1 #define CONFIG_TABLET_USB_HANWANG 1 #define CONFIG_SYSCTL 1 #define CONFIG_PLAT_RK 1 #define CONFIG_LOCAL_TIMERS 1 #define CONFIG_WM831X_BACKUP 1 #define CONFIG_HAVE_C_RECORDMCOUNT 1 #define CONFIG_MEDIA_TUNER_MT2131_MODULE 1 #define CONFIG_XFRM_USER 1 #define CONFIG_HAVE_PERF_EVENTS 1 #define CONFIG_PPP_ASYNC 1 #define CONFIG_UID_STAT 1 #define CONFIG_GS_KXTIK 1 #define CONFIG_SYS_SUPPORTS_APM_EMULATION 1 #define CONFIG_RTC_INTF_ALARM_DEV 1 #define CONFIG_HID_MULTITOUCH 1 #define CONFIG_NETFILTER_XT_MATCH_QUOTA2 1 #define CONFIG_GSENSOR_DEVICE 1 #define CONFIG_POWER_ON_CHARGER_DISPLAY 1 #define CONFIG_IDBLOCK 1 #define CONFIG_HID_ELECOM 1 #define CONFIG_SND_TIMER 1 #define CONFIG_FAT_DEFAULT_CODEPAGE 437 #define CONFIG_BLK_DEV 1 #define CONFIG_VIDEO_RK29_CAMMEM_ION 1 #define CONFIG_TRACING_SUPPORT 1 #define CONFIG_UNIX98_PTYS 1 #define CONFIG_NETFILTER_XT_TARGET_CONNMARK 1 #define CONFIG_HAVE_SCHED_CLOCK 1 #define CONFIG_NET_SCHED 1 #define CONFIG_JBD 1 #define CONFIG_PRINTK_TIME 1 #define CONFIG_PPP 1 #define CONFIG_NETFILTER_XT_MATCH_QUOTA 1 #define CONFIG_SOC_CAMERA_SP2518 1 #define CONFIG_HAVE_KERNEL_LZO 1 #define CONFIG_INET_DIAG 1 #define CONFIG_I2C1_RK30 1 #define CONFIG_NF_NAT_FTP 1 #define CONFIG_HID_ROCCAT_KONE 1 #define CONFIG_NF_CT_PROTO_UDPLITE 1 #define CONFIG_TEXTSEARCH 1 #define CONFIG_ADC_RK30 1 #define CONFIG_USB_SUPPORT 1 #define CONFIG_NETFILTER_XT_MATCH_QTAGUID 1 #define CONFIG_RK_HDMI 1 #define CONFIG_PL330 1 #define CONFIG_LIGHT_DEVICE 1 #define CONFIG_STAGING 1 #define CONFIG_MTD_CHAR 1 #define CONFIG_FLAT_NODE_MEM_MAP 1 #define CONFIG_VT_CONSOLE 1 #define CONFIG_HID_UCLOGIC 1 #define CONFIG_LEDS_GPIO 1 #define CONFIG_SMARTJOYPLUS_FF 1 #define CONFIG_NETFILTER_XT_MATCH_STATE 1 #define CONFIG_LOGIRUMBLEPAD2_FF 1 #define CONFIG_USB20_OTG 1 #define CONFIG_IR_RC5_DECODER 1 #define CONFIG_INET6_XFRM_MODE_BEET 1 #define CONFIG_GYROSCOPE_DEVICE 1 #define CONFIG_PREEMPT 1 #define CONFIG_FB_CFB_COPYAREA 1 #define CONFIG_BINARY_PRINTF 1 #define CONFIG_RK_SRAM_DMA 1 #define CONFIG_GENERIC_CLOCKEVENTS_BUILD 1 #define CONFIG_VIDEOBUF_GEN 1 #define CONFIG_VIDEO_V4L2 1 #define CONFIG_HID_NTRIG 1 #define CONFIG_DDR_SDRAM_FREQ 336 #define CONFIG_DECOMPRESS_GZIP 1 #define CONFIG_SDMMC_RK29 1 #define CONFIG_LLC 1 #define CONFIG_CROSS_COMPILE "" #define CONFIG_MEDIA_TUNER_TEA5761_MODULE 1 #define CONFIG_BATTERY_RK30_VOL3V8 1 #define CONFIG_USB_GADGET_SELECTED 1 #define CONFIG_GENERIC_CLOCKEVENTS_BROADCAST 1 #define CONFIG_JOYSTICK_XPAD 1 #define CONFIG_NETFILTER_TPROXY 1 #define CONFIG_RK29_LAST_LOG 1 #define CONFIG_USB_USBNET 1 #define CONFIG_SCSI_MULTI_LUN 1 #define CONFIG_NET_ACT_POLICE 1 #define CONFIG_SND_SOC_RT5623 1 #define CONFIG_HID_SMARTJOYPLUS 1 #define CONFIG_TPS65910_RTC 1 #define CONFIG_NEW_LEDS 1 #define CONFIG_SWAP 1 #define CONFIG_CRC_CCITT 1 #define CONFIG_BLK_DEV_SD 1 #define CONFIG_CMDLINE_FROM_BOOTLOADER 1 #define CONFIG_NETFILTER_NETLINK 1 #define CONFIG_MODULE_UNLOAD 1 #define CONFIG_CPU_FREQ_DEFAULT_GOV_INTERACTIVE 1 #define CONFIG_USB_DWC_OTG 1 #define CONFIG_RK_CONSOLE_THREAD 1 #define CONFIG_RCU_FANOUT 32 #define CONFIG_BITREVERSE 1 #define CONFIG_USB_SERIAL_WWAN 1 #define CONFIG_VIDEO_V4L2_COMMON 1 #define CONFIG_FB_MODE_HELPERS 1 #define CONFIG_CRYPTO_BLKCIPHER 1 #define CONFIG_NF_CONNTRACK 1 #define CONFIG_FILE_LOCKING 1 #define CONFIG_SND_SOC_I2C_AND_SPI 1 #define CONFIG_FIQ 1 #define CONFIG_HID_ROCCAT_ARVO 1 #define CONFIG_NET_EMATCH 1 #define CONFIG_IP_NF_TARGET_REJECT 1 #define CONFIG_LEDS_CLASS 1 #define CONFIG_GENERIC_HARDIRQS 1 #define CONFIG_RTC_INTF_DEV 1 #define CONFIG_MTD_MAP_BANK_WIDTH_4 1 #define CONFIG_HID_SUPPORT 1 #define CONFIG_NET_ACTIVITY_STATS 1 #define CONFIG_NLS_DEFAULT "iso8859-1" #define CONFIG_NF_CT_PROTO_GRE 1 #define CONFIG_ION_ROCKCHIP 1 #define CONFIG_NF_CT_NETLINK 1 #define CONFIG_CRYPTO_AEAD2 1 #define CONFIG_NETFILTER_XT_MATCH_HL 1 #define CONFIG_CRYPTO_ALGAPI2 1 #define CONFIG_USB_NET_DM9620 1 #define CONFIG_ZBOOT_ROM_TEXT 0x0 #define CONFIG_HAVE_MEMBLOCK 1 #define CONFIG_INPUT 1 #define CONFIG_PROC_SYSCTL 1 #define CONFIG_MMU 1 #define CONFIG_HAVE_IRQ_WORK 1 #define CONFIG_USER_WAKELOCK 1 #define CONFIG_ENABLE_DEFAULT_TRACERS 1 #define CONFIG_TABLET_USB_AIPTEK 1
EPDCenter/android_kernel_archos_80_titan
include/generated/autoconf.h
C
gpl-2.0
29,490
/* * AAC decoder data * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org ) * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com ) * * This file is part of Libav. * * Libav 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. * * Libav 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 Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * AAC decoder data * @author Oded Shimon ( ods15 ods15 dyndns org ) * @author Maxim Gavrilov ( maxim.gavrilov gmail com ) */ #ifndef AVCODEC_AACDECTAB_H #define AVCODEC_AACDECTAB_H #include "libavutil/audioconvert.h" #include "aac.h" #include <stdint.h> /* @name ltp_coef * Table of the LTP coefficients */ static const float ltp_coef[8] = { 0.570829, 0.696616, 0.813004, 0.911304, 0.984900, 1.067894, 1.194601, 1.369533, }; /* @name tns_tmp2_map * Tables of the tmp2[] arrays of LPC coefficients used for TNS. * The suffix _M_N[] indicate the values of coef_compress and coef_res * respectively. * @{ */ static const float tns_tmp2_map_1_3[4] = { 0.00000000, -0.43388373, 0.64278758, 0.34202015, }; static const float tns_tmp2_map_0_3[8] = { 0.00000000, -0.43388373, -0.78183150, -0.97492790, 0.98480773, 0.86602539, 0.64278758, 0.34202015, }; static const float tns_tmp2_map_1_4[8] = { 0.00000000, -0.20791170, -0.40673664, -0.58778524, 0.67369562, 0.52643216, 0.36124167, 0.18374951, }; static const float tns_tmp2_map_0_4[16] = { 0.00000000, -0.20791170, -0.40673664, -0.58778524, -0.74314481, -0.86602539, -0.95105654, -0.99452192, 0.99573416, 0.96182561, 0.89516330, 0.79801720, 0.67369562, 0.52643216, 0.36124167, 0.18374951, }; static const float * const tns_tmp2_map[4] = { tns_tmp2_map_0_3, tns_tmp2_map_0_4, tns_tmp2_map_1_3, tns_tmp2_map_1_4 }; // @} static const int8_t tags_per_config[16] = { 0, 1, 1, 2, 3, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0 }; static const uint8_t aac_channel_layout_map[7][5][2] = { { { TYPE_SCE, 0 }, }, { { TYPE_CPE, 0 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, { TYPE_SCE, 1 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, { TYPE_CPE, 1 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, { TYPE_LFE, 0 }, { TYPE_CPE, 1 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, { TYPE_LFE, 0 }, { TYPE_CPE, 2 }, { TYPE_CPE, 1 }, }, }; static const int64_t aac_channel_layout[8] = { AV_CH_LAYOUT_MONO, AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_SURROUND, AV_CH_LAYOUT_4POINT0, AV_CH_LAYOUT_5POINT0_BACK, AV_CH_LAYOUT_5POINT1_BACK, AV_CH_LAYOUT_7POINT1_WIDE, 0, }; #endif /* AVCODEC_AACDECTAB_H */
heiher/gst-ffmpeg
gst-libs/ext/libav/libavcodec/aacdectab.h
C
gpl-2.0
3,227
template <typename Item> void mergesort(Item a[], int l, int r) { if (r <= 1) return ; int m = (r+1)/2; mergesort(a, l, m); mergesort(a, m+1, r); merge(a, l, m, r); }
flow-J/Exercise
garbage/Algorithm_in_c++/test8.3.cpp
C++
gpl-2.0
187
/* This file is part of the KDE project Copyright (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <dcopclient.h> #include <kapplication.h> #include <kprocess.h> #include <kstaticdeleter.h> #include "watcher_stub.h" #include "mrml_utils.h" // after 100 of no use, terminate the mrmld #define TIMEOUT 100 // how often to restart the mrmld in case of failure #define NUM_RESTARTS 5 using namespace KMrml; KStaticDeleter<Util> utils_sd; Util *Util::s_self = 0L; Util::Util() { // we need our own dcopclient, when used in kio_mrml if ( !DCOPClient::mainClient() ) { DCOPClient::setMainClient( new DCOPClient() ); if ( !DCOPClient::mainClient()->attach() ) qWarning( "kio_mrml: Can't attach to DCOP Server."); } } Util::~Util() { if ( this == s_self ) s_self = 0L; } Util *Util::self() { if ( !s_self ) s_self = utils_sd.setObject( new Util() ); return s_self; } bool Util::requiresLocalServerFor( const KURL& url ) { return url.host().isEmpty() || url.host() == "localhost"; } bool Util::startLocalServer( const Config& config ) { if ( config.serverStartedIndividually() ) return true; DCOPClient *client = DCOPClient::mainClient(); // ### check if it's already running (add dcop method to Watcher) Watcher_stub watcher( client, "kded", "daemonwatcher"); return ( watcher.requireDaemon( client->appId(), "mrmld", config.mrmldCommandline(), TIMEOUT, NUM_RESTARTS ) && watcher.ok() ); } void Util::unrequireLocalServer() { DCOPClient *client = DCOPClient::mainClient(); Watcher_stub watcher( client, "kded", "daemonwatcher"); watcher.unrequireDaemon( client->appId(), "mrmld" ); }
iegor/kdegraphics
kmrml/kmrml/lib/mrml_utils.cpp
C++
gpl-2.0
2,481
# -*- coding: utf-8 -*- ## This file is part of Invenio. ## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Unit tests for the ranking engine.""" __revision__ = "$Id$" from invenio.importutils import lazy_import from invenio.testutils import make_test_suite, run_test_suite, InvenioTestCase bibrank_tag_based_indexer = lazy_import('invenio.bibrank_tag_based_indexer') split_ranges = lazy_import('invenio.bibrank:split_ranges') class TestListSetOperations(InvenioTestCase): """Test list set operations.""" def test_union_dicts(self): """bibrank tag based indexer - union dicts""" self.assertEqual({1: 5, 2: 6, 3: 9, 4: 10, 10: 1}, bibrank_tag_based_indexer.union_dicts({1: 5, 2: 6, 3: 9}, {3:9, 4:10, 10: 1})) def test_split_ranges(self): """bibrank tag based indexer - split ranges""" self.assertEqual([[0, 500], [600, 1000]], split_ranges("0-500,600-1000")) TEST_SUITE = make_test_suite(TestListSetOperations,) if __name__ == "__main__": run_test_suite(TEST_SUITE)
labordoc/labordoc-next
modules/bibrank/lib/bibrank_tag_based_indexer_unit_tests.py
Python
gpl-2.0
1,743
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.7 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2015 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM 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 Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2015 * $Id$ * */ class CRM_Event_Import_Controller extends CRM_Core_Controller { /** * Class constructor. * * @param null $title * @param bool|int $action * @param bool $modal */ public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) { parent::__construct($title, $modal); // lets get around the time limit issue if possible, CRM-2113 if (!ini_get('safe_mode')) { set_time_limit(0); } $this->_stateMachine = new CRM_Import_StateMachine($this, $action); // create and instantiate the pages $this->addPages($this->_stateMachine, $action); // add all the actions $config = CRM_Core_Config::singleton(); $this->addActions($config->uploadDir, array('uploadFile')); } }
alfonsom/ccdrupal
sites/all/modules/civicrm/CRM/Event/Import/Controller.php
PHP
gpl-2.0
2,507
--- layout: post title: For Rusty - 1988 - 2004 author: Chris Metcalf date: 2004/04/21 slug: for-rusty-1988-2004 category: tags: [ dogs, family, me ] --- Today we had to say goodbye to a loyal friend. <img src="/images/posts/rusty.jpg" alt="an old friend" /> Today we had to put one of our family's favorite pets to sleep. As he approached the ripe old age of 16, age had simply taken too much of a toll on him. He had a long, full life of deer and bunny chasing, and we're all sure he's much happier now. I decided I'd blog the occasion to make sure I always remembered him. The most loyal of friends deserve that.
chrismetcalf/chrismetcalf.net
_posts/2004-04-21-for-rusty-1988-2004.md
Markdown
gpl-2.0
622
/* protocol_subnet.c -- handle the meta-protocol, subnets Copyright (C) 1999-2005 Ivo Timmermans, 2000-2012 Guus Sliepen <guus@tinc-vpn.org> 2009 Michael Tokarev <mjt@tls.msk.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "system.h" #include "conf.h" #include "connection.h" #include "logger.h" #include "net.h" #include "netutl.h" #include "node.h" #include "protocol.h" #include "subnet.h" #include "utils.h" #include "xalloc.h" bool send_add_subnet(connection_t *c, const subnet_t *subnet) { char netstr[MAXNETSTR]; if(!net2str(netstr, sizeof netstr, subnet)) return false; return send_request(c, "%d %x %s %s", ADD_SUBNET, rand(), subnet->owner->name, netstr); } bool add_subnet_h(connection_t *c, const char *request) { char subnetstr[MAX_STRING_SIZE]; char name[MAX_STRING_SIZE]; node_t *owner; subnet_t s, *new, *old; memset(&s, 0x0, sizeof(subnet_t)); if(sscanf(request, "%*d %*x " MAX_STRING " " MAX_STRING, name, subnetstr) != 2) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ADD_SUBNET", c->name, c->hostname); return false; } /* Check if owner name is valid */ if(!check_id(name)) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ADD_SUBNET", c->name, c->hostname, "invalid name"); return false; } /* Check if subnet string is valid */ if(!str2net(&s, subnetstr)) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ADD_SUBNET", c->name, c->hostname, "invalid subnet string"); return false; } if(seen_request(request)) return true; /* Check if the owner of the new subnet is in the connection list */ owner = lookup_node(name); if(tunnelserver && owner != myself && owner != c->node) { /* in case of tunnelserver, ignore indirect subnet registrations */ logger(DEBUG_PROTOCOL, LOG_WARNING, "Ignoring indirect %s from %s (%s) for %s", "ADD_SUBNET", c->name, c->hostname, subnetstr); return true; } if(!owner) { owner = new_node(); owner->name = xstrdup(name); node_add(owner); } /* Check if we already know this subnet */ if(lookup_subnet(owner, &s)) return true; /* If we don't know this subnet, but we are the owner, retaliate with a DEL_SUBNET */ if(owner == myself) { logger(DEBUG_PROTOCOL, LOG_WARNING, "Got %s from %s (%s) for ourself", "ADD_SUBNET", c->name, c->hostname); s.owner = myself; send_del_subnet(c, &s); return true; } /* In tunnel server mode, we should already know all allowed subnets */ if(tunnelserver) { logger(DEBUG_ALWAYS, LOG_WARNING, "Ignoring unauthorized %s from %s (%s): %s", "ADD_SUBNET", c->name, c->hostname, subnetstr); return true; } /* Ignore if strictsubnets is true, but forward it to others */ if(strictsubnets) { logger(DEBUG_ALWAYS, LOG_WARNING, "Ignoring unauthorized %s from %s (%s): %s", "ADD_SUBNET", c->name, c->hostname, subnetstr); if ((!owner->status.reachable) && ((now.tv_sec - owner->last_state_change) >= keylifetime*2)) { logger(DEBUG_CONNECTIONS, LOG_INFO, "Not forwarding informations about %s to ALL (%lf / %d)", owner->name, difftime(now.tv_sec, owner->last_state_change), keylifetime); } else { forward_request(c, request); } return true; } /* If everything is correct, add the subnet to the list of the owner */ *(new = new_subnet()) = s; subnet_add(owner, new); if(owner->status.reachable) subnet_update(owner, new, true); /* Tell the rest */ if(!tunnelserver) forward_request(c, request); /* Fast handoff of roaming MAC addresses */ if(s.type == SUBNET_MAC && owner != myself && (old = lookup_subnet(myself, &s)) && old->expires) old->expires = 1; return true; } bool send_del_subnet(connection_t *c, const subnet_t *s) { char netstr[MAXNETSTR]; if(!net2str(netstr, sizeof netstr, s)) return false; return send_request(c, "%d %x %s %s", DEL_SUBNET, rand(), s->owner->name, netstr); } bool del_subnet_h(connection_t *c, const char *request) { char subnetstr[MAX_STRING_SIZE]; char name[MAX_STRING_SIZE]; node_t *owner; subnet_t s, *find; memset(&s, 0x0, sizeof(subnet_t)); if(sscanf(request, "%*d %*x " MAX_STRING " " MAX_STRING, name, subnetstr) != 2) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "DEL_SUBNET", c->name, c->hostname); return false; } /* Check if owner name is valid */ if(!check_id(name)) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "DEL_SUBNET", c->name, c->hostname, "invalid name"); return false; } /* Check if subnet string is valid */ if(!str2net(&s, subnetstr)) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "DEL_SUBNET", c->name, c->hostname, "invalid subnet string"); return false; } if(seen_request(request)) return true; /* Check if the owner of the subnet being deleted is in the connection list */ owner = lookup_node(name); if(tunnelserver && owner != myself && owner != c->node) { /* in case of tunnelserver, ignore indirect subnet deletion */ logger(DEBUG_PROTOCOL, LOG_WARNING, "Ignoring indirect %s from %s (%s) for %s", "DEL_SUBNET", c->name, c->hostname, subnetstr); return true; } if(!owner) { logger(DEBUG_PROTOCOL, LOG_WARNING, "Got %s from %s (%s) for %s which is not in our node tree", "DEL_SUBNET", c->name, c->hostname, name); return true; } /* If everything is correct, delete the subnet from the list of the owner */ s.owner = owner; find = lookup_subnet(owner, &s); if(!find) { logger(DEBUG_PROTOCOL, LOG_WARNING, "Got %s from %s (%s) for %s which does not appear in his subnet tree", "DEL_SUBNET", c->name, c->hostname, name); if(strictsubnets) forward_request(c, request); return true; } /* If we are the owner of this subnet, retaliate with an ADD_SUBNET */ if(owner == myself) { logger(DEBUG_PROTOCOL, LOG_WARNING, "Got %s from %s (%s) for ourself", "DEL_SUBNET", c->name, c->hostname); send_add_subnet(c, find); return true; } if(tunnelserver) return true; /* Tell the rest */ if(!tunnelserver) forward_request(c, request); if(strictsubnets) return true; /* Finally, delete it. */ if(owner->status.reachable) subnet_update(owner, find, false); subnet_del(owner, find); return true; }
jed1/tinc
src/protocol_subnet.c
C
gpl-2.0
6,984
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <assert.h> #include <exception> // System.Reflection.Emit.ModuleBuilder struct ModuleBuilder_t973; // System.Object struct Object_t; // System.Type[] struct TypeU5BU5D_t194; // System.Reflection.MemberInfo struct MemberInfo_t; // System.Reflection.Emit.TokenGenerator struct TokenGenerator_t970; #include "codegen/il2cpp-codegen.h" // System.Void System.Reflection.Emit.ModuleBuilder::.cctor() extern "C" void ModuleBuilder__cctor_m5685 (Object_t * __this /* static, unused */, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Int32 System.Reflection.Emit.ModuleBuilder::get_next_table_index(System.Object,System.Int32,System.Boolean) extern "C" int32_t ModuleBuilder_get_next_table_index_m5686 (ModuleBuilder_t973 * __this, Object_t * ___obj, int32_t ___table, bool ___inc, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Type[] System.Reflection.Emit.ModuleBuilder::GetTypes() extern "C" TypeU5BU5D_t194* ModuleBuilder_GetTypes_m5687 (ModuleBuilder_t973 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Int32 System.Reflection.Emit.ModuleBuilder::getToken(System.Reflection.Emit.ModuleBuilder,System.Object) extern "C" int32_t ModuleBuilder_getToken_m5688 (Object_t * __this /* static, unused */, ModuleBuilder_t973 * ___mb, Object_t * ___obj, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Int32 System.Reflection.Emit.ModuleBuilder::GetToken(System.Reflection.MemberInfo) extern "C" int32_t ModuleBuilder_GetToken_m5689 (ModuleBuilder_t973 * __this, MemberInfo_t * ___member, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void System.Reflection.Emit.ModuleBuilder::RegisterToken(System.Object,System.Int32) extern "C" void ModuleBuilder_RegisterToken_m5690 (ModuleBuilder_t973 * __this, Object_t * ___obj, int32_t ___token, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Reflection.Emit.TokenGenerator System.Reflection.Emit.ModuleBuilder::GetTokenGenerator() extern "C" Object_t * ModuleBuilder_GetTokenGenerator_m5691 (ModuleBuilder_t973 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
Soufien/unityIntoIOSSample
SampleProject/il2cpp_output/mscorlib_System_Reflection_Emit_ModuleBuilderMethodDeclarations.h
C
gpl-2.0
2,210
<?php /** * LICENSE: Anahita is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * * @category Anahita * @package Com_Base * @subpackage Template_Filter * @author Arash Sanieyan <ash@anahitapolis.com> * @author Rastin Mehr <rastin@anahitapolis.com> * @copyright 2008 - 2010 rmdStudio Inc./Peerglobe Technology Inc * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl-3.0.html> * @version SVN: $Id: view.php 13650 2012-04-11 08:56:41Z asanieyan $ * @link http://www.anahitapolis.com */ /** * Module Filter * * @category Anahita * @package Com_Base * @subpackage Template_Filter * @author Arash Sanieyan <ash@anahitapolis.com> * @author Rastin Mehr <rastin@anahitapolis.com> * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl-3.0.html> * @link http://www.anahitapolis.com */ class ComBaseTemplateFilterModule extends KTemplateFilterAbstract implements KTemplateFilterWrite { /** * Initializes the options for the object * * Called from {@link __construct()} as a first step of object instantiation. * * @param object An optional KConfig object with configuration options * @return void */ protected function _initialize(KConfig $config) { $config->append(array( 'priority' => KCommand::PRIORITY_LOW, )); parent::_initialize($config); } /** * Find any <module></module> elements and inject them into the JDocument object * * @param string Block of text to parse * * @return void */ public function write(&$text) { $matches = array(); if(preg_match_all('#<module([^>]*)>(.*)</module>#siU', $text, $matches)) { $modules = array(); foreach($matches[0] as $key => $match) { $text = str_replace($match, '', $text); $attributes = array( 'style' => 'default', 'params' => '', 'title' => '', 'class' => '', 'prepend' => true ); $attributes = array_merge($attributes, $this->_parseAttributes($matches[1][$key])); if ( !empty($attributes['class']) ) { $attributes['params'] .= ' moduleclass_sfx= '.$attributes['class']; } $module = new KObject(); $module->id = uniqid(); $module->content = $matches[2][$key]; $module->position = $attributes['position']; $module->params = $attributes['params']; $module->showtitle = !empty($attributes['title']); $module->title = $attributes['title']; $module->name = $attributes['position']; $module->attribs = $attributes; $module->user = 0; $module->module = 'mod_dynamic'; $modules[] = $module; } $mods =& JModuleHelper::_load(); $mods = array_merge($modules, $mods); } return $this; } }
pah861/hawkconnect2
components/com_base/templates/helpers/module.php
PHP
gpl-2.0
3,737
<?php /** * @version $Id: legacy.php 10066 2008-02-26 04:20:57Z ian $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); jimport( 'joomla.plugin.plugin' ); /** * Joomla! Debug plugin * * @author Johan Janssens <johan.janssens@joomla.org> * @package Joomla * @subpackage System */ class plgSystemLegacy extends JPlugin { /** * Constructor * * For php4 compatability we must not use the __constructor as a constructor for plugins * because func_get_args ( void ) returns a copy of all passed arguments NOT references. * This causes problems with cross-referencing necessary for the observer design pattern. * * @param object $subject The object to observe * @param array $config An array that holds the plugin configuration * @since 1.0 */ function plgSystemLegacy(& $subject, $config) { parent::__construct($subject, $config); global $mainframe; // Define the 1.0 legacy mode constant define('_JLEGACY', '1.0'); // Set global configuration var for legacy mode $config = &JFactory::getConfig(); $config->setValue('config.legacy', 1); // Import library dependencies require_once(dirname(__FILE__).DS.'legacy'.DS.'classes.php'); require_once(dirname(__FILE__).DS.'legacy'.DS.'functions.php'); // Register legacy classes for autoloading JLoader::register('mosAdminMenus' , dirname(__FILE__).DS.'legacy'.DS.'adminmenus.php'); JLoader::register('mosCache' , dirname(__FILE__).DS.'legacy'.DS.'cache.php'); JLoader::register('mosCategory' , dirname(__FILE__).DS.'legacy'.DS.'category.php'); JLoader::register('mosCommonHTML' , dirname(__FILE__).DS.'legacy'.DS.'commonhtml.php'); JLoader::register('mosComponent' , dirname(__FILE__).DS.'legacy'.DS.'component.php'); JLoader::register('mosContent' , dirname(__FILE__).DS.'legacy'.DS.'content.php'); JLoader::register('mosDBTable' , dirname(__FILE__).DS.'legacy'.DS.'dbtable.php'); JLoader::register('mosHTML' , dirname(__FILE__).DS.'legacy'.DS.'html.php'); JLoader::register('mosInstaller' , dirname(__FILE__).DS.'legacy'.DS.'installer.php'); JLoader::register('mosMainFrame' , dirname(__FILE__).DS.'legacy'.DS.'mainframe.php'); JLoader::register('mosMambot' , dirname(__FILE__).DS.'legacy'.DS.'mambot.php'); JLoader::register('mosMambotHandler', dirname(__FILE__).DS.'legacy'.DS.'mambothandler.php'); JLoader::register('mosMenu' , dirname(__FILE__).DS.'legacy'.DS.'menu.php'); JLoader::register('mosMenuBar' , dirname(__FILE__).DS.'legacy'.DS.'menubar.php'); JLoader::register('mosModule' , dirname(__FILE__).DS.'legacy'.DS.'module.php'); //JLoader::register('mosPageNav' , dirname(__FILE__).DS.'legacy'.DS.'pagination.php'); JLoader::register('mosParameters' , dirname(__FILE__).DS.'legacy'.DS.'parameters.php'); JLoader::register('patFactory' , dirname(__FILE__).DS.'legacy'.DS.'patfactory.php'); JLoader::register('mosProfiler' , dirname(__FILE__).DS.'legacy'.DS.'profiler.php'); JLoader::register('mosSection' , dirname(__FILE__).DS.'legacy'.DS.'section.php'); JLoader::register('mosSession' , dirname(__FILE__).DS.'legacy'.DS.'session.php'); JLoader::register('mosToolbar' , dirname(__FILE__).DS.'legacy'.DS.'toolbar.php'); JLoader::register('mosUser' , dirname(__FILE__).DS.'legacy'.DS.'user.php'); // Register class for the database, depends on which db type has been selected for use $dbtype = $config->getValue('config.dbtype', 'mysql'); JLoader::register('database' , dirname(__FILE__).DS.'legacy'.DS.$dbtype.'.php'); /** * Legacy define, _ISO define not used anymore. All output is forced as utf-8. * @deprecated As of version 1.5 */ define('_ISO','charset=utf-8'); /** * Legacy constant, use _JEXEC instead * @deprecated As of version 1.5 */ define( '_VALID_MOS', 1 ); /** * Legacy constant, use _JEXEC instead * @deprecated As of version 1.5 */ define( '_MOS_MAMBO_INCLUDED', 1 ); /** * Legacy constant, use DATE_FORMAT_LC instead * @deprecated As of version 1.5 */ DEFINE('_DATE_FORMAT_LC', JText::_('DATE_FORMAT_LC1') ); //Uses PHP's strftime Command Format /** * Legacy constant, use DATE_FORMAT_LC2 instead * @deprecated As of version 1.5 */ DEFINE('_DATE_FORMAT_LC2', JText::_('DATE_FORMAT_LC2')); /** * Legacy constant, use JFilterInput instead * @deprecated As of version 1.5 */ DEFINE( "_MOS_NOTRIM", 0x0001 ); /** * Legacy constant, use JFilterInput instead * @deprecated As of version 1.5 */ DEFINE( "_MOS_ALLOWHTML", 0x0002 ); /** * Legacy constant, use JFilterInput instead * @deprecated As of version 1.5 */ DEFINE( "_MOS_ALLOWRAW", 0x0004 ); /** * Legacy global, use JVersion->getLongVersion() instead * @name $_VERSION * @deprecated As of version 1.5 */ $GLOBALS['_VERSION'] = new JVersion(); $version = $GLOBALS['_VERSION']->getLongVersion(); /** * Legacy global, use JFactory::getDBO() instead * @name $database * @deprecated As of version 1.5 */ $conf =& JFactory::getConfig(); $GLOBALS['database'] = new database($conf->getValue('config.host'), $conf->getValue('config.user'), $conf->getValue('config.password'), $conf->getValue('config.db'), $conf->getValue('config.dbprefix')); $GLOBALS['database']->debug($conf->getValue('config.debug')); /** * Legacy global, use JFactory::getUser() [JUser object] instead * @name $my * @deprecated As of version 1.5 */ $user =& JFactory::getUser(); $GLOBALS['my'] = (object)$user->getProperties(); $GLOBALS['my']->gid = $user->get('aid', 0); /** * Insert configuration values into global scope (for backwards compatibility) * @deprecated As of version 1.5 */ $temp = new JConfig; foreach (get_object_vars($temp) as $k => $v) { $name = 'mosConfig_'.$k; $GLOBALS[$name] = $v; } $GLOBALS['mosConfig_live_site'] = substr_replace(JURI::root(), '', -1, 1); $GLOBALS['mosConfig_absolute_path'] = JPATH_SITE; $GLOBALS['mosConfig_cachepath'] = JPATH_BASE.DS.'cache'; $GLOBALS['mosConfig_offset_user'] = 0; $lang =& JFactory::getLanguage(); $GLOBALS['mosConfig_lang'] = $lang->getBackwardLang(); $config->setValue('config.live_site', $GLOBALS['mosConfig_live_site']); $config->setValue('config.absolute_path', $GLOBALS['mosConfig_absolute_path']); $config->setValue('config.lang', $GLOBALS['mosConfig_lang']); /** * Legacy global, use JFactory::getUser() instead * @name $acl * @deprecated As of version 1.5 */ $acl =& JFactory::getACL(); // Legacy ACL's for backward compat $acl->addACL( 'administration', 'edit', 'users', 'super administrator', 'components', 'all' ); $acl->addACL( 'administration', 'edit', 'users', 'administrator', 'components', 'all' ); $acl->addACL( 'administration', 'edit', 'users', 'super administrator', 'user properties', 'block_user' ); $acl->addACL( 'administration', 'manage', 'users', 'super administrator', 'components', 'com_users' ); $acl->addACL( 'administration', 'manage', 'users', 'administrator', 'components', 'com_users' ); $acl->addACL( 'administration', 'config', 'users', 'super administrator' ); //$acl->addACL( 'administration', 'config', 'users', 'administrator' ); $acl->addACL( 'action', 'add', 'users', 'author', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'editor', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'publisher', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'author', 'content', 'own' ); $acl->addACL( 'action', 'edit', 'users', 'editor', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'publisher', 'content', 'all' ); $acl->addACL( 'action', 'publish', 'users', 'publisher', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'manager', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'manager', 'content', 'all' ); $acl->addACL( 'action', 'publish', 'users', 'manager', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'administrator', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'administrator', 'content', 'all' ); $acl->addACL( 'action', 'publish', 'users', 'administrator', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'super administrator', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'super administrator', 'content', 'all' ); $acl->addACL( 'action', 'publish', 'users', 'super administrator', 'content', 'all' ); $acl->addACL( 'com_syndicate', 'manage', 'users', 'super administrator' ); $acl->addACL( 'com_syndicate', 'manage', 'users', 'administrator' ); $acl->addACL( 'com_syndicate', 'manage', 'users', 'manager' ); $GLOBALS['acl'] =& $acl; /** * Legacy global * @name $task * @deprecated As of version 1.5 */ $GLOBALS['task'] = JRequest::getString('task'); /** * Load the site language file (the old way - to be deprecated) * @deprecated As of version 1.5 */ global $mosConfig_lang; $mosConfig_lang = JFilterInput::clean($mosConfig_lang, 'cmd'); $file = JPATH_SITE.DS.'language'.DS.$mosConfig_lang.'.php'; if (file_exists( $file )) { require_once( $file); } else { $file = JPATH_SITE.DS.'language'.DS.'english.php'; if (file_exists( $file )) { require_once( $file ); } } /** * Legacy global * use JApplicaiton->registerEvent and JApplication->triggerEvent for event handling * use JPlugingHelper::importPlugin to load bot code * @deprecated As of version 1.5 */ $GLOBALS['_MAMBOTS'] = new mosMambotHandler(); } function onAfterRoute() { global $mainframe; if ($mainframe->isAdmin()) { return; } switch(JRequest::getCmd('option')) { case 'com_content' : $this->routeContent(); break; case 'com_newsfeeds' : $this->routeNewsfeeds(); break; case 'com_weblinks' : $this->routeWeblinks(); break; case 'com_frontpage' : JRequest::setVar('option', 'com_content'); JRequest::setVar('view', 'frontpage'); break; case 'com_login' : JRequest::setVar('option', 'com_user'); JRequest::setVar('view', 'login'); break; case 'com_registration' : JRequest::setVar('option', 'com_user'); JRequest::setVar('view', 'register'); break; } /** * Legacy global, use JApplication::getTemplate() instead * @name $cur_template * @deprecated As of version 1.5 */ $GLOBALS['cur_template'] = $mainframe->getTemplate(); } function routeContent() { $viewName = JRequest::getCmd( 'view', 'article' ); $layout = JRequest::getCmd( 'layout', 'default' ); // interceptors to support legacy urls switch( JRequest::getCmd('task')) { //index.php?option=com_content&task=x&id=x&Itemid=x case 'blogsection': $viewName = 'section'; $layout = 'blog'; break; case 'section': $viewName = 'section'; break; case 'category': $viewName = 'category'; break; case 'blogcategory': $viewName = 'category'; $layout = 'blog'; break; case 'archivesection': case 'archivecategory': $viewName = 'archive'; break; case 'frontpage' : $viewName = 'frontpage'; break; case 'view': $viewName = 'article'; break; } JRequest::setVar('layout', $layout); JRequest::setVar('view', $viewName); } function routeNewsfeeds() { $viewName = JRequest::getCmd( 'view', 'categories' ); // interceptors to support legacy urls switch( JRequest::getCmd('task')) { //index.php?option=com_newsfeeds&task=x&catid=xid=x&Itemid=x case 'view': $viewName = 'newsfeed'; break; default: { if(JRequest::getInt('catid') && !JRequest::getCmd('view')) { $viewName = 'category'; } } } JRequest::setVar('view', $viewName); } function routeWeblinks() { $viewName = JRequest::getCmd( 'view', 'categories' ); // interceptors to support legacy urls switch( JRequest::getCmd('task')) { //index.php?option=com_weblinks&task=x&catid=xid=x case 'view': $viewName = 'weblink'; break; default: { if(($catid = JRequest::getInt('catid')) && !JRequest::getCmd('view')) { $viewName = 'category'; JRequest::setVar('id', $catid); } } } JRequest::setVar('view', $viewName); } }
google-code/administradora-beraca
plugins/system/legacy.php
PHP
gpl-2.0
13,245
def spaceship_building(cans): total_cans = 0 for week in range(1,53): total_cans = total_cans + cans print('Week %s = %s cans' % (week, total_cans)) spaceship_building(2) spaceship_building(13)
erikdejonge/python_for_kids
chapter07/spaceship_building.py
Python
gpl-2.0
227
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-24 15:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('emailer', '0007_auto_20150509_1922'), ] operations = [ migrations.AlterField( model_name='email', name='recipient', field=models.EmailField(db_index=True, max_length=254), ), ]
JustinWingChungHui/okKindred
emailer/migrations/0008_auto_20151224_1528.py
Python
gpl-2.0
467
<html> <head> <title>Stożek</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="../books.css" /> </head> <body align="left"> <h1>Stożek</h1> <center><img src="../images/cone.png" /></center> <br /> <div align="left"> <a href="file:#V=(1/3)*pi*r%5e2*h">V = (1/3) * pi * r^2 * h</a><br /> <br /> <a href="file:#A=(pi*r%5e2)+(pi*r*s)">A = (pi * r^2) + (pi * r * s)</a><br /> <a href="file:#A=(pi*r%5e2)+(pi*r*sqrt(r%5e2+h%5e2))">A = (pi * r^2) + (pi * r * sqrt(r^2 + h^2))</a><br /> </div> </body> </html>
biluna/biluna
thrd/speedcrunch-0.10.1/src/books/pl/cone.html
HTML
gpl-2.0
638
/* * rev-parse.c * * Copyright (C) Linus Torvalds, 2005 */ #include "cache.h" #include "commit.h" #include "refs.h" #include "quote.h" #include "builtin.h" #include "parse-options.h" #include "diff.h" #include "revision.h" #include "split-index.h" #define DO_REVS 1 #define DO_NOREV 2 #define DO_FLAGS 4 #define DO_NONFLAGS 8 static int filter = ~0; static const char *def; #define NORMAL 0 #define REVERSED 1 static int show_type = NORMAL; #define SHOW_SYMBOLIC_ASIS 1 #define SHOW_SYMBOLIC_FULL 2 static int symbolic; static int abbrev; static int abbrev_ref; static int abbrev_ref_strict; static int output_sq; static int stuck_long; static struct string_list *ref_excludes; /* * Some arguments are relevant "revision" arguments, * others are about output format or other details. * This sorts it all out. */ static int is_rev_argument(const char *arg) { static const char *rev_args[] = { "--all", "--bisect", "--dense", "--branches=", "--branches", "--header", "--ignore-missing", "--max-age=", "--max-count=", "--min-age=", "--no-merges", "--min-parents=", "--no-min-parents", "--max-parents=", "--no-max-parents", "--objects", "--objects-edge", "--parents", "--pretty", "--remotes=", "--remotes", "--glob=", "--sparse", "--tags=", "--tags", "--topo-order", "--date-order", "--unpacked", NULL }; const char **p = rev_args; /* accept -<digit>, like traditional "head" */ if ((*arg == '-') && isdigit(arg[1])) return 1; for (;;) { const char *str = *p++; int len; if (!str) return 0; len = strlen(str); if (!strcmp(arg, str) || (str[len-1] == '=' && !strncmp(arg, str, len))) return 1; } } /* Output argument as a string, either SQ or normal */ static void show(const char *arg) { if (output_sq) { int sq = '\'', ch; putchar(sq); while ((ch = *arg++)) { if (ch == sq) fputs("'\\'", stdout); putchar(ch); } putchar(sq); putchar(' '); } else puts(arg); } /* Like show(), but with a negation prefix according to type */ static void show_with_type(int type, const char *arg) { if (type != show_type) putchar('^'); show(arg); } /* Output a revision, only if filter allows it */ static void show_rev(int type, const unsigned char *sha1, const char *name) { if (!(filter & DO_REVS)) return; def = NULL; if ((symbolic || abbrev_ref) && name) { if (symbolic == SHOW_SYMBOLIC_FULL || abbrev_ref) { unsigned char discard[20]; char *full; switch (dwim_ref(name, strlen(name), discard, &full)) { case 0: /* * Not found -- not a ref. We could * emit "name" here, but symbolic-full * users are interested in finding the * refs spelled in full, and they would * need to filter non-refs if we did so. */ break; case 1: /* happy */ if (abbrev_ref) full = shorten_unambiguous_ref(full, abbrev_ref_strict); show_with_type(type, full); break; default: /* ambiguous */ error("refname '%s' is ambiguous", name); break; } free(full); } else { show_with_type(type, name); } } else if (abbrev) show_with_type(type, find_unique_abbrev(sha1, abbrev)); else show_with_type(type, sha1_to_hex(sha1)); } /* Output a flag, only if filter allows it. */ static int show_flag(const char *arg) { if (!(filter & DO_FLAGS)) return 0; if (filter & (is_rev_argument(arg) ? DO_REVS : DO_NOREV)) { show(arg); return 1; } return 0; } static int show_default(void) { const char *s = def; if (s) { unsigned char sha1[20]; def = NULL; if (!get_sha1(s, sha1)) { show_rev(NORMAL, sha1, s); return 1; } } return 0; } static int show_reference(const char *refname, const struct object_id *oid, int flag, void *cb_data) { if (ref_excluded(ref_excludes, refname)) return 0; show_rev(NORMAL, oid->hash, refname); return 0; } static int anti_reference(const char *refname, const struct object_id *oid, int flag, void *cb_data) { show_rev(REVERSED, oid->hash, refname); return 0; } static int show_abbrev(const unsigned char *sha1, void *cb_data) { show_rev(NORMAL, sha1, NULL); return 0; } static void show_datestring(const char *flag, const char *datestr) { static char buffer[100]; /* date handling requires both flags and revs */ if ((filter & (DO_FLAGS | DO_REVS)) != (DO_FLAGS | DO_REVS)) return; snprintf(buffer, sizeof(buffer), "%s%lu", flag, approxidate(datestr)); show(buffer); } static int show_file(const char *arg, int output_prefix) { show_default(); if ((filter & (DO_NONFLAGS|DO_NOREV)) == (DO_NONFLAGS|DO_NOREV)) { if (output_prefix) { const char *prefix = startup_info->prefix; show(prefix_filename(prefix, prefix ? strlen(prefix) : 0, arg)); } else show(arg); return 1; } return 0; } static int try_difference(const char *arg) { char *dotdot; unsigned char sha1[20]; unsigned char end[20]; const char *next; const char *this; int symmetric; static const char head_by_default[] = "HEAD"; if (!(dotdot = strstr(arg, ".."))) return 0; next = dotdot + 2; this = arg; symmetric = (*next == '.'); *dotdot = 0; next += symmetric; if (!*next) next = head_by_default; if (dotdot == arg) this = head_by_default; if (this == head_by_default && next == head_by_default && !symmetric) { /* * Just ".."? That is not a range but the * pathspec for the parent directory. */ *dotdot = '.'; return 0; } if (!get_sha1_committish(this, sha1) && !get_sha1_committish(next, end)) { show_rev(NORMAL, end, next); show_rev(symmetric ? NORMAL : REVERSED, sha1, this); if (symmetric) { struct commit_list *exclude; struct commit *a, *b; a = lookup_commit_reference(sha1); b = lookup_commit_reference(end); exclude = get_merge_bases(a, b); while (exclude) { struct commit *commit = pop_commit(&exclude); show_rev(REVERSED, commit->object.oid.hash, NULL); } } *dotdot = '.'; return 1; } *dotdot = '.'; return 0; } static int try_parent_shorthands(const char *arg) { char *dotdot; unsigned char sha1[20]; struct commit *commit; struct commit_list *parents; int parents_only; if ((dotdot = strstr(arg, "^!"))) parents_only = 0; else if ((dotdot = strstr(arg, "^@"))) parents_only = 1; if (!dotdot || dotdot[2]) return 0; *dotdot = 0; if (get_sha1_committish(arg, sha1)) { *dotdot = '^'; return 0; } if (!parents_only) show_rev(NORMAL, sha1, arg); commit = lookup_commit_reference(sha1); for (parents = commit->parents; parents; parents = parents->next) show_rev(parents_only ? NORMAL : REVERSED, parents->item->object.oid.hash, arg); *dotdot = '^'; return 1; } static int parseopt_dump(const struct option *o, const char *arg, int unset) { struct strbuf *parsed = o->value; if (unset) strbuf_addf(parsed, " --no-%s", o->long_name); else if (o->short_name && (o->long_name == NULL || !stuck_long)) strbuf_addf(parsed, " -%c", o->short_name); else strbuf_addf(parsed, " --%s", o->long_name); if (arg) { if (!stuck_long) strbuf_addch(parsed, ' '); else if (o->long_name) strbuf_addch(parsed, '='); sq_quote_buf(parsed, arg); } return 0; } static const char *skipspaces(const char *s) { while (isspace(*s)) s++; return s; } static int cmd_parseopt(int argc, const char **argv, const char *prefix) { static int keep_dashdash = 0, stop_at_non_option = 0; static char const * const parseopt_usage[] = { N_("git rev-parse --parseopt [<options>] -- [<args>...]"), NULL }; static struct option parseopt_opts[] = { OPT_BOOL(0, "keep-dashdash", &keep_dashdash, N_("keep the `--` passed as an arg")), OPT_BOOL(0, "stop-at-non-option", &stop_at_non_option, N_("stop parsing after the " "first non-option argument")), OPT_BOOL(0, "stuck-long", &stuck_long, N_("output in stuck long form")), OPT_END(), }; static const char * const flag_chars = "*=?!"; struct strbuf sb = STRBUF_INIT, parsed = STRBUF_INIT; const char **usage = NULL; struct option *opts = NULL; int onb = 0, osz = 0, unb = 0, usz = 0; strbuf_addstr(&parsed, "set --"); argc = parse_options(argc, argv, prefix, parseopt_opts, parseopt_usage, PARSE_OPT_KEEP_DASHDASH); if (argc < 1 || strcmp(argv[0], "--")) usage_with_options(parseopt_usage, parseopt_opts); /* get the usage up to the first line with a -- on it */ for (;;) { if (strbuf_getline(&sb, stdin) == EOF) die("premature end of input"); ALLOC_GROW(usage, unb + 1, usz); if (!strcmp("--", sb.buf)) { if (unb < 1) die("no usage string given before the `--' separator"); usage[unb] = NULL; break; } usage[unb++] = strbuf_detach(&sb, NULL); } /* parse: (<short>|<short>,<long>|<long>)[*=?!]*<arghint>? SP+ <help> */ while (strbuf_getline(&sb, stdin) != EOF) { const char *s; const char *help; struct option *o; if (!sb.len) continue; ALLOC_GROW(opts, onb + 1, osz); memset(opts + onb, 0, sizeof(opts[onb])); o = &opts[onb++]; help = strchr(sb.buf, ' '); if (!help || *sb.buf == ' ') { o->type = OPTION_GROUP; o->help = xstrdup(skipspaces(sb.buf)); continue; } o->type = OPTION_CALLBACK; o->help = xstrdup(skipspaces(help)); o->value = &parsed; o->flags = PARSE_OPT_NOARG; o->callback = &parseopt_dump; /* name(s) */ s = strpbrk(sb.buf, flag_chars); if (s == NULL) s = help; if (s - sb.buf == 1) /* short option only */ o->short_name = *sb.buf; else if (sb.buf[1] != ',') /* long option only */ o->long_name = xmemdupz(sb.buf, s - sb.buf); else { o->short_name = *sb.buf; o->long_name = xmemdupz(sb.buf + 2, s - sb.buf - 2); } /* flags */ while (s < help) { switch (*s++) { case '=': o->flags &= ~PARSE_OPT_NOARG; continue; case '?': o->flags &= ~PARSE_OPT_NOARG; o->flags |= PARSE_OPT_OPTARG; continue; case '!': o->flags |= PARSE_OPT_NONEG; continue; case '*': o->flags |= PARSE_OPT_HIDDEN; continue; } s--; break; } if (s < help) o->argh = xmemdupz(s, help - s); } strbuf_release(&sb); /* put an OPT_END() */ ALLOC_GROW(opts, onb + 1, osz); memset(opts + onb, 0, sizeof(opts[onb])); argc = parse_options(argc, argv, prefix, opts, usage, (keep_dashdash ? PARSE_OPT_KEEP_DASHDASH : 0) | (stop_at_non_option ? PARSE_OPT_STOP_AT_NON_OPTION : 0) | PARSE_OPT_SHELL_EVAL); strbuf_addstr(&parsed, " --"); sq_quote_argv(&parsed, argv, 0); puts(parsed.buf); return 0; } static int cmd_sq_quote(int argc, const char **argv) { struct strbuf buf = STRBUF_INIT; if (argc) sq_quote_argv(&buf, argv, 0); printf("%s\n", buf.buf); strbuf_release(&buf); return 0; } static void die_no_single_rev(int quiet) { if (quiet) exit(1); else die("Needed a single revision"); } static const char builtin_rev_parse_usage[] = N_("git rev-parse --parseopt [<options>] -- [<args>...]\n" " or: git rev-parse --sq-quote [<arg>...]\n" " or: git rev-parse [<options>] [<arg>...]\n" "\n" "Run \"git rev-parse --parseopt -h\" for more information on the first usage."); int cmd_rev_parse(int argc, const char **argv, const char *prefix) { int i, as_is = 0, verify = 0, quiet = 0, revs_count = 0, type = 0; int did_repo_setup = 0; int has_dashdash = 0; int output_prefix = 0; unsigned char sha1[20]; unsigned int flags = 0; const char *name = NULL; struct object_context unused; if (argc > 1 && !strcmp("--parseopt", argv[1])) return cmd_parseopt(argc - 1, argv + 1, prefix); if (argc > 1 && !strcmp("--sq-quote", argv[1])) return cmd_sq_quote(argc - 2, argv + 2); if (argc > 1 && !strcmp("-h", argv[1])) usage(builtin_rev_parse_usage); for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "--")) { has_dashdash = 1; break; } } /* No options; just report on whether we're in a git repo or not. */ if (argc == 1) { setup_git_directory(); git_config(git_default_config, NULL); return 0; } for (i = 1; i < argc; i++) { const char *arg = argv[i]; if (!strcmp(arg, "--local-env-vars")) { int i; for (i = 0; local_repo_env[i]; i++) printf("%s\n", local_repo_env[i]); continue; } if (!strcmp(arg, "--resolve-git-dir")) { const char *gitdir = argv[++i]; if (!gitdir) die("--resolve-git-dir requires an argument"); gitdir = resolve_gitdir(gitdir); if (!gitdir) die("not a gitdir '%s'", argv[i]); puts(gitdir); continue; } /* The rest of the options require a git repository. */ if (!did_repo_setup) { prefix = setup_git_directory(); git_config(git_default_config, NULL); did_repo_setup = 1; } if (!strcmp(arg, "--git-path")) { if (!argv[i + 1]) die("--git-path requires an argument"); puts(git_path("%s", argv[i + 1])); i++; continue; } if (as_is) { if (show_file(arg, output_prefix) && as_is < 2) verify_filename(prefix, arg, 0); continue; } if (!strcmp(arg,"-n")) { if (++i >= argc) die("-n requires an argument"); if ((filter & DO_FLAGS) && (filter & DO_REVS)) { show(arg); show(argv[i]); } continue; } if (starts_with(arg, "-n")) { if ((filter & DO_FLAGS) && (filter & DO_REVS)) show(arg); continue; } if (*arg == '-') { if (!strcmp(arg, "--")) { as_is = 2; /* Pass on the "--" if we show anything but files.. */ if (filter & (DO_FLAGS | DO_REVS)) show_file(arg, 0); continue; } if (!strcmp(arg, "--default")) { def = argv[++i]; if (!def) die("--default requires an argument"); continue; } if (!strcmp(arg, "--prefix")) { prefix = argv[++i]; if (!prefix) die("--prefix requires an argument"); startup_info->prefix = prefix; output_prefix = 1; continue; } if (!strcmp(arg, "--revs-only")) { filter &= ~DO_NOREV; continue; } if (!strcmp(arg, "--no-revs")) { filter &= ~DO_REVS; continue; } if (!strcmp(arg, "--flags")) { filter &= ~DO_NONFLAGS; continue; } if (!strcmp(arg, "--no-flags")) { filter &= ~DO_FLAGS; continue; } if (!strcmp(arg, "--verify")) { filter &= ~(DO_FLAGS|DO_NOREV); verify = 1; continue; } if (!strcmp(arg, "--quiet") || !strcmp(arg, "-q")) { quiet = 1; flags |= GET_SHA1_QUIETLY; continue; } if (!strcmp(arg, "--short") || starts_with(arg, "--short=")) { filter &= ~(DO_FLAGS|DO_NOREV); verify = 1; abbrev = DEFAULT_ABBREV; if (arg[7] == '=') abbrev = strtoul(arg + 8, NULL, 10); if (abbrev < MINIMUM_ABBREV) abbrev = MINIMUM_ABBREV; else if (40 <= abbrev) abbrev = 40; continue; } if (!strcmp(arg, "--sq")) { output_sq = 1; continue; } if (!strcmp(arg, "--not")) { show_type ^= REVERSED; continue; } if (!strcmp(arg, "--symbolic")) { symbolic = SHOW_SYMBOLIC_ASIS; continue; } if (!strcmp(arg, "--symbolic-full-name")) { symbolic = SHOW_SYMBOLIC_FULL; continue; } if (starts_with(arg, "--abbrev-ref") && (!arg[12] || arg[12] == '=')) { abbrev_ref = 1; abbrev_ref_strict = warn_ambiguous_refs; if (arg[12] == '=') { if (!strcmp(arg + 13, "strict")) abbrev_ref_strict = 1; else if (!strcmp(arg + 13, "loose")) abbrev_ref_strict = 0; else die("unknown mode for %s", arg); } continue; } if (!strcmp(arg, "--all")) { for_each_ref(show_reference, NULL); continue; } if (starts_with(arg, "--disambiguate=")) { for_each_abbrev(arg + 15, show_abbrev, NULL); continue; } if (!strcmp(arg, "--bisect")) { for_each_ref_in("refs/bisect/bad", show_reference, NULL); for_each_ref_in("refs/bisect/good", anti_reference, NULL); continue; } if (starts_with(arg, "--branches=")) { for_each_glob_ref_in(show_reference, arg + 11, "refs/heads/", NULL); clear_ref_exclusion(&ref_excludes); continue; } if (!strcmp(arg, "--branches")) { for_each_branch_ref(show_reference, NULL); clear_ref_exclusion(&ref_excludes); continue; } if (starts_with(arg, "--tags=")) { for_each_glob_ref_in(show_reference, arg + 7, "refs/tags/", NULL); clear_ref_exclusion(&ref_excludes); continue; } if (!strcmp(arg, "--tags")) { for_each_tag_ref(show_reference, NULL); clear_ref_exclusion(&ref_excludes); continue; } if (starts_with(arg, "--glob=")) { for_each_glob_ref(show_reference, arg + 7, NULL); clear_ref_exclusion(&ref_excludes); continue; } if (starts_with(arg, "--remotes=")) { for_each_glob_ref_in(show_reference, arg + 10, "refs/remotes/", NULL); clear_ref_exclusion(&ref_excludes); continue; } if (!strcmp(arg, "--remotes")) { for_each_remote_ref(show_reference, NULL); clear_ref_exclusion(&ref_excludes); continue; } if (starts_with(arg, "--exclude=")) { add_ref_exclusion(&ref_excludes, arg + 10); continue; } if (!strcmp(arg, "--show-toplevel")) { const char *work_tree = get_git_work_tree(); if (work_tree) puts(work_tree); continue; } if (!strcmp(arg, "--show-prefix")) { if (prefix) puts(prefix); else putchar('\n'); continue; } if (!strcmp(arg, "--show-cdup")) { const char *pfx = prefix; if (!is_inside_work_tree()) { const char *work_tree = get_git_work_tree(); if (work_tree) printf("%s\n", work_tree); continue; } while (pfx) { pfx = strchr(pfx, '/'); if (pfx) { pfx++; printf("../"); } } putchar('\n'); continue; } if (!strcmp(arg, "--git-dir")) { const char *gitdir = getenv(GIT_DIR_ENVIRONMENT); char *cwd; int len; if (gitdir) { puts(gitdir); continue; } if (!prefix) { puts(".git"); continue; } cwd = xgetcwd(); len = strlen(cwd); printf("%s%s.git\n", cwd, len && cwd[len-1] != '/' ? "/" : ""); free(cwd); continue; } if (!strcmp(arg, "--git-common-dir")) { const char *pfx = prefix ? prefix : ""; puts(prefix_filename(pfx, strlen(pfx), get_git_common_dir())); continue; } if (!strcmp(arg, "--is-inside-git-dir")) { printf("%s\n", is_inside_git_dir() ? "true" : "false"); continue; } if (!strcmp(arg, "--is-inside-work-tree")) { printf("%s\n", is_inside_work_tree() ? "true" : "false"); continue; } if (!strcmp(arg, "--is-bare-repository")) { printf("%s\n", is_bare_repository() ? "true" : "false"); continue; } if (!strcmp(arg, "--shared-index-path")) { if (read_cache() < 0) die(_("Could not read the index")); if (the_index.split_index) { const unsigned char *sha1 = the_index.split_index->base_sha1; puts(git_path("sharedindex.%s", sha1_to_hex(sha1))); } continue; } if (starts_with(arg, "--since=")) { show_datestring("--max-age=", arg+8); continue; } if (starts_with(arg, "--after=")) { show_datestring("--max-age=", arg+8); continue; } if (starts_with(arg, "--before=")) { show_datestring("--min-age=", arg+9); continue; } if (starts_with(arg, "--until=")) { show_datestring("--min-age=", arg+8); continue; } if (show_flag(arg) && verify) die_no_single_rev(quiet); continue; } /* Not a flag argument */ if (try_difference(arg)) continue; if (try_parent_shorthands(arg)) continue; name = arg; type = NORMAL; if (*arg == '^') { name++; type = REVERSED; } if (!get_sha1_with_context(name, flags, sha1, &unused)) { if (verify) revs_count++; else show_rev(type, sha1, name); continue; } if (verify) die_no_single_rev(quiet); if (has_dashdash) die("bad revision '%s'", arg); as_is = 1; if (!show_file(arg, output_prefix)) continue; verify_filename(prefix, arg, 1); } if (verify) { if (revs_count == 1) { show_rev(type, sha1, name); return 0; } else if (revs_count == 0 && show_default()) return 0; die_no_single_rev(quiet); } else show_default(); return 0; }
sunny256/git
builtin/rev-parse.c
C
gpl-2.0
20,118
/* * Copyright (C) 2011 Peter Grasch <peter.grasch@bedahr.org> * Copyright (C) 2012 Vladislav Sitalo <root@stvad.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * or (at your option) any later version, as published by the Free * Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef JULIUSRECOGNIZER_H #define JULIUSRECOGNIZER_H #include "recognizer.h" #include <QMutex> #include <QString> #include "simonrecognizer_export.h" class KProcess; class SIMONRECOGNIZER_EXPORT JuliusRecognizer : public Recognizer { private: KProcess *m_juliusProcess; bool isBeingKilled; QMutex recognitionLock; QMutex initializationLock; private: bool blockTillPrompt(QByteArray *data=0); QByteArray readData(); bool startProcess(); public: JuliusRecognizer(); bool init(RecognitionConfiguration* config); QList<RecognitionResult> recognize(const QString& file); bool uninitialize(); virtual ~JuliusRecognizer(); }; #endif // JULIUSRECOGNIZER_H
photom/simon
simonlib/simonrecognizer/juliusrecognizer.h
C
gpl-2.0
1,542
#pragma once #include <OpenEXR/ImathVec.h> #include <string> struct RenderSettings { // maximum path length allowed in the path tracer (1 = direct // illumination only). int m_pathtracerMaxNumBounces; // Max number of accumulated samples before the render finishes int m_pathtracerMaxSamples; // rendered image resolution in pixels Imath::V2i m_imageResolution; // Viewport within which to render the image. This may not match the // resolution of the rendered image, in which case stretching or squashing // will occur. int m_viewport[4]; float m_wireframeOpacity; float m_wireframeThickness; std::string m_backgroundImage; Imath::V3f m_backgroundColor[2]; // gradient (top/bottom) int m_backgroundRotationDegrees; };
joesfer/voxelToy
src/renderer/renderSettings.h
C
gpl-2.0
752
/* $Id: VBoxGuest-win.cpp $ */ /** @file * VBoxGuest - Windows specifics. */ /* * Copyright (C) 2010-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /******************************************************************************* * Header Files * *******************************************************************************/ #define LOG_GROUP LOG_GROUP_SUP_DRV #include "VBoxGuest-win.h" #include "VBoxGuestInternal.h" #include <iprt/asm.h> #include <iprt/asm-amd64-x86.h> #include <VBox/log.h> #include <VBox/VBoxGuestLib.h> #include <iprt/string.h> /* * XP DDK #defines ExFreePool to ExFreePoolWithTag. The latter does not exist * on NT4, so... The same for ExAllocatePool. */ #ifdef TARGET_NT4 # undef ExAllocatePool # undef ExFreePool #endif /******************************************************************************* * Internal Functions * *******************************************************************************/ RT_C_DECLS_BEGIN static NTSTATUS vbgdNtAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj); static void vbgdNtUnload(PDRIVER_OBJECT pDrvObj); static NTSTATUS vbgdNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtInternalIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtRegistryReadDWORD(ULONG ulRoot, PCWSTR pwszPath, PWSTR pwszName, PULONG puValue); static NTSTATUS vbgdNtSystemControl(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtShutdown(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp); #ifdef DEBUG static void vbgdNtDoTests(void); #endif RT_C_DECLS_END /******************************************************************************* * Exported Functions * *******************************************************************************/ RT_C_DECLS_BEGIN ULONG DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath); RT_C_DECLS_END #ifdef ALLOC_PRAGMA # pragma alloc_text(INIT, DriverEntry) # pragma alloc_text(PAGE, vbgdNtAddDevice) # pragma alloc_text(PAGE, vbgdNtUnload) # pragma alloc_text(PAGE, vbgdNtCreate) # pragma alloc_text(PAGE, vbgdNtClose) # pragma alloc_text(PAGE, vbgdNtShutdown) # pragma alloc_text(PAGE, vbgdNtNotSupportedStub) # pragma alloc_text(PAGE, vbgdNtScanPCIResourceList) #endif /******************************************************************************* * Global Variables * *******************************************************************************/ /** The detected NT (windows) version. */ VBGDNTVER g_enmVbgdNtVer = VBGDNTVER_INVALID; /** * Driver entry point. * * @returns appropriate status code. * @param pDrvObj Pointer to driver object. * @param pRegPath Registry base path. */ ULONG DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath) { NTSTATUS rc = STATUS_SUCCESS; LogFunc(("Driver built: %s %s\n", __DATE__, __TIME__)); /* * Check if the the NT version is supported and initializing * g_enmVbgdNtVer in the process. */ ULONG ulMajorVer; ULONG ulMinorVer; ULONG ulBuildNo; BOOLEAN fCheckedBuild = PsGetVersion(&ulMajorVer, &ulMinorVer, &ulBuildNo, NULL); /* Use RTLogBackdoorPrintf to make sure that this goes to VBox.log */ RTLogBackdoorPrintf("VBoxGuest: Windows version %u.%u, build %u\n", ulMajorVer, ulMinorVer, ulBuildNo); if (fCheckedBuild) RTLogBackdoorPrintf("VBoxGuest: Windows checked build\n"); #ifdef DEBUG vbgdNtDoTests(); #endif switch (ulMajorVer) { case 10: switch (ulMinorVer) { case 0: /* Windows 10 Preview builds starting with 9926. */ default: /* Also everything newer. */ g_enmVbgdNtVer = VBGDNTVER_WIN10; break; } break; case 6: /* Windows Vista or Windows 7 (based on minor ver) */ switch (ulMinorVer) { case 0: /* Note: Also could be Windows 2008 Server! */ g_enmVbgdNtVer = VBGDNTVER_WINVISTA; break; case 1: /* Note: Also could be Windows 2008 Server R2! */ g_enmVbgdNtVer = VBGDNTVER_WIN7; break; case 2: g_enmVbgdNtVer = VBGDNTVER_WIN8; break; case 3: g_enmVbgdNtVer = VBGDNTVER_WIN81; break; case 4: /* Windows 10 Preview builds. */ default: /* Also everything newer. */ g_enmVbgdNtVer = VBGDNTVER_WIN10; break; } break; case 5: switch (ulMinorVer) { default: case 2: g_enmVbgdNtVer = VBGDNTVER_WIN2K3; break; case 1: g_enmVbgdNtVer = VBGDNTVER_WINXP; break; case 0: g_enmVbgdNtVer = VBGDNTVER_WIN2K; break; } break; case 4: g_enmVbgdNtVer = VBGDNTVER_WINNT4; break; default: if (ulMajorVer > 6) { /* "Windows 10 mode" for Windows 8.1+. */ g_enmVbgdNtVer = VBGDNTVER_WIN10; } else { if (ulMajorVer < 4) LogRelFunc(("At least Windows NT4 required! (%u.%u)\n", ulMajorVer, ulMinorVer)); else LogRelFunc(("Unknown version %u.%u!\n", ulMajorVer, ulMinorVer)); rc = STATUS_DRIVER_UNABLE_TO_LOAD; } break; } if (NT_SUCCESS(rc)) { /* * Setup the driver entry points in pDrvObj. */ pDrvObj->DriverUnload = vbgdNtUnload; pDrvObj->MajorFunction[IRP_MJ_CREATE] = vbgdNtCreate; pDrvObj->MajorFunction[IRP_MJ_CLOSE] = vbgdNtClose; pDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = vbgdNtIOCtl; pDrvObj->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = vbgdNtInternalIOCtl; pDrvObj->MajorFunction[IRP_MJ_SHUTDOWN] = vbgdNtShutdown; pDrvObj->MajorFunction[IRP_MJ_READ] = vbgdNtNotSupportedStub; pDrvObj->MajorFunction[IRP_MJ_WRITE] = vbgdNtNotSupportedStub; #ifdef TARGET_NT4 rc = vbgdNt4CreateDevice(pDrvObj, NULL /* pDevObj */, pRegPath); #else pDrvObj->MajorFunction[IRP_MJ_PNP] = vbgdNtPnP; pDrvObj->MajorFunction[IRP_MJ_POWER] = vbgdNtPower; pDrvObj->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = vbgdNtSystemControl; pDrvObj->DriverExtension->AddDevice = (PDRIVER_ADD_DEVICE)vbgdNtAddDevice; #endif } LogFlowFunc(("Returning %#x\n", rc)); return rc; } #ifndef TARGET_NT4 /** * Handle request from the Plug & Play subsystem. * * @returns NT status code * @param pDrvObj Driver object * @param pDevObj Device object */ static NTSTATUS vbgdNtAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj) { NTSTATUS rc; LogFlowFuncEnter(); /* * Create device. */ UNICODE_STRING DevName; RtlInitUnicodeString(&DevName, VBOXGUEST_DEVICE_NAME_NT); PDEVICE_OBJECT pDeviceObject = NULL; rc = IoCreateDevice(pDrvObj, sizeof(VBOXGUESTDEVEXTWIN), &DevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject); if (NT_SUCCESS(rc)) { /* * Create symbolic link (DOS devices). */ UNICODE_STRING DosName; RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS); rc = IoCreateSymbolicLink(&DosName, &DevName); if (NT_SUCCESS(rc)) { /* * Setup the device extension. */ PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDeviceObject->DeviceExtension; RT_ZERO(*pDevExt); KeInitializeSpinLock(&pDevExt->MouseEventAccessLock); pDevExt->pDeviceObject = pDeviceObject; pDevExt->prevDevState = STOPPED; pDevExt->devState = STOPPED; pDevExt->pNextLowerDriver = IoAttachDeviceToDeviceStack(pDeviceObject, pDevObj); if (pDevExt->pNextLowerDriver != NULL) { /* * If we reached this point we're fine with the basic driver setup, * so continue to init our own things. */ #ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION vbgdNtBugCheckCallback(pDevExt); /* Ignore failure! */ #endif if (NT_SUCCESS(rc)) { /* VBoxGuestPower is pageable; ensure we are not called at elevated IRQL */ pDeviceObject->Flags |= DO_POWER_PAGABLE; /* Driver is ready now. */ pDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; LogFlowFunc(("Returning with rc=0x%x (success)\n", rc)); return rc; } IoDetachDevice(pDevExt->pNextLowerDriver); } else { LogFunc(("IoAttachDeviceToDeviceStack did not give a nextLowerDriver!\n")); rc = STATUS_DEVICE_NOT_CONNECTED; } /* bail out */ IoDeleteSymbolicLink(&DosName); } else LogFunc(("IoCreateSymbolicLink failed with rc=%#x!\n", rc)); IoDeleteDevice(pDeviceObject); } else LogFunc(("IoCreateDevice failed with rc=%#x!\n", rc)); LogFunc(("Returning with rc=0x%x\n", rc)); return rc; } #endif /** * Debug helper to dump a device resource list. * * @param pResourceList list of device resources. */ static void vbgdNtShowDeviceResources(PCM_PARTIAL_RESOURCE_LIST pResourceList) { #ifdef LOG_ENABLED PCM_PARTIAL_RESOURCE_DESCRIPTOR pResource = pResourceList->PartialDescriptors; ULONG cResources = pResourceList->Count; for (ULONG i = 0; i < cResources; ++i, ++pResource) { ULONG uType = pResource->Type; static char const * const s_apszName[] = { "CmResourceTypeNull", "CmResourceTypePort", "CmResourceTypeInterrupt", "CmResourceTypeMemory", "CmResourceTypeDma", "CmResourceTypeDeviceSpecific", "CmResourceTypeBusNumber", "CmResourceTypeDevicePrivate", "CmResourceTypeAssignedResource", "CmResourceTypeSubAllocateFrom", }; LogFunc(("Type=%s", uType < RT_ELEMENTS(s_apszName) ? s_apszName[uType] : "Unknown")); switch (uType) { case CmResourceTypePort: case CmResourceTypeMemory: LogFunc(("Start %8X%8.8lX, length=%X\n", pResource->u.Port.Start.HighPart, pResource->u.Port.Start.LowPart, pResource->u.Port.Length)); break; case CmResourceTypeInterrupt: LogFunc(("Level=%X, vector=%X, affinity=%X\n", pResource->u.Interrupt.Level, pResource->u.Interrupt.Vector, pResource->u.Interrupt.Affinity)); break; case CmResourceTypeDma: LogFunc(("Channel %d, Port %X\n", pResource->u.Dma.Channel, pResource->u.Dma.Port)); break; default: LogFunc(("\n")); break; } } #endif } /** * Global initialisation stuff (PnP + NT4 legacy). * * @param pDevObj Device object. * @param pIrp Request packet. */ #ifndef TARGET_NT4 NTSTATUS vbgdNtInit(PDEVICE_OBJECT pDevObj, PIRP pIrp) #else NTSTATUS vbgdNtInit(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj, PUNICODE_STRING pRegPath) #endif { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; #ifndef TARGET_NT4 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); #endif LogFlowFuncEnter(); int rc = STATUS_SUCCESS; /** @todo r=bird: s/rc/rcNt/ and s/int/NTSTATUS/. gee. */ #ifdef TARGET_NT4 /* * Let's have a look at what our PCI adapter offers. */ LogFlowFunc(("Starting to scan PCI resources of VBoxGuest ...\n")); /* Assign the PCI resources. */ PCM_RESOURCE_LIST pResourceList = NULL; UNICODE_STRING classNameString; RtlInitUnicodeString(&classNameString, L"VBoxGuestAdapter"); rc = HalAssignSlotResources(pRegPath, &classNameString, pDrvObj, pDevObj, PCIBus, pDevExt->busNumber, pDevExt->slotNumber, &pResourceList); if (pResourceList && pResourceList->Count > 0) vbgdNtShowDeviceResources(&pResourceList->List[0].PartialResourceList); if (NT_SUCCESS(rc)) rc = vbgdNtScanPCIResourceList(pResourceList, pDevExt); #else if (pStack->Parameters.StartDevice.AllocatedResources->Count > 0) vbgdNtShowDeviceResources(&pStack->Parameters.StartDevice.AllocatedResources->List[0].PartialResourceList); if (NT_SUCCESS(rc)) rc = vbgdNtScanPCIResourceList(pStack->Parameters.StartDevice.AllocatedResourcesTranslated, pDevExt); #endif if (NT_SUCCESS(rc)) { /* * Map physical address of VMMDev memory into MMIO region * and init the common device extension bits. */ void *pvMMIOBase = NULL; uint32_t cbMMIO = 0; rc = vbgdNtMapVMMDevMemory(pDevExt, pDevExt->vmmDevPhysMemoryAddress, pDevExt->vmmDevPhysMemoryLength, &pvMMIOBase, &cbMMIO); if (NT_SUCCESS(rc)) { pDevExt->Core.pVMMDevMemory = (VMMDevMemory *)pvMMIOBase; LogFunc(("pvMMIOBase=0x%p, pDevExt=0x%p, pDevExt->Core.pVMMDevMemory=0x%p\n", pvMMIOBase, pDevExt, pDevExt ? pDevExt->Core.pVMMDevMemory : NULL)); int vrc = VbgdCommonInitDevExt(&pDevExt->Core, pDevExt->Core.IOPortBase, pvMMIOBase, cbMMIO, vbgdNtVersionToOSType(g_enmVbgdNtVer), VMMDEV_EVENT_MOUSE_POSITION_CHANGED); if (RT_FAILURE(vrc)) { LogFunc(("Could not init device extension, rc=%Rrc\n", vrc)); rc = STATUS_DEVICE_CONFIGURATION_ERROR; } } else LogFunc(("Could not map physical address of VMMDev, rc=0x%x\n", rc)); } if (NT_SUCCESS(rc)) { int vrc = VbglGRAlloc((VMMDevRequestHeader **)&pDevExt->pPowerStateRequest, sizeof(VMMDevPowerStateRequest), VMMDevReq_SetPowerStatus); if (RT_FAILURE(vrc)) { LogFunc(("Alloc for pPowerStateRequest failed, rc=%Rrc\n", vrc)); rc = STATUS_UNSUCCESSFUL; } } if (NT_SUCCESS(rc)) { /* * Register DPC and ISR. */ LogFlowFunc(("Initializing DPC/ISR ...\n")); IoInitializeDpcRequest(pDevExt->pDeviceObject, vbgdNtDpcHandler); #ifdef TARGET_NT4 ULONG uInterruptVector; KIRQL irqLevel; /* Get an interrupt vector. */ /* Only proceed if the device provides an interrupt. */ if ( pDevExt->interruptLevel || pDevExt->interruptVector) { LogFlowFunc(("Getting interrupt vector (HAL): Bus=%u, IRQL=%u, Vector=%u\n", pDevExt->busNumber, pDevExt->interruptLevel, pDevExt->interruptVector)); uInterruptVector = HalGetInterruptVector(PCIBus, pDevExt->busNumber, pDevExt->interruptLevel, pDevExt->interruptVector, &irqLevel, &pDevExt->interruptAffinity); LogFlowFunc(("HalGetInterruptVector returns vector=%u\n", uInterruptVector)); if (uInterruptVector == 0) LogFunc(("No interrupt vector found!\n")); } else LogFunc(("Device does not provide an interrupt!\n")); #endif if (pDevExt->interruptVector) { LogFlowFunc(("Connecting interrupt ...\n")); rc = IoConnectInterrupt(&pDevExt->pInterruptObject, /* Out: interrupt object. */ (PKSERVICE_ROUTINE)vbgdNtIsrHandler, /* Our ISR handler. */ pDevExt, /* Device context. */ NULL, /* Optional spinlock. */ #ifdef TARGET_NT4 uInterruptVector, /* Interrupt vector. */ irqLevel, /* Interrupt level. */ irqLevel, /* Interrupt level. */ #else pDevExt->interruptVector, /* Interrupt vector. */ (KIRQL)pDevExt->interruptLevel, /* Interrupt level. */ (KIRQL)pDevExt->interruptLevel, /* Interrupt level. */ #endif pDevExt->interruptMode, /* LevelSensitive or Latched. */ TRUE, /* Shareable interrupt. */ pDevExt->interruptAffinity, /* CPU affinity. */ FALSE); /* Don't save FPU stack. */ if (NT_ERROR(rc)) LogFunc(("Could not connect interrupt, rc=0x%x\n", rc)); } else LogFunc(("No interrupt vector found!\n")); } #ifdef VBOX_WITH_HGCM LogFunc(("Allocating kernel session data ...\n")); int vrc = VbgdCommonCreateKernelSession(&pDevExt->Core, &pDevExt->pKernelSession); if (RT_FAILURE(vrc)) { LogFunc(("Failed to allocated kernel session data, rc=%Rrc\n", rc)); rc = STATUS_UNSUCCESSFUL; } #endif if (RT_SUCCESS(rc)) { ULONG ulValue = 0; NTSTATUS rcNt = vbgdNtRegistryReadDWORD(RTL_REGISTRY_SERVICES, L"VBoxGuest", L"LoggingEnabled", &ulValue); if (NT_SUCCESS(rcNt)) { pDevExt->Core.fLoggingEnabled = ulValue >= 0xFF; if (pDevExt->Core.fLoggingEnabled) LogRelFunc(("Logging to host log enabled (0x%x)", ulValue)); } /* Ready to rumble! */ LogRelFunc(("Device is ready!\n")); VBOXGUEST_UPDATE_DEVSTATE(pDevExt, WORKING); } else pDevExt->pInterruptObject = NULL; /** @todo r=bird: The error cleanup here is completely missing. We'll leak a * whole bunch of things... */ LogFunc(("Returned with rc=0x%x\n", rc)); return rc; } /** * Cleans up hardware resources. * Do not delete DevExt here. * * @param pDrvObj Driver object. */ NTSTATUS vbgdNtCleanup(PDEVICE_OBJECT pDevObj) { LogFlowFuncEnter(); PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; if (pDevExt) { #if 0 /* @todo: test & enable cleaning global session data */ #ifdef VBOX_WITH_HGCM if (pDevExt->pKernelSession) { VbgdCommonCloseSession(pDevExt, pDevExt->pKernelSession); pDevExt->pKernelSession = NULL; } #endif #endif if (pDevExt->pInterruptObject) { IoDisconnectInterrupt(pDevExt->pInterruptObject); pDevExt->pInterruptObject = NULL; } /** @todo: cleanup the rest stuff */ #ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION hlpDeregisterBugCheckCallback(pDevExt); /* ignore failure! */ #endif /* According to MSDN we have to unmap previously mapped memory. */ vbgdNtUnmapVMMDevMemory(pDevExt); } return STATUS_SUCCESS; } /** * Unload the driver. * * @param pDrvObj Driver object. */ static void vbgdNtUnload(PDRIVER_OBJECT pDrvObj) { LogFlowFuncEnter(); #ifdef TARGET_NT4 vbgdNtCleanup(pDrvObj->DeviceObject); /* Destroy device extension and clean up everything else. */ if (pDrvObj->DeviceObject && pDrvObj->DeviceObject->DeviceExtension) VbgdCommonDeleteDevExt((PVBOXGUESTDEVEXT)pDrvObj->DeviceObject->DeviceExtension); /* * I don't think it's possible to unload a driver which processes have * opened, at least we'll blindly assume that here. */ UNICODE_STRING DosName; RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS); NTSTATUS rc = IoDeleteSymbolicLink(&DosName); IoDeleteDevice(pDrvObj->DeviceObject); #else /* !TARGET_NT4 */ /* On a PnP driver this routine will be called after * IRP_MN_REMOVE_DEVICE (where we already did the cleanup), * so don't do anything here (yet). */ #endif /* !TARGET_NT4 */ LogFlowFunc(("Returning\n")); } /** * Create (i.e. Open) file entry point. * * @param pDevObj Device object. * @param pIrp Request packet. */ static NTSTATUS vbgdNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp) { /** @todo AssertPtrReturn(pIrp); */ PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); /** @todo AssertPtrReturn(pStack); */ PFILE_OBJECT pFileObj = pStack->FileObject; PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; NTSTATUS rc = STATUS_SUCCESS; if (pDevExt->devState != WORKING) { LogFunc(("Device is not working currently, state=%d\n", pDevExt->devState)); rc = STATUS_UNSUCCESSFUL; } else if (pStack->Parameters.Create.Options & FILE_DIRECTORY_FILE) { /* * We are not remotely similar to a directory... * (But this is possible.) */ LogFlowFunc(("Uhm, we're not a directory!\n")); rc = STATUS_NOT_A_DIRECTORY; } else { #ifdef VBOX_WITH_HGCM if (pFileObj) { LogFlowFunc(("File object type=%d\n", pFileObj->Type)); int vrc; PVBOXGUESTSESSION pSession; if (pFileObj->Type == 5 /* File Object */) { /* * Create a session object if we have a valid file object. This session object * exists for every R3 process. */ vrc = VbgdCommonCreateUserSession(&pDevExt->Core, &pSession); } else { /* ... otherwise we've been called from R0! */ vrc = VbgdCommonCreateKernelSession(&pDevExt->Core, &pSession); } if (RT_SUCCESS(vrc)) pFileObj->FsContext = pSession; } #endif } /* Complete the request! */ pIrp->IoStatus.Information = 0; pIrp->IoStatus.Status = rc; IoCompleteRequest(pIrp, IO_NO_INCREMENT); LogFlowFunc(("Returning rc=0x%x\n", rc)); return rc; } /** * Close file entry point. * * @param pDevObj Device object. * @param pIrp Request packet. */ static NTSTATUS vbgdNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFileObj = pStack->FileObject; LogFlowFunc(("pDevExt=0x%p, pFileObj=0x%p, FsContext=0x%p\n", pDevExt, pFileObj, pFileObj->FsContext)); #ifdef VBOX_WITH_HGCM /* Close both, R0 and R3 sessions. */ PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)pFileObj->FsContext; if (pSession) VbgdCommonCloseSession(&pDevExt->Core, pSession); #endif pFileObj->FsContext = NULL; pIrp->IoStatus.Information = 0; pIrp->IoStatus.Status = STATUS_SUCCESS; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return STATUS_SUCCESS; } /** * Device I/O Control entry point. * * @param pDevObj Device object. * @param pIrp Request packet. */ static NTSTATUS vbgdNtIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp) { NTSTATUS Status = STATUS_SUCCESS; PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); unsigned int uCmd = (unsigned int)pStack->Parameters.DeviceIoControl.IoControlCode; char *pBuf = (char *)pIrp->AssociatedIrp.SystemBuffer; /* All requests are buffered. */ size_t cbData = pStack->Parameters.DeviceIoControl.InputBufferLength; size_t cbOut = 0; /* Do we have a file object associated?*/ PFILE_OBJECT pFileObj = pStack->FileObject; PVBOXGUESTSESSION pSession = NULL; if (pFileObj) /* ... then we might have a session object as well! */ pSession = (PVBOXGUESTSESSION)pFileObj->FsContext; LogFlowFunc(("uCmd=%u, pDevExt=0x%p, pSession=0x%p\n", uCmd, pDevExt, pSession)); /* We don't have a session associated with the file object? So this seems * to be a kernel call then. */ /** @todo r=bird: What on earth is this supposed to be? Each kernel session * shall have its own context of course, no hacks, pleeease. */ if (pSession == NULL) { LogFunc(("XXX: BUGBUG: FIXME: Using ugly kernel session data hack ...\n")); #ifdef DEBUG_andy RTLogBackdoorPrintf("XXX: BUGBUG: FIXME: Using ugly kernel session data hack ... Please don't forget to fix this one, Andy!\n"); #endif pSession = pDevExt->pKernelSession; } /* Verify that it's a buffered CTL. */ if ((pStack->Parameters.DeviceIoControl.IoControlCode & 0x3) == METHOD_BUFFERED) { /* * Process the common IOCtls. */ size_t cbDataReturned; int vrc = VbgdCommonIoCtl(uCmd, &pDevExt->Core, pSession, pBuf, cbData, &cbDataReturned); LogFlowFunc(("rc=%Rrc, pBuf=0x%p, cbData=%u, cbDataReturned=%u\n", vrc, pBuf, cbData, cbDataReturned)); if (RT_SUCCESS(vrc)) { if (RT_UNLIKELY( cbDataReturned > cbData || cbDataReturned > pStack->Parameters.DeviceIoControl.OutputBufferLength)) { LogFunc(("Too much output data %u - expected %u!\n", cbDataReturned, cbData)); cbDataReturned = cbData; Status = STATUS_BUFFER_TOO_SMALL; } if (cbDataReturned > 0) cbOut = cbDataReturned; } else { if ( vrc == VERR_NOT_SUPPORTED || vrc == VERR_INVALID_PARAMETER) Status = STATUS_INVALID_PARAMETER; else if (vrc == VERR_OUT_OF_RANGE) Status = STATUS_INVALID_BUFFER_SIZE; else Status = STATUS_UNSUCCESSFUL; } } else { LogFunc(("Not buffered request (%#x) - not supported\n", pStack->Parameters.DeviceIoControl.IoControlCode)); Status = STATUS_NOT_SUPPORTED; } pIrp->IoStatus.Status = Status; pIrp->IoStatus.Information = cbOut; IoCompleteRequest(pIrp, IO_NO_INCREMENT); //LogFlowFunc(("Returned cbOut=%d rc=%#x\n", cbOut, Status)); return Status; } /** * Internal Device I/O Control entry point. * * @param pDevObj Device object. * @param pIrp Request packet. */ static NTSTATUS vbgdNtInternalIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp) { NTSTATUS Status = STATUS_SUCCESS; PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); unsigned int uCmd = (unsigned int)pStack->Parameters.DeviceIoControl.IoControlCode; bool fProcessed = false; unsigned Info = 0; /* * Override common behavior of some operations. */ /** @todo r=bird: Better to add dedicated worker functions for this! */ switch (uCmd) { case VBOXGUEST_IOCTL_SET_MOUSE_NOTIFY_CALLBACK: { PVOID pvBuf = pStack->Parameters.Others.Argument1; size_t cbData = (size_t)pStack->Parameters.Others.Argument2; fProcessed = true; if (cbData != sizeof(VBoxGuestMouseSetNotifyCallback)) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } VBoxGuestMouseSetNotifyCallback *pInfo = (VBoxGuestMouseSetNotifyCallback*)pvBuf; /* we need a lock here to avoid concurrency with the set event functionality */ KIRQL OldIrql; KeAcquireSpinLock(&pDevExt->MouseEventAccessLock, &OldIrql); pDevExt->Core.MouseNotifyCallback = *pInfo; KeReleaseSpinLock(&pDevExt->MouseEventAccessLock, OldIrql); Status = STATUS_SUCCESS; break; } default: break; } if (fProcessed) { pIrp->IoStatus.Status = Status; pIrp->IoStatus.Information = Info; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return Status; } /* * No override, go to common code. */ return vbgdNtIOCtl(pDevObj, pIrp); } /** * IRP_MJ_SYSTEM_CONTROL handler. * * @returns NT status code * @param pDevObj Device object. * @param pIrp IRP. */ NTSTATUS vbgdNtSystemControl(PDEVICE_OBJECT pDevObj, PIRP pIrp) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; LogFlowFuncEnter(); /* Always pass it on to the next driver. */ IoSkipCurrentIrpStackLocation(pIrp); return IoCallDriver(pDevExt->pNextLowerDriver, pIrp); } /** * IRP_MJ_SHUTDOWN handler. * * @returns NT status code * @param pDevObj Device object. * @param pIrp IRP. */ NTSTATUS vbgdNtShutdown(PDEVICE_OBJECT pDevObj, PIRP pIrp) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; LogFlowFuncEnter(); VMMDevPowerStateRequest *pReq = pDevExt->pPowerStateRequest; if (pReq) { pReq->header.requestType = VMMDevReq_SetPowerStatus; pReq->powerState = VMMDevPowerState_PowerOff; int rc = VbglGRPerform(&pReq->header); if (RT_FAILURE(rc)) LogFunc(("Error performing request to VMMDev, rc=%Rrc\n", rc)); } return STATUS_SUCCESS; } /** * Stub function for functions we don't implemented. * * @returns STATUS_NOT_SUPPORTED * @param pDevObj Device object. * @param pIrp IRP. */ NTSTATUS vbgdNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp) { LogFlowFuncEnter(); pIrp->IoStatus.Information = 0; pIrp->IoStatus.Status = STATUS_NOT_SUPPORTED; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return STATUS_NOT_SUPPORTED; } /** * DPC handler. * * @param pDPC DPC descriptor. * @param pDevObj Device object. * @param pIrp Interrupt request packet. * @param pContext Context specific pointer. */ void vbgdNtDpcHandler(PKDPC pDPC, PDEVICE_OBJECT pDevObj, PIRP pIrp, PVOID pContext) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; Log3Func(("pDevExt=0x%p\n", pDevExt)); /* Test & reset the counter. */ if (ASMAtomicXchgU32(&pDevExt->Core.u32MousePosChangedSeq, 0)) { /* we need a lock here to avoid concurrency with the set event ioctl handler thread, * i.e. to prevent the event from destroyed while we're using it */ Assert(KeGetCurrentIrql() == DISPATCH_LEVEL); KeAcquireSpinLockAtDpcLevel(&pDevExt->MouseEventAccessLock); if (pDevExt->Core.MouseNotifyCallback.pfnNotify) pDevExt->Core.MouseNotifyCallback.pfnNotify(pDevExt->Core.MouseNotifyCallback.pvUser); KeReleaseSpinLockFromDpcLevel(&pDevExt->MouseEventAccessLock); } /* Process the wake-up list we were asked by the scheduling a DPC * in vbgdNtIsrHandler(). */ VbgdCommonWaitDoWakeUps(&pDevExt->Core); } /** * ISR handler. * * @return BOOLEAN Indicates whether the IRQ came from us (TRUE) or not (FALSE). * @param pInterrupt Interrupt that was triggered. * @param pServiceContext Context specific pointer. */ BOOLEAN vbgdNtIsrHandler(PKINTERRUPT pInterrupt, PVOID pServiceContext) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pServiceContext; if (pDevExt == NULL) return FALSE; /*Log3Func(("pDevExt=0x%p, pVMMDevMemory=0x%p\n", pDevExt, pDevExt ? pDevExt->pVMMDevMemory : NULL));*/ /* Enter the common ISR routine and do the actual work. */ BOOLEAN fIRQTaken = VbgdCommonISR(&pDevExt->Core); /* If we need to wake up some events we do that in a DPC to make * sure we're called at the right IRQL. */ if (fIRQTaken) { Log3Func(("IRQ was taken! pInterrupt=0x%p, pDevExt=0x%p\n", pInterrupt, pDevExt)); if (ASMAtomicUoReadU32( &pDevExt->Core.u32MousePosChangedSeq) || !RTListIsEmpty(&pDevExt->Core.WakeUpList)) { Log3Func(("Requesting DPC ...\n")); IoRequestDpc(pDevExt->pDeviceObject, pDevExt->pCurrentIrp, NULL); } } return fIRQTaken; } /** * Overridden routine for mouse polling events. * * @param pDevExt Device extension structure. */ void VbgdNativeISRMousePollEvent(PVBOXGUESTDEVEXT pDevExt) { NOREF(pDevExt); /* nothing to do here - i.e. since we can not KeSetEvent from ISR level, * we rely on the pDevExt->u32MousePosChangedSeq to be set to a non-zero value on a mouse event * and queue the DPC in our ISR routine in that case doing KeSetEvent from the DPC routine */ } /** * Queries (gets) a DWORD value from the registry. * * @return NTSTATUS * @param ulRoot Relative path root. See RTL_REGISTRY_SERVICES or RTL_REGISTRY_ABSOLUTE. * @param pwszPath Path inside path root. * @param pwszName Actual value name to look up. * @param puValue On input this can specify the default value (if RTL_REGISTRY_OPTIONAL is * not specified in ulRoot), on output this will retrieve the looked up * registry value if found. */ NTSTATUS vbgdNtRegistryReadDWORD(ULONG ulRoot, PCWSTR pwszPath, PWSTR pwszName, PULONG puValue) { if (!pwszPath || !pwszName || !puValue) return STATUS_INVALID_PARAMETER; ULONG ulDefault = *puValue; RTL_QUERY_REGISTRY_TABLE tblQuery[2]; RtlZeroMemory(tblQuery, sizeof(tblQuery)); /** @todo Add RTL_QUERY_REGISTRY_TYPECHECK! */ tblQuery[0].Flags = RTL_QUERY_REGISTRY_DIRECT; tblQuery[0].Name = pwszName; tblQuery[0].EntryContext = puValue; tblQuery[0].DefaultType = REG_DWORD; tblQuery[0].DefaultData = &ulDefault; tblQuery[0].DefaultLength = sizeof(ULONG); return RtlQueryRegistryValues(ulRoot, pwszPath, &tblQuery[0], NULL /* Context */, NULL /* Environment */); } /** * Helper to scan the PCI resource list and remember stuff. * * @param pResList Resource list * @param pDevExt Device extension */ NTSTATUS vbgdNtScanPCIResourceList(PCM_RESOURCE_LIST pResList, PVBOXGUESTDEVEXTWIN pDevExt) { /* Enumerate the resource list. */ LogFlowFunc(("Found %d resources\n", pResList->List->PartialResourceList.Count)); NTSTATUS rc = STATUS_SUCCESS; PCM_PARTIAL_RESOURCE_DESCRIPTOR pPartialData = NULL; ULONG rangeCount = 0; ULONG cMMIORange = 0; PVBOXGUESTWINBASEADDRESS pBaseAddress = pDevExt->pciBaseAddress; for (ULONG i = 0; i < pResList->List->PartialResourceList.Count; i++) { pPartialData = &pResList->List->PartialResourceList.PartialDescriptors[i]; switch (pPartialData->Type) { case CmResourceTypePort: { /* Overflow protection. */ if (rangeCount < PCI_TYPE0_ADDRESSES) { LogFlowFunc(("I/O range: Base=%08x:%08x, length=%08x\n", pPartialData->u.Port.Start.HighPart, pPartialData->u.Port.Start.LowPart, pPartialData->u.Port.Length)); /* Save the IO port base. */ /** @todo Not so good. * Update/bird: What is not so good? That we just consider the last range? */ pDevExt->Core.IOPortBase = (RTIOPORT)pPartialData->u.Port.Start.LowPart; /* Save resource information. */ pBaseAddress->RangeStart = pPartialData->u.Port.Start; pBaseAddress->RangeLength = pPartialData->u.Port.Length; pBaseAddress->RangeInMemory = FALSE; pBaseAddress->ResourceMapped = FALSE; LogFunc(("I/O range for VMMDev found! Base=%08x:%08x, length=%08x\n", pPartialData->u.Port.Start.HighPart, pPartialData->u.Port.Start.LowPart, pPartialData->u.Port.Length)); /* Next item ... */ rangeCount++; pBaseAddress++; } break; } case CmResourceTypeInterrupt: { LogFunc(("Interrupt: Level=%x, vector=%x, mode=%x\n", pPartialData->u.Interrupt.Level, pPartialData->u.Interrupt.Vector, pPartialData->Flags)); /* Save information. */ pDevExt->interruptLevel = pPartialData->u.Interrupt.Level; pDevExt->interruptVector = pPartialData->u.Interrupt.Vector; pDevExt->interruptAffinity = pPartialData->u.Interrupt.Affinity; /* Check interrupt mode. */ if (pPartialData->Flags & CM_RESOURCE_INTERRUPT_LATCHED) pDevExt->interruptMode = Latched; else pDevExt->interruptMode = LevelSensitive; break; } case CmResourceTypeMemory: { /* Overflow protection. */ if (rangeCount < PCI_TYPE0_ADDRESSES) { LogFlowFunc(("Memory range: Base=%08x:%08x, length=%08x\n", pPartialData->u.Memory.Start.HighPart, pPartialData->u.Memory.Start.LowPart, pPartialData->u.Memory.Length)); /* We only care about read/write memory. */ /** @todo Reconsider memory type. */ if ( cMMIORange == 0 /* Only care about the first MMIO range (!!!). */ && (pPartialData->Flags & VBOX_CM_PRE_VISTA_MASK) == CM_RESOURCE_MEMORY_READ_WRITE) { /* Save physical MMIO base + length for VMMDev. */ pDevExt->vmmDevPhysMemoryAddress = pPartialData->u.Memory.Start; pDevExt->vmmDevPhysMemoryLength = (ULONG)pPartialData->u.Memory.Length; /* Save resource information. */ pBaseAddress->RangeStart = pPartialData->u.Memory.Start; pBaseAddress->RangeLength = pPartialData->u.Memory.Length; pBaseAddress->RangeInMemory = TRUE; pBaseAddress->ResourceMapped = FALSE; LogFunc(("Memory range for VMMDev found! Base = %08x:%08x, Length = %08x\n", pPartialData->u.Memory.Start.HighPart, pPartialData->u.Memory.Start.LowPart, pPartialData->u.Memory.Length)); /* Next item ... */ rangeCount++; pBaseAddress++; cMMIORange++; } else LogFunc(("Ignoring memory: Flags=%08x\n", pPartialData->Flags)); } break; } default: { LogFunc(("Unhandled resource found, type=%d\n", pPartialData->Type)); break; } } } /* Memorize the number of resources found. */ pDevExt->pciAddressCount = rangeCount; return rc; } /** * Maps the I/O space from VMMDev to virtual kernel address space. * * @return NTSTATUS * * @param pDevExt The device extension. * @param PhysAddr Physical address to map. * @param cbToMap Number of bytes to map. * @param ppvMMIOBase Pointer of mapped I/O base. * @param pcbMMIO Length of mapped I/O base. */ NTSTATUS vbgdNtMapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt, PHYSICAL_ADDRESS PhysAddr, ULONG cbToMap, void **ppvMMIOBase, uint32_t *pcbMMIO) { AssertPtrReturn(pDevExt, VERR_INVALID_POINTER); AssertPtrReturn(ppvMMIOBase, VERR_INVALID_POINTER); /* pcbMMIO is optional. */ NTSTATUS rc = STATUS_SUCCESS; if (PhysAddr.LowPart > 0) /* We're mapping below 4GB. */ { VMMDevMemory *pVMMDevMemory = (VMMDevMemory *)MmMapIoSpace(PhysAddr, cbToMap, MmNonCached); LogFlowFunc(("pVMMDevMemory = 0x%x\n", pVMMDevMemory)); if (pVMMDevMemory) { LogFunc(("VMMDevMemory: Version = 0x%x, Size = %d\n", pVMMDevMemory->u32Version, pVMMDevMemory->u32Size)); /* Check version of the structure; do we have the right memory version? */ if (pVMMDevMemory->u32Version == VMMDEV_MEMORY_VERSION) { /* Save results. */ *ppvMMIOBase = pVMMDevMemory; if (pcbMMIO) /* Optional. */ *pcbMMIO = pVMMDevMemory->u32Size; LogFlowFunc(("VMMDevMemory found and mapped! pvMMIOBase = 0x%p\n", *ppvMMIOBase)); } else { /* Not our version, refuse operation and unmap the memory. */ LogFunc(("Wrong version (%u), refusing operation!\n", pVMMDevMemory->u32Version)); vbgdNtUnmapVMMDevMemory(pDevExt); rc = STATUS_UNSUCCESSFUL; } } else rc = STATUS_UNSUCCESSFUL; } return rc; } /** * Unmaps the VMMDev I/O range from kernel space. * * @param pDevExt The device extension. */ void vbgdNtUnmapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt) { LogFlowFunc(("pVMMDevMemory = 0x%x\n", pDevExt->Core.pVMMDevMemory)); if (pDevExt->Core.pVMMDevMemory) { MmUnmapIoSpace((void*)pDevExt->Core.pVMMDevMemory, pDevExt->vmmDevPhysMemoryLength); pDevExt->Core.pVMMDevMemory = NULL; } pDevExt->vmmDevPhysMemoryAddress.QuadPart = 0; pDevExt->vmmDevPhysMemoryLength = 0; } VBOXOSTYPE vbgdNtVersionToOSType(VBGDNTVER enmNtVer) { VBOXOSTYPE enmOsType; switch (enmNtVer) { case VBGDNTVER_WINNT4: enmOsType = VBOXOSTYPE_WinNT4; break; case VBGDNTVER_WIN2K: enmOsType = VBOXOSTYPE_Win2k; break; case VBGDNTVER_WINXP: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_WinXP_x64; #else enmOsType = VBOXOSTYPE_WinXP; #endif break; case VBGDNTVER_WIN2K3: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win2k3_x64; #else enmOsType = VBOXOSTYPE_Win2k3; #endif break; case VBGDNTVER_WINVISTA: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_WinVista_x64; #else enmOsType = VBOXOSTYPE_WinVista; #endif break; case VBGDNTVER_WIN7: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win7_x64; #else enmOsType = VBOXOSTYPE_Win7; #endif break; case VBGDNTVER_WIN8: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win8_x64; #else enmOsType = VBOXOSTYPE_Win8; #endif break; case VBGDNTVER_WIN81: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win81_x64; #else enmOsType = VBOXOSTYPE_Win81; #endif break; case VBGDNTVER_WIN10: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win10_x64; #else enmOsType = VBOXOSTYPE_Win10; #endif break; default: /* We don't know, therefore NT family. */ enmOsType = VBOXOSTYPE_WinNT; break; } return enmOsType; } #ifdef DEBUG /** * A quick implementation of AtomicTestAndClear for uint32_t and multiple bits. */ static uint32_t vboxugestwinAtomicBitsTestAndClear(void *pu32Bits, uint32_t u32Mask) { AssertPtrReturn(pu32Bits, 0); LogFlowFunc(("*pu32Bits=0x%x, u32Mask=0x%x\n", *(uint32_t *)pu32Bits, u32Mask)); uint32_t u32Result = 0; uint32_t u32WorkingMask = u32Mask; int iBitOffset = ASMBitFirstSetU32 (u32WorkingMask); while (iBitOffset > 0) { bool fSet = ASMAtomicBitTestAndClear(pu32Bits, iBitOffset - 1); if (fSet) u32Result |= 1 << (iBitOffset - 1); u32WorkingMask &= ~(1 << (iBitOffset - 1)); iBitOffset = ASMBitFirstSetU32 (u32WorkingMask); } LogFlowFunc(("Returning 0x%x\n", u32Result)); return u32Result; } static void vbgdNtTestAtomicTestAndClearBitsU32(uint32_t u32Mask, uint32_t u32Bits, uint32_t u32Exp) { ULONG u32Bits2 = u32Bits; uint32_t u32Result = vboxugestwinAtomicBitsTestAndClear(&u32Bits2, u32Mask); if ( u32Result != u32Exp || (u32Bits2 & u32Mask) || (u32Bits2 & u32Result) || ((u32Bits2 | u32Result) != u32Bits) ) AssertLogRelMsgFailed(("%s: TEST FAILED: u32Mask=0x%x, u32Bits (before)=0x%x, u32Bits (after)=0x%x, u32Result=0x%x, u32Exp=ox%x\n", __PRETTY_FUNCTION__, u32Mask, u32Bits, u32Bits2, u32Result)); } static void vbgdNtDoTests(void) { vbgdNtTestAtomicTestAndClearBitsU32(0x00, 0x23, 0); vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0, 0); vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0x22, 0); vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0x23, 0x1); vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0x32, 0x10); vbgdNtTestAtomicTestAndClearBitsU32(0x22, 0x23, 0x22); } #endif /* DEBUG */ #ifdef VBOX_WITH_DPC_LATENCY_CHECKER /* * DPC latency checker. */ /** * One DPC latency sample. */ typedef struct DPCSAMPLE { LARGE_INTEGER PerfDelta; LARGE_INTEGER PerfCounter; LARGE_INTEGER PerfFrequency; uint64_t u64TSC; } DPCSAMPLE; AssertCompileSize(DPCSAMPLE, 4*8); /** * The DPC latency measurement workset. */ typedef struct DPCDATA { KDPC Dpc; KTIMER Timer; KSPIN_LOCK SpinLock; ULONG ulTimerRes; bool volatile fFinished; /** The timer interval (relative). */ LARGE_INTEGER DueTime; LARGE_INTEGER PerfCounterPrev; /** Align the sample array on a 64 byte boundrary just for the off chance * that we'll get cache line aligned memory backing this structure. */ uint32_t auPadding[ARCH_BITS == 32 ? 5 : 7]; int cSamples; DPCSAMPLE aSamples[8192]; } DPCDATA; AssertCompileMemberAlignment(DPCDATA, aSamples, 64); # define VBOXGUEST_DPC_TAG 'DPCS' /** * DPC callback routine for the DPC latency measurement code. * * @param pDpc The DPC, not used. * @param pvDeferredContext Pointer to the DPCDATA. * @param SystemArgument1 System use, ignored. * @param SystemArgument2 System use, ignored. */ static VOID vbgdNtDpcLatencyCallback(PKDPC pDpc, PVOID pvDeferredContext, PVOID SystemArgument1, PVOID SystemArgument2) { DPCDATA *pData = (DPCDATA *)pvDeferredContext; KeAcquireSpinLockAtDpcLevel(&pData->SpinLock); if (pData->cSamples >= RT_ELEMENTS(pData->aSamples)) pData->fFinished = true; else { DPCSAMPLE *pSample = &pData->aSamples[pData->cSamples++]; pSample->u64TSC = ASMReadTSC(); pSample->PerfCounter = KeQueryPerformanceCounter(&pSample->PerfFrequency); pSample->PerfDelta.QuadPart = pSample->PerfCounter.QuadPart - pData->PerfCounterPrev.QuadPart; pData->PerfCounterPrev.QuadPart = pSample->PerfCounter.QuadPart; KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc); } KeReleaseSpinLockFromDpcLevel(&pData->SpinLock); } /** * Handles the DPC latency checker request. * * @returns VBox status code. */ int VbgdNtIOCtl_DpcLatencyChecker(void) { /* * Allocate a block of non paged memory for samples and related data. */ DPCDATA *pData = (DPCDATA *)ExAllocatePoolWithTag(NonPagedPool, sizeof(DPCDATA), VBOXGUEST_DPC_TAG); if (!pData) { RTLogBackdoorPrintf("VBoxGuest: DPC: DPCDATA allocation failed.\n"); return VERR_NO_MEMORY; } /* * Initialize the data. */ KeInitializeDpc(&pData->Dpc, vbgdNtDpcLatencyCallback, pData); KeInitializeTimer(&pData->Timer); KeInitializeSpinLock(&pData->SpinLock); pData->fFinished = false; pData->cSamples = 0; pData->PerfCounterPrev.QuadPart = 0; pData->ulTimerRes = ExSetTimerResolution(1000 * 10, 1); pData->DueTime.QuadPart = -(int64_t)pData->ulTimerRes / 10; /* * Start the DPC measurements and wait for a full set. */ KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc); while (!pData->fFinished) { LARGE_INTEGER Interval; Interval.QuadPart = -100 * 1000 * 10; KeDelayExecutionThread(KernelMode, TRUE, &Interval); } ExSetTimerResolution(0, 0); /* * Log everything to the host. */ RTLogBackdoorPrintf("DPC: ulTimerRes = %d\n", pData->ulTimerRes); for (int i = 0; i < pData->cSamples; i++) { DPCSAMPLE *pSample = &pData->aSamples[i]; RTLogBackdoorPrintf("[%d] pd %lld pc %lld pf %lld t %lld\n", i, pSample->PerfDelta.QuadPart, pSample->PerfCounter.QuadPart, pSample->PerfFrequency.QuadPart, pSample->u64TSC); } ExFreePoolWithTag(pData, VBOXGUEST_DPC_TAG); return VINF_SUCCESS; } #endif /* VBOX_WITH_DPC_LATENCY_CHECKER */
sobomax/virtualbox_64bit_edd
src/VBox/Additions/common/VBoxGuest/VBoxGuest-win.cpp
C++
gpl-2.0
52,418
#Credits for the Assets Used. Please give credit to the respected authors for any assets used or redistributed. If you see any incorrect Copyright information below please file an [issue report](https://github.com/tsteinholz/SpaceShooter/issues) and any problems will be resolved as quickly as possible. ##Fonts | Font | Author / Source | Copyright | | :--: | :-------------: | :-------: | | Gtek_Technology_free.ttf | http://www.fonts2u.com/gtek-technology.font | Gtek Technology © (By Carlos Matteoli a.k.a Qbotype). 2013. All Rights Reserved | ##Music / Sounds | Song | Author / Source | Copyright | |:----:|:---------------:|:---------:| | Dawn.ogg | Rehan Choudhery | Space Shooter | | Rain.ogg | Rehan Choudhery | Space Shooter | | Wanted.ogg | Rehan Choudhery | Space Shooter | | MenuSelectionClick.wav | NenadSimic | Creative Commons | ##Images | Image | Author / Source | Copyright | | :---: | :-------------: | :-------: | | background.png | Ben Miller | Public Domain Dedication | | logo.png | Ross Owens | Space Shooter | | off-switch.png | Ross Owens | Space Shooter | | on-switch.png | Ross Owens | Space Shooter | | slick_arrow-delta.png | qubodup | Public Domain Dedication | | transparent-button.png | Ross Owens | Space Shooter | | white-button.png | Ross Owens | Space Shooter | | badlogic.png | Bad Logic Games | Apache 2 License | | favicon-black.png | Ross Owens | Space Shooter | | favicon-blue.png | Ross Owens | Space Shooter | | favicon-white.png | Ross Owens | Space Shooter | | laststand.png | Ross Owens + Thomas Steinholz | Space Shooter |
tsteinholz/SpaceShooter
core/assets/README.md
Markdown
gpl-2.0
1,574
#ifndef DATTO_CLIENT_DEVICE_SYNCHRONIZER_DEVICE_SYNCHRONIZER_INTERFACE_H_ #define DATTO_CLIENT_DEVICE_SYNCHRONIZER_DEVICE_SYNCHRONIZER_INTERFACE_H_ #include <memory> #include "backup/backup_coordinator.h" #include "backup_status_tracker/sync_count_handler.h" #include "block_device/block_device.h" #include "block_device/mountable_block_device.h" #include "unsynced_sector_manager/unsynced_sector_manager.h" namespace datto_linux_client { // Existance of this class allows for easier mocking in unit tests // The real work is done in DeviceSynchronizer class DeviceSynchronizerInterface { public: // Precondition: source_device must be both traced and mounted virtual void DoSync(std::shared_ptr<BackupCoordinator> coordinator, std::shared_ptr<SyncCountHandler> count_handler) = 0; virtual std::shared_ptr<const MountableBlockDevice> source_device() const = 0; virtual std::shared_ptr<const UnsyncedSectorManager> sector_manager() const = 0; virtual std::shared_ptr<const BlockDevice> destination_device() const = 0; virtual ~DeviceSynchronizerInterface() {} DeviceSynchronizerInterface(const DeviceSynchronizerInterface &) = delete; DeviceSynchronizerInterface& operator=(const DeviceSynchronizerInterface &) = delete; protected: DeviceSynchronizerInterface() {} }; } #endif // DATTO_CLIENT_DEVICE_SYNCHRONIZER_DEVICE_SYNCHRONIZER_INTERFACE_H_
fuhry/linux-agent
device_synchronizer/device_synchronizer_interface.h
C
gpl-2.0
1,404
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions for the AF_INET socket handler. * * Version: @(#)sock.h 1.0.4 05/13/93 * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche <flla@stud.uni-sb.de> * * Fixes: * Alan Cox : Volatiles in skbuff pointers. See * skbuff comments. May be overdone, * better to prove they can be removed * than the reverse. * Alan Cox : Added a zapped field for tcp to note * a socket is reset and must stay shut up * Alan Cox : New fields for options * Pauline Middelink : identd support * Alan Cox : Eliminate low level recv/recvfrom * David S. Miller : New socket lookup architecture. * Steve Whitehouse: Default routines for sock_ops * Arnaldo C. Melo : removed net_pinfo, tp_pinfo and made * protinfo be just a void pointer, as the * protocol specific parts were moved to * respective headers and ipv4/v6, etc now * use private slabcaches for its socks * Pedro Hortas : New flags field for socket options * * * 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. */ #ifndef _SOCK_H #define _SOCK_H #include <linux/config.h> #include <linux/list.h> #include <linux/timer.h> #include <linux/cache.h> #include <linux/module.h> #include <linux/netdevice.h> #include <linux/skbuff.h> /* struct sk_buff */ #include <linux/security.h> #include <linux/filter.h> #include <asm/atomic.h> #include <net/dst.h> #include <net/checksum.h> /* * This structure really needs to be cleaned up. * Most of it is for TCP, and not used by any of * the other protocols. */ /* Define this to get the SOCK_DBG debugging facility. */ #define SOCK_DEBUGGING #ifdef SOCK_DEBUGGING #define SOCK_DEBUG(sk, msg...) do { if ((sk) && sock_flag((sk), SOCK_DBG)) \ printk(KERN_DEBUG msg); } while (0) #else #define SOCK_DEBUG(sk, msg...) do { } while (0) #endif /* This is the per-socket lock. The spinlock provides a synchronization * between user contexts and software interrupt processing, whereas the * mini-semaphore synchronizes multiple users amongst themselves. */ struct sock_iocb; typedef struct { spinlock_t slock; struct sock_iocb *owner; wait_queue_head_t wq; } socket_lock_t; #define sock_lock_init(__sk) \ do { spin_lock_init(&((__sk)->sk_lock.slock)); \ (__sk)->sk_lock.owner = NULL; \ init_waitqueue_head(&((__sk)->sk_lock.wq)); \ } while(0) struct sock; /** * struct sock_common - minimal network layer representation of sockets * @skc_family: network address family * @skc_state: Connection state * @skc_reuse: %SO_REUSEADDR setting * @skc_bound_dev_if: bound device index if != 0 * @skc_node: main hash linkage for various protocol lookup tables * @skc_bind_node: bind hash linkage for various protocol lookup tables * @skc_refcnt: reference count * * This is the minimal network layer representation of sockets, the header * for struct sock and struct tcp_tw_bucket. */ struct sock_common { unsigned short skc_family; volatile unsigned char skc_state; unsigned char skc_reuse; int skc_bound_dev_if; struct hlist_node skc_node; struct hlist_node skc_bind_node; atomic_t skc_refcnt; }; /** * struct sock - network layer representation of sockets * @__sk_common: shared layout with tcp_tw_bucket * @sk_shutdown: mask of %SEND_SHUTDOWN and/or %RCV_SHUTDOWN * @sk_userlocks: %SO_SNDBUF and %SO_RCVBUF settings * @sk_lock: synchronizer * @sk_rcvbuf: size of receive buffer in bytes * @sk_sleep: sock wait queue * @sk_dst_cache: destination cache * @sk_dst_lock: destination cache lock * @sk_policy: flow policy * @sk_rmem_alloc: receive queue bytes committed * @sk_receive_queue: incoming packets * @sk_wmem_alloc: transmit queue bytes committed * @sk_write_queue: Packet sending queue * @sk_omem_alloc: "o" is "option" or "other" * @sk_wmem_queued: persistent queue size * @sk_forward_alloc: space allocated forward * @sk_allocation: allocation mode * @sk_sndbuf: size of send buffer in bytes * @sk_flags: %SO_LINGER (l_onoff), %SO_BROADCAST, %SO_KEEPALIVE, %SO_OOBINLINE settings * @sk_no_check: %SO_NO_CHECK setting, wether or not checkup packets * @sk_route_caps: route capabilities (e.g. %NETIF_F_TSO) * @sk_lingertime: %SO_LINGER l_linger setting * @sk_hashent: hash entry in several tables (e.g. tcp_ehash) * @sk_backlog: always used with the per-socket spinlock held * @sk_callback_lock: used with the callbacks in the end of this struct * @sk_error_queue: rarely used * @sk_prot: protocol handlers inside a network family * @sk_prot_creator: sk_prot of original sock creator (see ipv6_setsockopt, IPV6_ADDRFORM for instance) * @sk_err: last error * @sk_err_soft: errors that don't cause failure but are the cause of a persistent failure not just 'timed out' * @sk_ack_backlog: current listen backlog * @sk_max_ack_backlog: listen backlog set in listen() * @sk_priority: %SO_PRIORITY setting * @sk_type: socket type (%SOCK_STREAM, etc) * @sk_protocol: which protocol this socket belongs in this network family * @sk_peercred: %SO_PEERCRED setting * @sk_rcvlowat: %SO_RCVLOWAT setting * @sk_rcvtimeo: %SO_RCVTIMEO setting * @sk_sndtimeo: %SO_SNDTIMEO setting * @sk_filter: socket filtering instructions * @sk_protinfo: private area, net family specific, when not using slab * @sk_timer: sock cleanup timer * @sk_stamp: time stamp of last packet received * @sk_socket: Identd and reporting IO signals * @sk_user_data: RPC layer private data * @sk_sndmsg_page: cached page for sendmsg * @sk_sndmsg_off: cached offset for sendmsg * @sk_send_head: front of stuff to transmit * @sk_security: used by security modules * @sk_write_pending: a write to stream socket waits to start * @sk_state_change: callback to indicate change in the state of the sock * @sk_data_ready: callback to indicate there is data to be processed * @sk_write_space: callback to indicate there is bf sending space available * @sk_error_report: callback to indicate errors (e.g. %MSG_ERRQUEUE) * @sk_backlog_rcv: callback to process the backlog * @sk_destruct: called at sock freeing time, i.e. when all refcnt == 0 */ struct sock { /* * Now struct tcp_tw_bucket also uses sock_common, so please just * don't add nothing before this first member (__sk_common) --acme */ struct sock_common __sk_common; #define sk_family __sk_common.skc_family #define sk_state __sk_common.skc_state #define sk_reuse __sk_common.skc_reuse #define sk_bound_dev_if __sk_common.skc_bound_dev_if #define sk_node __sk_common.skc_node #define sk_bind_node __sk_common.skc_bind_node #define sk_refcnt __sk_common.skc_refcnt unsigned char sk_shutdown : 2, sk_no_check : 2, sk_userlocks : 4; unsigned char sk_protocol; unsigned short sk_type; int sk_rcvbuf; socket_lock_t sk_lock; wait_queue_head_t *sk_sleep; struct dst_entry *sk_dst_cache; struct xfrm_policy *sk_policy[2]; rwlock_t sk_dst_lock; atomic_t sk_rmem_alloc; atomic_t sk_wmem_alloc; atomic_t sk_omem_alloc; struct sk_buff_head sk_receive_queue; struct sk_buff_head sk_write_queue; int sk_wmem_queued; int sk_forward_alloc; unsigned int sk_allocation; int sk_sndbuf; int sk_route_caps; int sk_hashent; unsigned long sk_flags; unsigned long sk_lingertime; /* * The backlog queue is special, it is always used with * the per-socket spinlock held and requires low latency * access. Therefore we special case it's implementation. */ struct { struct sk_buff *head; struct sk_buff *tail; } sk_backlog; struct sk_buff_head sk_error_queue; struct proto *sk_prot; struct proto *sk_prot_creator; rwlock_t sk_callback_lock; int sk_err, sk_err_soft; unsigned short sk_ack_backlog; unsigned short sk_max_ack_backlog; __u32 sk_priority; struct ucred sk_peercred; int sk_rcvlowat; long sk_rcvtimeo; long sk_sndtimeo; struct sk_filter *sk_filter; void *sk_protinfo; struct timer_list sk_timer; struct timeval sk_stamp; struct socket *sk_socket; void *sk_user_data; struct page *sk_sndmsg_page; struct sk_buff *sk_send_head; __u32 sk_sndmsg_off; int sk_write_pending; void *sk_security; void (*sk_state_change)(struct sock *sk); void (*sk_data_ready)(struct sock *sk, int bytes); void (*sk_write_space)(struct sock *sk); void (*sk_error_report)(struct sock *sk); int (*sk_backlog_rcv)(struct sock *sk, struct sk_buff *skb); void (*sk_destruct)(struct sock *sk); }; /* * Hashed lists helper routines */ static inline struct sock *__sk_head(struct hlist_head *head) { return hlist_entry(head->first, struct sock, sk_node); } static inline struct sock *sk_head(struct hlist_head *head) { return hlist_empty(head) ? NULL : __sk_head(head); } static inline struct sock *sk_next(struct sock *sk) { return sk->sk_node.next ? hlist_entry(sk->sk_node.next, struct sock, sk_node) : NULL; } static inline int sk_unhashed(struct sock *sk) { return hlist_unhashed(&sk->sk_node); } static inline int sk_hashed(struct sock *sk) { return sk->sk_node.pprev != NULL; } static __inline__ void sk_node_init(struct hlist_node *node) { node->pprev = NULL; } static __inline__ void __sk_del_node(struct sock *sk) { __hlist_del(&sk->sk_node); } static __inline__ int __sk_del_node_init(struct sock *sk) { if (sk_hashed(sk)) { __sk_del_node(sk); sk_node_init(&sk->sk_node); return 1; } return 0; } /* Grab socket reference count. This operation is valid only when sk is ALREADY grabbed f.e. it is found in hash table or a list and the lookup is made under lock preventing hash table modifications. */ static inline void sock_hold(struct sock *sk) { atomic_inc(&sk->sk_refcnt); } /* Ungrab socket in the context, which assumes that socket refcnt cannot hit zero, f.e. it is true in context of any socketcall. */ static inline void __sock_put(struct sock *sk) { atomic_dec(&sk->sk_refcnt); } static __inline__ int sk_del_node_init(struct sock *sk) { int rc = __sk_del_node_init(sk); if (rc) { /* paranoid for a while -acme */ WARN_ON(atomic_read(&sk->sk_refcnt) == 1); __sock_put(sk); } return rc; } static __inline__ void __sk_add_node(struct sock *sk, struct hlist_head *list) { hlist_add_head(&sk->sk_node, list); } static __inline__ void sk_add_node(struct sock *sk, struct hlist_head *list) { sock_hold(sk); __sk_add_node(sk, list); } static __inline__ void __sk_del_bind_node(struct sock *sk) { __hlist_del(&sk->sk_bind_node); } static __inline__ void sk_add_bind_node(struct sock *sk, struct hlist_head *list) { hlist_add_head(&sk->sk_bind_node, list); } #define sk_for_each(__sk, node, list) \ hlist_for_each_entry(__sk, node, list, sk_node) #define sk_for_each_from(__sk, node) \ if (__sk && ({ node = &(__sk)->sk_node; 1; })) \ hlist_for_each_entry_from(__sk, node, sk_node) #define sk_for_each_continue(__sk, node) \ if (__sk && ({ node = &(__sk)->sk_node; 1; })) \ hlist_for_each_entry_continue(__sk, node, sk_node) #define sk_for_each_safe(__sk, node, tmp, list) \ hlist_for_each_entry_safe(__sk, node, tmp, list, sk_node) #define sk_for_each_bound(__sk, node, list) \ hlist_for_each_entry(__sk, node, list, sk_bind_node) /* Sock flags */ enum sock_flags { SOCK_DEAD, SOCK_DONE, SOCK_URGINLINE, SOCK_KEEPOPEN, SOCK_LINGER, SOCK_DESTROY, SOCK_BROADCAST, SOCK_TIMESTAMP, SOCK_ZAPPED, SOCK_USE_WRITE_QUEUE, /* whether to call sk->sk_write_space in sock_wfree */ SOCK_DBG, /* %SO_DEBUG setting */ SOCK_RCVTSTAMP, /* %SO_TIMESTAMP setting */ SOCK_NO_LARGESEND, /* whether to sent large segments or not */ SOCK_LOCALROUTE, /* route locally only, %SO_DONTROUTE setting */ SOCK_QUEUE_SHRUNK, /* write queue has been shrunk recently */ }; static inline void sock_copy_flags(struct sock *nsk, struct sock *osk) { nsk->sk_flags = osk->sk_flags; } static inline void sock_set_flag(struct sock *sk, enum sock_flags flag) { __set_bit(flag, &sk->sk_flags); } static inline void sock_reset_flag(struct sock *sk, enum sock_flags flag) { __clear_bit(flag, &sk->sk_flags); } static inline int sock_flag(struct sock *sk, enum sock_flags flag) { return test_bit(flag, &sk->sk_flags); } static inline void sk_acceptq_removed(struct sock *sk) { sk->sk_ack_backlog--; } static inline void sk_acceptq_added(struct sock *sk) { sk->sk_ack_backlog++; } static inline int sk_acceptq_is_full(struct sock *sk) { return sk->sk_ack_backlog > sk->sk_max_ack_backlog; } /* * Compute minimal free write space needed to queue new packets. */ static inline int sk_stream_min_wspace(struct sock *sk) { return sk->sk_wmem_queued / 2; } static inline int sk_stream_wspace(struct sock *sk) { return sk->sk_sndbuf - sk->sk_wmem_queued; } extern void sk_stream_write_space(struct sock *sk); static inline int sk_stream_memory_free(struct sock *sk) { return sk->sk_wmem_queued < sk->sk_sndbuf; } extern void sk_stream_rfree(struct sk_buff *skb); static inline void sk_stream_set_owner_r(struct sk_buff *skb, struct sock *sk) { skb->sk = sk; skb->destructor = sk_stream_rfree; atomic_add(skb->truesize, &sk->sk_rmem_alloc); sk->sk_forward_alloc -= skb->truesize; } static inline void sk_stream_free_skb(struct sock *sk, struct sk_buff *skb) { sock_set_flag(sk, SOCK_QUEUE_SHRUNK); sk->sk_wmem_queued -= skb->truesize; sk->sk_forward_alloc += skb->truesize; __kfree_skb(skb); } /* The per-socket spinlock must be held here. */ #define sk_add_backlog(__sk, __skb) \ do { if (!(__sk)->sk_backlog.tail) { \ (__sk)->sk_backlog.head = \ (__sk)->sk_backlog.tail = (__skb); \ } else { \ ((__sk)->sk_backlog.tail)->next = (__skb); \ (__sk)->sk_backlog.tail = (__skb); \ } \ (__skb)->next = NULL; \ } while(0) #define sk_wait_event(__sk, __timeo, __condition) \ ({ int rc; \ release_sock(__sk); \ rc = __condition; \ if (!rc) { \ *(__timeo) = schedule_timeout(*(__timeo)); \ rc = __condition; \ } \ lock_sock(__sk); \ rc; \ }) extern int sk_stream_wait_connect(struct sock *sk, long *timeo_p); extern int sk_stream_wait_memory(struct sock *sk, long *timeo_p); extern void sk_stream_wait_close(struct sock *sk, long timeo_p); extern int sk_stream_error(struct sock *sk, int flags, int err); extern void sk_stream_kill_queues(struct sock *sk); extern int sk_wait_data(struct sock *sk, long *timeo); struct request_sock_ops; /* Networking protocol blocks we attach to sockets. * socket layer -> transport layer interface * transport -> network interface is defined by struct inet_proto */ struct proto { void (*close)(struct sock *sk, long timeout); int (*connect)(struct sock *sk, struct sockaddr *uaddr, int addr_len); int (*disconnect)(struct sock *sk, int flags); struct sock * (*accept) (struct sock *sk, int flags, int *err); int (*ioctl)(struct sock *sk, int cmd, unsigned long arg); int (*init)(struct sock *sk); int (*destroy)(struct sock *sk); void (*shutdown)(struct sock *sk, int how); int (*setsockopt)(struct sock *sk, int level, int optname, char __user *optval, int optlen); int (*getsockopt)(struct sock *sk, int level, int optname, char __user *optval, int __user *option); int (*sendmsg)(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len); int (*recvmsg)(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len); int (*sendpage)(struct sock *sk, struct page *page, int offset, size_t size, int flags); int (*bind)(struct sock *sk, struct sockaddr *uaddr, int addr_len); int (*backlog_rcv) (struct sock *sk, struct sk_buff *skb); /* Keeping track of sk's, looking them up, and port selection methods. */ void (*hash)(struct sock *sk); void (*unhash)(struct sock *sk); int (*get_port)(struct sock *sk, unsigned short snum); /* Memory pressure */ void (*enter_memory_pressure)(void); atomic_t *memory_allocated; /* Current allocated memory. */ atomic_t *sockets_allocated; /* Current number of sockets. */ /* * Pressure flag: try to collapse. * Technical note: it is used by multiple contexts non atomically. * All the sk_stream_mem_schedule() is of this nature: accounting * is strict, actions are advisory and have some latency. */ int *memory_pressure; int *sysctl_mem; int *sysctl_wmem; int *sysctl_rmem; int max_header; kmem_cache_t *slab; unsigned int obj_size; struct request_sock_ops *rsk_prot; struct module *owner; char name[32]; struct list_head node; struct { int inuse; u8 __pad[SMP_CACHE_BYTES - sizeof(int)]; } stats[NR_CPUS]; }; extern int proto_register(struct proto *prot, int alloc_slab); extern void proto_unregister(struct proto *prot); /* Called with local bh disabled */ static __inline__ void sock_prot_inc_use(struct proto *prot) { prot->stats[smp_processor_id()].inuse++; } static __inline__ void sock_prot_dec_use(struct proto *prot) { prot->stats[smp_processor_id()].inuse--; } /* About 10 seconds */ #define SOCK_DESTROY_TIME (10*HZ) /* Sockets 0-1023 can't be bound to unless you are superuser */ #define PROT_SOCK 1024 #define SHUTDOWN_MASK 3 #define RCV_SHUTDOWN 1 #define SEND_SHUTDOWN 2 #define SOCK_SNDBUF_LOCK 1 #define SOCK_RCVBUF_LOCK 2 #define SOCK_BINDADDR_LOCK 4 #define SOCK_BINDPORT_LOCK 8 /* sock_iocb: used to kick off async processing of socket ios */ struct sock_iocb { struct list_head list; int flags; int size; struct socket *sock; struct sock *sk; struct scm_cookie *scm; struct msghdr *msg, async_msg; struct iovec async_iov; struct kiocb *kiocb; }; static inline struct sock_iocb *kiocb_to_siocb(struct kiocb *iocb) { return (struct sock_iocb *)iocb->private; } static inline struct kiocb *siocb_to_kiocb(struct sock_iocb *si) { return si->kiocb; } struct socket_alloc { struct socket socket; struct inode vfs_inode; }; static inline struct socket *SOCKET_I(struct inode *inode) { return &container_of(inode, struct socket_alloc, vfs_inode)->socket; } static inline struct inode *SOCK_INODE(struct socket *socket) { return &container_of(socket, struct socket_alloc, socket)->vfs_inode; } extern void __sk_stream_mem_reclaim(struct sock *sk); extern int sk_stream_mem_schedule(struct sock *sk, int size, int kind); #define SK_STREAM_MEM_QUANTUM ((int)PAGE_SIZE) static inline int sk_stream_pages(int amt) { return (amt + SK_STREAM_MEM_QUANTUM - 1) / SK_STREAM_MEM_QUANTUM; } static inline void sk_stream_mem_reclaim(struct sock *sk) { if (sk->sk_forward_alloc >= SK_STREAM_MEM_QUANTUM) __sk_stream_mem_reclaim(sk); } static inline void sk_stream_writequeue_purge(struct sock *sk) { struct sk_buff *skb; while ((skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) sk_stream_free_skb(sk, skb); sk_stream_mem_reclaim(sk); } static inline int sk_stream_rmem_schedule(struct sock *sk, struct sk_buff *skb) { return (int)skb->truesize <= sk->sk_forward_alloc || sk_stream_mem_schedule(sk, skb->truesize, 1); } /* Used by processes to "lock" a socket state, so that * interrupts and bottom half handlers won't change it * from under us. It essentially blocks any incoming * packets, so that we won't get any new data or any * packets that change the state of the socket. * * While locked, BH processing will add new packets to * the backlog queue. This queue is processed by the * owner of the socket lock right before it is released. * * Since ~2.3.5 it is also exclusive sleep lock serializing * accesses from user process context. */ #define sock_owned_by_user(sk) ((sk)->sk_lock.owner) extern void FASTCALL(lock_sock(struct sock *sk)); extern void FASTCALL(release_sock(struct sock *sk)); /* BH context may only use the following locking interface. */ #define bh_lock_sock(__sk) spin_lock(&((__sk)->sk_lock.slock)) #define bh_unlock_sock(__sk) spin_unlock(&((__sk)->sk_lock.slock)) extern struct sock *sk_alloc(int family, unsigned int __nocast priority, struct proto *prot, int zero_it); extern void sk_free(struct sock *sk); extern struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, unsigned int __nocast priority); extern struct sk_buff *sock_rmalloc(struct sock *sk, unsigned long size, int force, unsigned int __nocast priority); extern void sock_wfree(struct sk_buff *skb); extern void sock_rfree(struct sk_buff *skb); extern int sock_setsockopt(struct socket *sock, int level, int op, char __user *optval, int optlen); extern int sock_getsockopt(struct socket *sock, int level, int op, char __user *optval, int __user *optlen); extern struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size, int noblock, int *errcode); extern void *sock_kmalloc(struct sock *sk, int size, unsigned int __nocast priority); extern void sock_kfree_s(struct sock *sk, void *mem, int size); extern void sk_send_sigurg(struct sock *sk); /* * Functions to fill in entries in struct proto_ops when a protocol * does not implement a particular function. */ extern int sock_no_bind(struct socket *, struct sockaddr *, int); extern int sock_no_connect(struct socket *, struct sockaddr *, int, int); extern int sock_no_socketpair(struct socket *, struct socket *); extern int sock_no_accept(struct socket *, struct socket *, int); extern int sock_no_getname(struct socket *, struct sockaddr *, int *, int); extern unsigned int sock_no_poll(struct file *, struct socket *, struct poll_table_struct *); extern int sock_no_ioctl(struct socket *, unsigned int, unsigned long); extern int sock_no_listen(struct socket *, int); extern int sock_no_shutdown(struct socket *, int); extern int sock_no_getsockopt(struct socket *, int , int, char __user *, int __user *); extern int sock_no_setsockopt(struct socket *, int, int, char __user *, int); extern int sock_no_sendmsg(struct kiocb *, struct socket *, struct msghdr *, size_t); extern int sock_no_recvmsg(struct kiocb *, struct socket *, struct msghdr *, size_t, int); extern int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma); extern ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags); /* * Functions to fill in entries in struct proto_ops when a protocol * uses the inet style. */ extern int sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen); extern int sock_common_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags); extern int sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, int optlen); extern void sk_common_release(struct sock *sk); /* * Default socket callbacks and setup code */ /* Initialise core socket variables */ extern void sock_init_data(struct socket *sock, struct sock *sk); /** * sk_filter - run a packet through a socket filter * @sk: sock associated with &sk_buff * @skb: buffer to filter * @needlock: set to 1 if the sock is not locked by caller. * * Run the filter code and then cut skb->data to correct size returned by * sk_run_filter. If pkt_len is 0 we toss packet. If skb->len is smaller * than pkt_len we keep whole skb->data. This is the socket level * wrapper to sk_run_filter. It returns 0 if the packet should * be accepted or -EPERM if the packet should be tossed. * */ static inline int sk_filter(struct sock *sk, struct sk_buff *skb, int needlock) { int err; err = security_sock_rcv_skb(sk, skb); if (err) return err; if (sk->sk_filter) { struct sk_filter *filter; if (needlock) bh_lock_sock(sk); filter = sk->sk_filter; if (filter) { int pkt_len = sk_run_filter(skb, filter->insns, filter->len); if (!pkt_len) err = -EPERM; else skb_trim(skb, pkt_len); } if (needlock) bh_unlock_sock(sk); } return err; } /** * sk_filter_release: Release a socket filter * @sk: socket * @fp: filter to remove * * Remove a filter from a socket and release its resources. */ static inline void sk_filter_release(struct sock *sk, struct sk_filter *fp) { unsigned int size = sk_filter_len(fp); atomic_sub(size, &sk->sk_omem_alloc); if (atomic_dec_and_test(&fp->refcnt)) kfree(fp); } static inline void sk_filter_charge(struct sock *sk, struct sk_filter *fp) { atomic_inc(&fp->refcnt); atomic_add(sk_filter_len(fp), &sk->sk_omem_alloc); } /* * Socket reference counting postulates. * * * Each user of socket SHOULD hold a reference count. * * Each access point to socket (an hash table bucket, reference from a list, * running timer, skb in flight MUST hold a reference count. * * When reference count hits 0, it means it will never increase back. * * When reference count hits 0, it means that no references from * outside exist to this socket and current process on current CPU * is last user and may/should destroy this socket. * * sk_free is called from any context: process, BH, IRQ. When * it is called, socket has no references from outside -> sk_free * may release descendant resources allocated by the socket, but * to the time when it is called, socket is NOT referenced by any * hash tables, lists etc. * * Packets, delivered from outside (from network or from another process) * and enqueued on receive/error queues SHOULD NOT grab reference count, * when they sit in queue. Otherwise, packets will leak to hole, when * socket is looked up by one cpu and unhasing is made by another CPU. * It is true for udp/raw, netlink (leak to receive and error queues), tcp * (leak to backlog). Packet socket does all the processing inside * BR_NETPROTO_LOCK, so that it has not this race condition. UNIX sockets * use separate SMP lock, so that they are prone too. */ /* Ungrab socket and destroy it, if it was the last reference. */ static inline void sock_put(struct sock *sk) { if (atomic_dec_and_test(&sk->sk_refcnt)) sk_free(sk); } /* Detach socket from process context. * Announce socket dead, detach it from wait queue and inode. * Note that parent inode held reference count on this struct sock, * we do not release it in this function, because protocol * probably wants some additional cleanups or even continuing * to work with this socket (TCP). */ static inline void sock_orphan(struct sock *sk) { write_lock_bh(&sk->sk_callback_lock); sock_set_flag(sk, SOCK_DEAD); sk->sk_socket = NULL; sk->sk_sleep = NULL; write_unlock_bh(&sk->sk_callback_lock); } static inline void sock_graft(struct sock *sk, struct socket *parent) { write_lock_bh(&sk->sk_callback_lock); sk->sk_sleep = &parent->wait; parent->sk = sk; sk->sk_socket = parent; write_unlock_bh(&sk->sk_callback_lock); } extern int sock_i_uid(struct sock *sk); extern unsigned long sock_i_ino(struct sock *sk); static inline struct dst_entry * __sk_dst_get(struct sock *sk) { return sk->sk_dst_cache; } static inline struct dst_entry * sk_dst_get(struct sock *sk) { struct dst_entry *dst; read_lock(&sk->sk_dst_lock); dst = sk->sk_dst_cache; if (dst) dst_hold(dst); read_unlock(&sk->sk_dst_lock); return dst; } static inline void __sk_dst_set(struct sock *sk, struct dst_entry *dst) { struct dst_entry *old_dst; old_dst = sk->sk_dst_cache; sk->sk_dst_cache = dst; dst_release(old_dst); } static inline void sk_dst_set(struct sock *sk, struct dst_entry *dst) { write_lock(&sk->sk_dst_lock); __sk_dst_set(sk, dst); write_unlock(&sk->sk_dst_lock); } static inline void __sk_dst_reset(struct sock *sk) { struct dst_entry *old_dst; old_dst = sk->sk_dst_cache; sk->sk_dst_cache = NULL; dst_release(old_dst); } static inline void sk_dst_reset(struct sock *sk) { write_lock(&sk->sk_dst_lock); __sk_dst_reset(sk); write_unlock(&sk->sk_dst_lock); } static inline struct dst_entry * __sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk->sk_dst_cache; if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk->sk_dst_cache = NULL; dst_release(dst); return NULL; } return dst; } static inline struct dst_entry * sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_dst_reset(sk); dst_release(dst); return NULL; } return dst; } static inline void sk_charge_skb(struct sock *sk, struct sk_buff *skb) { sk->sk_wmem_queued += skb->truesize; sk->sk_forward_alloc -= skb->truesize; } static inline int skb_copy_to_page(struct sock *sk, char __user *from, struct sk_buff *skb, struct page *page, int off, int copy) { if (skb->ip_summed == CHECKSUM_NONE) { int err = 0; unsigned int csum = csum_and_copy_from_user(from, page_address(page) + off, copy, 0, &err); if (err) return err; skb->csum = csum_block_add(skb->csum, csum, skb->len); } else if (copy_from_user(page_address(page) + off, from, copy)) return -EFAULT; skb->len += copy; skb->data_len += copy; skb->truesize += copy; sk->sk_wmem_queued += copy; sk->sk_forward_alloc -= copy; return 0; } /* * Queue a received datagram if it will fit. Stream and sequenced * protocols can't normally use this as they need to fit buffers in * and play with them. * * Inlined as it's very short and called for pretty much every * packet ever received. */ static inline void skb_set_owner_w(struct sk_buff *skb, struct sock *sk) { sock_hold(sk); skb->sk = sk; skb->destructor = sock_wfree; atomic_add(skb->truesize, &sk->sk_wmem_alloc); } static inline void skb_set_owner_r(struct sk_buff *skb, struct sock *sk) { skb->sk = sk; skb->destructor = sock_rfree; atomic_add(skb->truesize, &sk->sk_rmem_alloc); } extern void sk_reset_timer(struct sock *sk, struct timer_list* timer, unsigned long expires); extern void sk_stop_timer(struct sock *sk, struct timer_list* timer); static inline int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err = 0; int skb_len; /* Cast skb->rcvbuf to unsigned... It's pointless, but reduces number of warnings when compiling with -W --ANK */ if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned)sk->sk_rcvbuf) { err = -ENOMEM; goto out; } /* It would be deadlock, if sock_queue_rcv_skb is used with socket lock! We assume that users of this function are lock free. */ err = sk_filter(sk, skb, 1); if (err) goto out; skb->dev = NULL; skb_set_owner_r(skb, sk); /* Cache the SKB length before we tack it onto the receive * queue. Once it is added it no longer belongs to us and * may be freed by other threads of control pulling packets * from the queue. */ skb_len = skb->len; skb_queue_tail(&sk->sk_receive_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb_len); out: return err; } static inline int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb) { /* Cast skb->rcvbuf to unsigned... It's pointless, but reduces number of warnings when compiling with -W --ANK */ if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned)sk->sk_rcvbuf) return -ENOMEM; skb_set_owner_r(skb, sk); skb_queue_tail(&sk->sk_error_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); return 0; } /* * Recover an error report and clear atomically */ static inline int sock_error(struct sock *sk) { int err = xchg(&sk->sk_err, 0); return -err; } static inline unsigned long sock_wspace(struct sock *sk) { int amt = 0; if (!(sk->sk_shutdown & SEND_SHUTDOWN)) { amt = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc); if (amt < 0) amt = 0; } return amt; } static inline void sk_wake_async(struct sock *sk, int how, int band) { if (sk->sk_socket && sk->sk_socket->fasync_list) sock_wake_async(sk->sk_socket, how, band); } #define SOCK_MIN_SNDBUF 2048 #define SOCK_MIN_RCVBUF 256 static inline void sk_stream_moderate_sndbuf(struct sock *sk) { if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK)) { sk->sk_sndbuf = min(sk->sk_sndbuf, sk->sk_wmem_queued / 2); sk->sk_sndbuf = max(sk->sk_sndbuf, SOCK_MIN_SNDBUF); } } static inline struct sk_buff *sk_stream_alloc_pskb(struct sock *sk, int size, int mem, unsigned int __nocast gfp) { struct sk_buff *skb; int hdr_len; hdr_len = SKB_DATA_ALIGN(sk->sk_prot->max_header); skb = alloc_skb(size + hdr_len, gfp); if (skb) { skb->truesize += mem; if (sk->sk_forward_alloc >= (int)skb->truesize || sk_stream_mem_schedule(sk, skb->truesize, 0)) { skb_reserve(skb, hdr_len); return skb; } __kfree_skb(skb); } else { sk->sk_prot->enter_memory_pressure(); sk_stream_moderate_sndbuf(sk); } return NULL; } static inline struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, unsigned int __nocast gfp) { return sk_stream_alloc_pskb(sk, size, 0, gfp); } static inline struct page *sk_stream_alloc_page(struct sock *sk) { struct page *page = NULL; if (sk->sk_forward_alloc >= (int)PAGE_SIZE || sk_stream_mem_schedule(sk, PAGE_SIZE, 0)) page = alloc_pages(sk->sk_allocation, 0); else { sk->sk_prot->enter_memory_pressure(); sk_stream_moderate_sndbuf(sk); } return page; } #define sk_stream_for_retrans_queue(skb, sk) \ for (skb = (sk)->sk_write_queue.next; \ (skb != (sk)->sk_send_head) && \ (skb != (struct sk_buff *)&(sk)->sk_write_queue); \ skb = skb->next) /* * Default write policy as shown to user space via poll/select/SIGIO */ static inline int sock_writeable(const struct sock *sk) { return atomic_read(&sk->sk_wmem_alloc) < (sk->sk_sndbuf / 2); } static inline unsigned int __nocast gfp_any(void) { return in_softirq() ? GFP_ATOMIC : GFP_KERNEL; } static inline long sock_rcvtimeo(const struct sock *sk, int noblock) { return noblock ? 0 : sk->sk_rcvtimeo; } static inline long sock_sndtimeo(const struct sock *sk, int noblock) { return noblock ? 0 : sk->sk_sndtimeo; } static inline int sock_rcvlowat(const struct sock *sk, int waitall, int len) { return (waitall ? len : min_t(int, sk->sk_rcvlowat, len)) ? : 1; } /* Alas, with timeout socket operations are not restartable. * Compare this to poll(). */ static inline int sock_intr_errno(long timeo) { return timeo == MAX_SCHEDULE_TIMEOUT ? -ERESTARTSYS : -EINTR; } static __inline__ void sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { struct timeval *stamp = &skb->stamp; if (sock_flag(sk, SOCK_RCVTSTAMP)) { /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (stamp->tv_sec == 0) do_gettimeofday(stamp); put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP, sizeof(struct timeval), stamp); } else sk->sk_stamp = *stamp; } /** * sk_eat_skb - Release a skb if it is no longer needed * @sk: socket to eat this skb from * @skb: socket buffer to eat * * This routine must be called with interrupts disabled or with the socket * locked so that the sk_buff queue operation is ok. */ static inline void sk_eat_skb(struct sock *sk, struct sk_buff *skb) { __skb_unlink(skb, &sk->sk_receive_queue); __kfree_skb(skb); } extern void sock_enable_timestamp(struct sock *sk); extern int sock_get_timestamp(struct sock *, struct timeval __user *); /* * Enable debug/info messages */ #if 0 #define NETDEBUG(x) do { } while (0) #define LIMIT_NETDEBUG(x) do {} while(0) #else #define NETDEBUG(x) do { x; } while (0) #define LIMIT_NETDEBUG(x) do { if (net_ratelimit()) { x; } } while(0) #endif /* * Macros for sleeping on a socket. Use them like this: * * SOCK_SLEEP_PRE(sk) * if (condition) * schedule(); * SOCK_SLEEP_POST(sk) * * N.B. These are now obsolete and were, afaik, only ever used in DECnet * and when the last use of them in DECnet has gone, I'm intending to * remove them. */ #define SOCK_SLEEP_PRE(sk) { struct task_struct *tsk = current; \ DECLARE_WAITQUEUE(wait, tsk); \ tsk->state = TASK_INTERRUPTIBLE; \ add_wait_queue((sk)->sk_sleep, &wait); \ release_sock(sk); #define SOCK_SLEEP_POST(sk) tsk->state = TASK_RUNNING; \ remove_wait_queue((sk)->sk_sleep, &wait); \ lock_sock(sk); \ } static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool) { if (valbool) sock_set_flag(sk, bit); else sock_reset_flag(sk, bit); } extern __u32 sysctl_wmem_max; extern __u32 sysctl_rmem_max; #ifdef CONFIG_NET int siocdevprivate_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg); #else static inline int siocdevprivate_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { return -ENODEV; } #endif #endif /* _SOCK_H */
waterice/Test-Git
include/net/sock.h
C
gpl-2.0
37,810
/*********************************************************************************** * Smooth Tasks * Copyright (C) 2009 Mathias Panzenböck <grosser.meister.morti@gmx.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***********************************************************************************/ #include "SmoothTasks/FixedItemCountTaskbarLayout.h" #include <QApplication> #include <cmath> namespace SmoothTasks { void FixedItemCountTaskbarLayout::setItemsPerRow(int itemsPerRow) { if (m_itemsPerRow != itemsPerRow) { m_itemsPerRow = itemsPerRow; invalidate(); } } int FixedItemCountTaskbarLayout::optimumCapacity() const { return m_itemsPerRow * maximumRows(); } void FixedItemCountTaskbarLayout::doLayout() { // I think this way the loops can be optimized by the compiler. // (lifting out the comparison and making two loops; TODO: find out whether this is true): const bool isVertical = orientation() == Qt::Vertical; const QList<TaskbarItem*>& items = this->items(); const int N = items.size(); // if there is nothing to layout fill in some dummy data and leave if (N == 0) { stopAnimation(); QRectF rect(geometry()); m_rows = 1; if (isVertical) { m_cellHeight = rect.width(); } else { m_cellHeight = rect.height(); } QSizeF newPreferredSize(qMin(10.0, rect.width()), qMin(10.0, rect.height())); if (newPreferredSize != m_preferredSize) { m_preferredSize = newPreferredSize; emit sizeHintChanged(Qt::PreferredSize); } return; } const QRectF effectiveRect(effectiveGeometry()); const qreal availableWidth = isVertical ? effectiveRect.height() : effectiveRect.width(); const qreal availableHeight = isVertical ? effectiveRect.width() : effectiveRect.height(); const qreal spacing = this->spacing(); #define CELL_HEIGHT(ROWS) (((availableHeight + spacing) / ((qreal) (ROWS))) - spacing) int itemsPerRow = m_itemsPerRow; int rows = maximumRows(); if (itemsPerRow * rows < N) { itemsPerRow = std::ceil(((qreal) N) / rows); } else { rows = std::ceil(((qreal) N) / itemsPerRow); } qreal cellHeight = CELL_HEIGHT(rows); qreal cellWidth = cellHeight * aspectRatio(); QList<RowInfo> rowInfos; qreal maxPreferredRowWidth = 0; buildRows(itemsPerRow, cellWidth, rowInfos, rows, maxPreferredRowWidth); cellHeight = CELL_HEIGHT(rows); updateLayout(rows, cellWidth, cellHeight, availableWidth, maxPreferredRowWidth, rowInfos, effectiveRect); #undef CELL_HEIGHT } } // namespace SmoothTasks
Nuk9/smooth-task-next
applet/SmoothTasks/FixedItemCountTaskbarLayout.cpp
C++
gpl-2.0
3,155
#ifndef _HEAD_HACK_CLIENT #define _HEAD_HACK_CLIENT #define SOCKET_SEND_MAXLEN 1024 int init_client_connect(); int handle_send(int sock_fd, const char *msg); #endif
rexrock/HackShell
include/hack_client.h
C
gpl-2.0
167
'use strict'; var env = process.env.NODE_ENV || 'development', config = require('./config'), B = require('bluebird'), _ = require('underscore'), L = require('./logger'), S = require('underscore.string'), nodemailer = require('nodemailer'), smtpTransport = require('nodemailer-smtp-pool'); var Mailer = function (options) { var opts = _.extend({}, config.mail, options); this.transporter = B.promisifyAll(nodemailer.createTransport(smtpTransport(opts))); }; Mailer.prototype.send = function (options) { var that = this; return that.transporter.sendMailAsync(options); }; module.exports = Mailer;
zamamohammed/health-check
mailer.js
JavaScript
gpl-2.0
643
/* Copyright (c) 2009-2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * */ #include <linux/kernel.h> #include <linux/irq.h> #include <linux/gpio.h> #include <linux/platform_device.h> #include <linux/delay.h> #include <linux/bootmem.h> #include <linux/io.h> #ifdef CONFIG_SPI_QSD #include <linux/spi/spi.h> #endif #include <linux/mfd/pmic8058.h> #include <linux/mfd/marimba.h> #include <linux/i2c.h> #include <linux/input.h> #ifdef CONFIG_SMSC911X #include <linux/smsc911x.h> #endif #include <linux/ofn_atlab.h> #include <linux/power_supply.h> #include <linux/input/pmic8058-keypad.h> #include <linux/i2c/isa1200.h> #include <linux/pwm.h> #include <linux/pmic8058-pwm.h> #include <linux/i2c/tsc2007.h> #include <linux/input/kp_flip_switch.h> #include <linux/leds-pmic8058.h> #include <linux/input/cy8c_ts.h> #include <linux/msm_adc.h> #include <linux/dma-mapping.h> #ifdef CONFIG_KEYBOARD_GPIO #include <linux/gpio_keys.h> // DIV2-SW2-BSP-FBx-BUTTONS #endif #ifdef CONFIG_PMIC8058_VIBRATOR #include <linux/pmic8058-vibrator.h> // DIV2-SW2-BSP-FBx-VIB #endif #include <linux/gps_fm_lna.h> /* AlbertYCFang, 2011.06.13, FM */ #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/setup.h> #include <mach/mpp.h> #include <mach/board.h> #include <mach/camera.h> #include <mach/memory.h> #include <mach/msm_iomap.h> #include <mach/msm_hsusb.h> #include <mach/rpc_hsusb.h> #include <mach/msm_spi.h> #include <mach/qdsp5v2/msm_lpa.h> #include <mach/dma.h> #include <linux/android_pmem.h> #include <linux/input/msm_ts.h> #include <mach/pmic.h> #include <mach/rpc_pmapp.h> #include <mach/qdsp5v2/aux_pcm.h> #include <mach/qdsp5v2/mi2s.h> #include <mach/qdsp5v2/audio_dev_ctl.h> #ifdef CONFIG_BATTERY_MSM #include <mach/msm_battery.h> #endif #include <mach/rpc_server_handset.h> #include <mach/msm_tsif.h> #include <mach/socinfo.h> #include <linux/cyttsp.h> #include <asm/mach/mmc.h> #include <asm/mach/flash.h> #include <mach/vreg.h> #include "devices.h" #include "timer.h" #ifdef CONFIG_USB_ANDROID #include <linux/usb/android_composite.h> #endif #include "pm.h" #include "spm.h" #include <linux/msm_kgsl.h> #include <mach/dal_axi.h> #include <mach/msm_serial_hs.h> #include <mach/msm_reqs.h> #include <mach/qdsp5v2/mi2s.h> #include <mach/qdsp5v2/audio_dev_ctl.h> #include <mach/sdio_al.h> #include "smd_private.h" #include <linux/fih_hw_info.h> //FIHTDC, Div2-SW2-BSP /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL #undef HDMI_RESET #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ #include <linux/bma150.h> #ifdef CONFIG_LEDS_FIH_FBX_PWM #include <mach/leds-fbx-pwm.h> // DIV2-SW2-BSP-FBx-LEDS #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 {+ #ifdef CONFIG_KEYBOARD_SF4H8 #include <mach/sf8_kybd.h> #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 -} #ifdef CONFIG_DS2482 #include <mach/ds2482.h> // DIV2-SW2-BSP-FBx-BATT #endif #ifdef CONFIG_BATTERY_FIH_DS2784 #include <mach/ds2784.h> // DIV2-SW2-BSP-FBx-BATT #endif #ifdef CONFIG_BATTERY_FIH_MSM #include <mach/fih_msm_battery.h> // DIV2-SW2-BSP-FBx-BATT #endif #ifdef CONFIG_BATTERY_BQ275X0 #include <mach/bq275x0_battery.h> // DIV2-SW2-BSP-FBx-BATT #endif /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ #include <linux/switch.h> /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ /* FIHTDC, Div2-SW2-BSP, Penho, USB_ACCESORIES { */ #ifdef CONFIG_USB_ANDROID_ACCESSORY #include <linux/usb/f_accessory.h> #endif // CONFIG_USB_ANDROID_ACCESSORY /* } FIHTDC, Div2-SW2-BSP, Penho, USB_ACCESORIES */ /* FIHTDC, Div2-SW2-BSP, Ming, PMEM { */ /* Enlarge PMEM_SF to 30 MB for WVGA */ #define MSM_PMEM_SF_SIZE 0x1E00000 //0x1700000 /* } FIHTDC, Div2-SW2-BSP, Ming, PMEM */ /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL #define MSM_FB_SIZE 0x500000 #else #define MSM_FB_SIZE 0xA00000 ///0x500000 #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ #define MSM_PMEM_ADSP_SIZE 0x2400000 //0x1800000 //SW4-L1-HL-Camera-FixCTS_2.3_R4_FailIssue-00* #define MSM_FLUID_PMEM_ADSP_SIZE 0x2800000 #define PMEM_KERNEL_EBI1_SIZE 0x600000 #define MSM_PMEM_AUDIO_SIZE 0x200000 #define PMIC_GPIO_INT 27 #define PMIC_VREG_WLAN_LEVEL 2900 #define PMIC_GPIO_SD_DET 36 #define PMIC_GPIO_SDC4_EN_N 17 /* PMIC GPIO Number 18 */ /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL #define PMIC_GPIO_HDMI_5V_EN_V3 32 /* PMIC GPIO for V3 H/W */ #define PMIC_GPIO_HDMI_5V_EN_V2 39 /* PMIC GPIO for V2 H/W */ #define ADV7520_I2C_ADDR 0x39 #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL #define PMIC_GPIO_HDMI_18V_EN 32 /* PMIC GPIO Number 33 */ #define GPIO_HDMI_5V_EN \ GPIO_CFG(34, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_4MA) #define HDMI_INT 180 static bool hdmi_init_done = false; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ /* FIHTDC, Div2-SW2-BSP, Ming, LCM { */ #define PMIC_GPIO_LCM_V1P8_EN 35 /* PMIC GPIO Number 36 */ /* } FIHTDC, Div2-SW2-BSP, Ming, LCM */ #define FPGA_SDCC_STATUS 0x8E0001A8 #define FPGA_OPTNAV_GPIO_ADDR 0x8E000026 #define OPTNAV_I2C_SLAVE_ADDR (0xB0 >> 1) #define OPTNAV_IRQ 20 #define OPTNAV_CHIP_SELECT 19 /* Macros assume PMIC GPIOs start at 0 */ #define PM8058_GPIO_PM_TO_SYS(pm_gpio) (pm_gpio + NR_GPIO_IRQS) #define PM8058_GPIO_SYS_TO_PM(sys_gpio) (sys_gpio - NR_GPIO_IRQS) #define PMIC_GPIO_FLASH_BOOST_ENABLE 15 /* PMIC GPIO Number 16 */ #define PMIC_GPIO_HAP_ENABLE 16 /* PMIC GPIO Number 17 */ #define PMIC_GPIO_WLAN_EXT_POR 22 /* PMIC GPIO NUMBER 23 */ #define BMA150_GPIO_INT 1 #define HAP_LVL_SHFT_MSM_GPIO 24 #define PMIC_GPIO_QUICKVX_CLK 37 /* PMIC GPIO 38 */ #define PM_FLIP_MPP 5 /* PMIC MPP 06 */ /* +++ AlbertYCFang, 2011.06.13,FM +++ */ //SQ01.FC-73: Change QTR8200 WCN clock source(32M) from PMIC-D0 to PMIC-A1 #if defined(CONFIG_FIH_PROJECT_SF4V5) || defined(CONFIG_FIH_PROJECT_SF4Y6) #define QTR8x00_WCN_CLK PMAPP_CLOCK_ID_DO #else #define QTR8x00_WCN_CLK PMAPP_CLOCK_ID_A1 #endif /* --- AlbertYCFang, 2011.06.13,FM --- */ // DIV2-SW2-BSP-FBx-BUTTONS+ #ifdef CONFIG_KEYBOARD_GPIO #define PM_GPIO_CAMF 1 #define PM_GPIO_CAMT 2 #define PM_GPIO_VOLUP 3 #define PM_GPIO_VOLDN 4 #define KEY_NUM 4 #define KEY_FOCUS KEY_F13 #define KEY_DEBOUNCE_INTERVAL 2 // ms static struct gpio_keys_button gpio_buttons[KEY_NUM] = { { .code = KEY_VOLUMEUP, .gpio = PM8058_GPIO_PM_TO_SYS(PM_GPIO_VOLUP), .active_low = 0, .desc = "Vol Up Key", .type = EV_KEY, .wakeup = 0, .debounce_interval = KEY_DEBOUNCE_INTERVAL }, { .code = KEY_VOLUMEDOWN, .gpio = PM8058_GPIO_PM_TO_SYS(PM_GPIO_VOLDN), .active_low = 0, .desc = "Vol Dn Key", .type = EV_KEY, .wakeup = 0, .debounce_interval = KEY_DEBOUNCE_INTERVAL }, { .code = KEY_FOCUS, .gpio = PM8058_GPIO_PM_TO_SYS(PM_GPIO_CAMF), .active_low = 0, .desc = "Focus Key", .type = EV_KEY, .wakeup = 0, .debounce_interval = KEY_DEBOUNCE_INTERVAL }, { .code = KEY_CAMERA, .gpio = PM8058_GPIO_PM_TO_SYS(PM_GPIO_CAMT), .active_low = 0, .desc = "Camera Key", .type = EV_KEY, .wakeup = 0, .debounce_interval = KEY_DEBOUNCE_INTERVAL }, }; static struct gpio_keys_platform_data gpio_buttons_pdata = { .buttons = gpio_buttons, .nbuttons = KEY_NUM - 2, .rep = 0 }; static struct platform_device gpio_buttons_device = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &gpio_buttons_pdata, }, }; #endif // DIV2-SW2-BSP-FBx-BUTTONS- /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ bool m_HsAmpOn=false; bool m_SpkAmpOn=false; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ int sd_detect_pin = 0; int sd_enable_pin = 0; static int pm8058_gpios_init(void) { int rc; /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL int pmic_gpio_hdmi_5v_en; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ /* remove redundant code*/ #if 0 #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION struct pm8058_gpio sdcc_det = { .direction = PM_GPIO_DIR_IN, .pull = PM_GPIO_PULL_UP_1P5, .vin_sel = 2, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, }; #endif #endif struct pm8058_gpio sdc4_en = { .direction = PM_GPIO_DIR_OUT, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_L5, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, .out_strength = PM_GPIO_STRENGTH_LOW, .output_value = 0, }; struct pm8058_gpio haptics_enable = { .direction = PM_GPIO_DIR_OUT, .pull = PM_GPIO_PULL_NO, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, .vin_sel = 2, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 0, }; /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL struct pm8058_gpio hdmi_5V_en = { .direction = PM_GPIO_DIR_OUT, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_VPH, .function = PM_GPIO_FUNC_NORMAL, .out_strength = PM_GPIO_STRENGTH_LOW, .output_value = 0, }; #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL struct pm8058_gpio hdmi_18V_en = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .pull = PM_GPIO_PULL_NO, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_NORMAL, }; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ /* FIHTDC, Div2-SW2-BSP, Ming, LCM { */ struct pm8058_gpio lcm_v1p8_en ={ .direction = PM_GPIO_DIR_OUT, //Let the pin be an output one. .output_buffer = PM_GPIO_OUT_BUF_CMOS, //HW suggestion .output_value = 1, //You also can set 0, but it seems useless. .out_strength = PM_GPIO_STRENGTH_HIGH, //There are three options for this, LOW, MED, and HIGH, but I don!|t know the actual effect. .function = PM_GPIO_FUNC_NORMAL, //Let the pin be a general GPIO. }; /* } FIHTDC, Div2-SW2-BSP, Ming, LCM */ struct pm8058_gpio flash_boost_enable = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 0, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S3, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_2, }; struct pm8058_gpio gpio23 = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 0, .pull = PM_GPIO_PULL_NO, .vin_sel = 2, .out_strength = PM_GPIO_STRENGTH_LOW, .function = PM_GPIO_FUNC_NORMAL, }; // DIV2-SW2-BSP-FBx-BUTTONS+ #ifdef CONFIG_KEYBOARD_GPIO struct pm8058_gpio button_configuration = { .direction = PM_GPIO_DIR_IN, .pull = PM_GPIO_PULL_DN, .vin_sel = 2, .out_strength = PM_GPIO_STRENGTH_NO, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, }; #endif // DIV2-SW2-BSP-FBx-BUTTONS- /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa() || machine_is_msm7x30_fluid()) pmic_gpio_hdmi_5v_en = PMIC_GPIO_HDMI_5V_EN_V2 ; else pmic_gpio_hdmi_5v_en = PMIC_GPIO_HDMI_5V_EN_V3 ; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ if (machine_is_msm7x30_fluid()) { rc = pm8058_gpio_config(PMIC_GPIO_HAP_ENABLE, &haptics_enable); if (rc) { pr_err("%s: PMIC GPIO %d write failed\n", __func__, (PMIC_GPIO_HAP_ENABLE + 1)); return rc; } rc = pm8058_gpio_config(PMIC_GPIO_FLASH_BOOST_ENABLE, &flash_boost_enable); if (rc) { pr_err("%s: PMIC GPIO %d write failed\n", __func__, (PMIC_GPIO_FLASH_BOOST_ENABLE + 1)); return rc; } } /*remove redundant code*/ #if 0 #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION if (machine_is_msm7x30_fluid()) sdcc_det.inv_int_pol = 1; rc = pm8058_gpio_config(PMIC_GPIO_SD_DET - 1, &sdcc_det); if (rc) { pr_err("%s PMIC_GPIO_SD_DET config failed\n", __func__); return rc; } #endif #endif /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL rc = pm8058_gpio_config(pmic_gpio_hdmi_5v_en, &hdmi_5V_en); if (rc) { pr_err("%s PMIC_GPIO_HDMI_5V_EN config failed\n", __func__); return rc; } #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL rc = pm8058_gpio_config(PMIC_GPIO_HDMI_18V_EN, &hdmi_18V_en); if (rc) { pr_err("%s PMIC_GPIO_HDMI_1.8V_EN config failed\n", __func__); return rc; } rc = gpio_request(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_HDMI_18V_EN), "hdmi_18V_en"); if (rc) { pr_err("%s PMIC_GPIO_HDMI_1.8V_EN gpio_request failed\n", __func__); return rc; } gpio_set_value_cansleep( PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_HDMI_18V_EN), 1); #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ /* Deassert GPIO#23 (source for Ext_POR on WLAN-Volans) */ rc = pm8058_gpio_config(PMIC_GPIO_WLAN_EXT_POR, &gpio23); if (rc) { pr_err("%s PMIC_GPIO_WLAN_EXT_POR config failed\n", __func__); return rc; } if (machine_is_msm7x30_fluid()) { rc = pm8058_gpio_config(PMIC_GPIO_SDC4_EN_N, &sdc4_en); if (rc) { pr_err("%s PMIC_GPIO_SDC4_EN_N config failed\n", __func__); return rc; } rc = gpio_request(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_SDC4_EN_N), "sdc4_en"); if (rc) { pr_err("%s PMIC_GPIO_SDC4_EN_N gpio_request failed\n", __func__); return rc; } gpio_set_value_cansleep( PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_SDC4_EN_N), 0); } /* FIHTDC, Div2-SW2-BSP, Ming, LCM { */ rc = pm8058_gpio_config(PMIC_GPIO_LCM_V1P8_EN, &lcm_v1p8_en); if (rc) { pr_err("%s PMIC_GPIO_LCM_V1P8_EN config failed\n", __func__); return rc; } /* } FIHTDC, Div2-SW2-BSP, Ming, LCM */ // DIV2-SW2-BSP-FBx-BUTTONS+ #ifdef CONFIG_KEYBOARD_GPIO rc = pm8058_gpio_config(PM_GPIO_VOLUP, &button_configuration); if (rc < 0) { printk(KERN_INFO "gpio %d configured failed\n", PM_GPIO_VOLUP); return rc; } rc = pm8058_gpio_config(PM_GPIO_VOLDN, &button_configuration); if (rc < 0) { printk(KERN_INFO "gpio %d configured failed\n", PM_GPIO_VOLDN); return rc; } if (fih_get_product_phase() == Product_PR1 || fih_get_product_phase() == Product_EVB) { rc = pm8058_gpio_config(PM_GPIO_CAMF, &button_configuration); if (rc < 0) { printk(KERN_INFO "gpio %d configured failed\n", PM_GPIO_CAMF); return rc; } rc = pm8058_gpio_config(PM_GPIO_CAMT, &button_configuration); if (rc < 0) { printk(KERN_INFO "gpio %d configured failed\n", PM_GPIO_CAMT); return rc; } gpio_buttons_pdata.nbuttons = KEY_NUM; } #endif // DIV2-SW2-BSP-FBx-BUTTONS- return 0; } /*virtual key support */ static ssize_t tma300_vkeys_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, __stringify(EV_KEY) ":" __stringify(KEY_BACK) ":50:842:80:100" ":" __stringify(EV_KEY) ":" __stringify(KEY_MENU) ":170:842:80:100" ":" __stringify(EV_KEY) ":" __stringify(KEY_HOME) ":290:842:80:100" ":" __stringify(EV_KEY) ":" __stringify(KEY_SEARCH) ":410:842:80:100" "\n"); } static struct kobj_attribute tma300_vkeys_attr = { .attr = { .mode = S_IRUGO, }, .show = &tma300_vkeys_show, }; static struct attribute *tma300_properties_attrs[] = { &tma300_vkeys_attr.attr, NULL }; static struct attribute_group tma300_properties_attr_group = { .attrs = tma300_properties_attrs, }; static struct kobject *properties_kobj; #define CYTTSP_TS_GPIO_IRQ 150 static int cyttsp_platform_init(struct i2c_client *client) { int rc = -EINVAL; struct vreg *vreg_ldo8, *vreg_ldo15; vreg_ldo8 = vreg_get(NULL, "gp7"); if (!vreg_ldo8) { pr_err("%s: VREG L8 get failed\n", __func__); return rc; } rc = vreg_set_level(vreg_ldo8, 1800); if (rc) { pr_err("%s: VREG L8 set failed\n", __func__); goto l8_put; } rc = vreg_enable(vreg_ldo8); if (rc) { pr_err("%s: VREG L8 enable failed\n", __func__); goto l8_put; } vreg_ldo15 = vreg_get(NULL, "gp6"); if (!vreg_ldo15) { pr_err("%s: VREG L15 get failed\n", __func__); goto l8_disable; } rc = vreg_set_level(vreg_ldo15, 3050); if (rc) { pr_err("%s: VREG L15 set failed\n", __func__); goto l8_disable; } rc = vreg_enable(vreg_ldo15); if (rc) { pr_err("%s: VREG L15 enable failed\n", __func__); goto l8_disable; } /* check this device active by reading first byte/register */ rc = i2c_smbus_read_byte_data(client, 0x01); if (rc < 0) { pr_err("%s: i2c sanity check failed\n", __func__); goto l8_disable; } rc = gpio_tlmm_config(GPIO_CFG(CYTTSP_TS_GPIO_IRQ, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_6MA), GPIO_CFG_ENABLE); if (rc) { pr_err("%s: Could not configure gpio %d\n", __func__, CYTTSP_TS_GPIO_IRQ); goto l8_disable; } rc = gpio_request(CYTTSP_TS_GPIO_IRQ, "ts_irq"); if (rc) { pr_err("%s: unable to request gpio %d (%d)\n", __func__, CYTTSP_TS_GPIO_IRQ, rc); goto l8_disable; } /* virtual keys */ tma300_vkeys_attr.attr.name = "virtualkeys.cyttsp-i2c"; properties_kobj = kobject_create_and_add("board_properties", NULL); if (properties_kobj) rc = sysfs_create_group(properties_kobj, &tma300_properties_attr_group); if (!properties_kobj || rc) pr_err("%s: failed to create board_properties\n", __func__); return CY_OK; l8_disable: vreg_disable(vreg_ldo8); l8_put: vreg_put(vreg_ldo8); return rc; } static int cyttsp_platform_resume(struct i2c_client *client) { /* add any special code to strobe a wakeup pin or chip reset */ mdelay(10); return CY_OK; } static struct cyttsp_platform_data cyttsp_data = { .panel_maxx = 479, .panel_maxy = 799, .disp_maxx = 469, .disp_maxy = 799, .disp_minx = 10, .disp_miny = 0, .flags = 0, .gen = CY_GEN3, /* or */ .use_st = CY_USE_ST, .use_mt = CY_USE_MT, .use_hndshk = CY_SEND_HNDSHK, .use_trk_id = CY_USE_TRACKING_ID, .use_sleep = CY_USE_SLEEP, .use_gestures = CY_USE_GESTURES, /* activate up to 4 groups * and set active distance */ .gest_set = CY_GEST_GRP1 | CY_GEST_GRP2 | CY_GEST_GRP3 | CY_GEST_GRP4 | CY_ACT_DIST, /* change act_intrvl to customize the Active power state * scanning/processing refresh interval for Operating mode */ .act_intrvl = CY_ACT_INTRVL_DFLT, /* change tch_tmout to customize the touch timeout for the * Active power state for Operating mode */ .tch_tmout = CY_TCH_TMOUT_DFLT, /* change lp_intrvl to customize the Low Power power state * scanning/processing refresh interval for Operating mode */ .lp_intrvl = CY_LP_INTRVL_DFLT, .resume = cyttsp_platform_resume, .init = cyttsp_platform_init, }; static int pm8058_pwm_config(struct pwm_device *pwm, int ch, int on) { struct pm8058_gpio pwm_gpio_config = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 0, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S3, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_2, }; int rc = -EINVAL; int id, mode, max_mA; id = mode = max_mA = 0; switch (ch) { case 0: case 1: case 2: if (on) { id = 24 + ch; rc = pm8058_gpio_config(id - 1, &pwm_gpio_config); if (rc) pr_err("%s: pm8058_gpio_config(%d): rc=%d\n", __func__, id, rc); } break; case 3: id = PM_PWM_LED_KPD; mode = PM_PWM_CONF_DTEST3; max_mA = 200; break; case 4: id = PM_PWM_LED_0; mode = PM_PWM_CONF_PWM1; max_mA = 40; break; // DIV2-SW2-BSP-FBx-LEDS+ #ifdef CONFIG_LEDS_FIH_FBX_PWM case 5: id = PM_PWM_LED_1; mode = PM_PWM_CONF_PWM2; max_mA = 40; break; case 6: id = PM_PWM_LED_2; mode = PM_PWM_CONF_PWM3; max_mA = 40; break; #else #ifdef CONFIG_FIH_PROJECT_SF4Y6 //OwenHung Add+ case 5: id = PM_PWM_LED_1; mode = PM_PWM_CONF_PWM2; max_mA = 10; break; case 6: id = PM_PWM_LED_2; mode = PM_PWM_CONF_PWM3; max_mA = 10; break; #else case 5: id = PM_PWM_LED_2; mode = PM_PWM_CONF_PWM2; max_mA = 40; break; case 6: id = PM_PWM_LED_FLASH; mode = PM_PWM_CONF_DTEST3; max_mA = 200; break; #endif #endif // DIV2-SW2-BSP-FBx-LEDS- default: break; } if (ch >= 3 && ch <= 6) { if (!on) { mode = PM_PWM_CONF_NONE; max_mA = 0; } rc = pm8058_pwm_config_led(pwm, id, mode, max_mA); if (rc) pr_err("%s: pm8058_pwm_config_led(ch=%d): rc=%d\n", __func__, ch, rc); } return rc; } static int pm8058_pwm_enable(struct pwm_device *pwm, int ch, int on) { int rc; switch (ch) { case 7: rc = pm8058_pwm_set_dtest(pwm, on); if (rc) pr_err("%s: pwm_set_dtest(%d): rc=%d\n", __func__, on, rc); break; default: rc = -EINVAL; break; } return rc; } #ifdef CONFIG_KEYBOARD_PMIC8058 static const unsigned int fluid_keymap[] = { KEY(0, 0, KEY_7), KEY(0, 1, KEY_ENTER), KEY(0, 2, KEY_UP), /* drop (0,3) as it always shows up in pair with(0,2) */ KEY(0, 4, KEY_DOWN), KEY(1, 0, KEY_CAMERA_SNAPSHOT), KEY(1, 1, KEY_SELECT), KEY(1, 2, KEY_1), KEY(1, 3, KEY_VOLUMEUP), KEY(1, 4, KEY_VOLUMEDOWN), }; static const unsigned int surf_keymap[] = { KEY(0, 0, KEY_7), KEY(0, 1, KEY_DOWN), KEY(0, 2, KEY_UP), KEY(0, 3, KEY_RIGHT), KEY(0, 4, KEY_ENTER), KEY(0, 5, KEY_L), KEY(0, 6, KEY_BACK), KEY(0, 7, KEY_M), KEY(1, 0, KEY_LEFT), KEY(1, 1, KEY_SEND), KEY(1, 2, KEY_1), KEY(1, 3, KEY_4), KEY(1, 4, KEY_CLEAR), KEY(1, 5, KEY_MSDOS), KEY(1, 6, KEY_SPACE), KEY(1, 7, KEY_COMMA), KEY(2, 0, KEY_6), KEY(2, 1, KEY_5), KEY(2, 2, KEY_8), KEY(2, 3, KEY_3), KEY(2, 4, KEY_NUMERIC_STAR), KEY(2, 5, KEY_UP), KEY(2, 6, KEY_DOWN), /* SYN */ KEY(2, 7, KEY_LEFTSHIFT), KEY(3, 0, KEY_9), KEY(3, 1, KEY_NUMERIC_POUND), KEY(3, 2, KEY_0), KEY(3, 3, KEY_2), KEY(3, 4, KEY_SLEEP), KEY(3, 5, KEY_F1), KEY(3, 6, KEY_F2), KEY(3, 7, KEY_F3), KEY(4, 0, KEY_BACK), KEY(4, 1, KEY_HOME), KEY(4, 2, KEY_MENU), KEY(4, 3, KEY_VOLUMEUP), KEY(4, 4, KEY_VOLUMEDOWN), KEY(4, 5, KEY_F4), KEY(4, 6, KEY_F5), KEY(4, 7, KEY_F6), KEY(5, 0, KEY_R), KEY(5, 1, KEY_T), KEY(5, 2, KEY_Y), KEY(5, 3, KEY_LEFTALT), KEY(5, 4, KEY_KPENTER), KEY(5, 5, KEY_Q), KEY(5, 6, KEY_W), KEY(5, 7, KEY_E), KEY(6, 0, KEY_F), KEY(6, 1, KEY_G), KEY(6, 2, KEY_H), KEY(6, 3, KEY_CAPSLOCK), KEY(6, 4, KEY_PAGEUP), KEY(6, 5, KEY_A), KEY(6, 6, KEY_S), KEY(6, 7, KEY_D), KEY(7, 0, KEY_V), KEY(7, 1, KEY_B), KEY(7, 2, KEY_N), KEY(7, 3, KEY_MENU), /* REVISIT - SYM */ KEY(7, 4, KEY_PAGEDOWN), KEY(7, 5, KEY_Z), KEY(7, 6, KEY_X), KEY(7, 7, KEY_C), KEY(8, 0, KEY_P), KEY(8, 1, KEY_J), KEY(8, 2, KEY_K), KEY(8, 3, KEY_INSERT), KEY(8, 4, KEY_LINEFEED), KEY(8, 5, KEY_U), KEY(8, 6, KEY_I), KEY(8, 7, KEY_O), KEY(9, 0, KEY_4), KEY(9, 1, KEY_5), KEY(9, 2, KEY_6), KEY(9, 3, KEY_7), KEY(9, 4, KEY_8), KEY(9, 5, KEY_1), KEY(9, 6, KEY_2), KEY(9, 7, KEY_3), KEY(10, 0, KEY_F7), KEY(10, 1, KEY_F8), KEY(10, 2, KEY_F9), KEY(10, 3, KEY_F10), KEY(10, 4, KEY_FN), KEY(10, 5, KEY_9), KEY(10, 6, KEY_0), KEY(10, 7, KEY_DOT), KEY(11, 0, KEY_LEFTCTRL), KEY(11, 1, KEY_F11), /* START */ KEY(11, 2, KEY_ENTER), KEY(11, 3, KEY_SEARCH), KEY(11, 4, KEY_DELETE), KEY(11, 5, KEY_RIGHT), KEY(11, 6, KEY_LEFT), KEY(11, 7, KEY_RIGHTSHIFT), }; static struct resource resources_keypad[] = { { .start = PM8058_KEYPAD_IRQ(PMIC8058_IRQ_BASE), .end = PM8058_KEYPAD_IRQ(PMIC8058_IRQ_BASE), .flags = IORESOURCE_IRQ, }, { .start = PM8058_KEYSTUCK_IRQ(PMIC8058_IRQ_BASE), .end = PM8058_KEYSTUCK_IRQ(PMIC8058_IRQ_BASE), .flags = IORESOURCE_IRQ, }, }; static struct matrix_keymap_data surf_keymap_data = { .keymap_size = ARRAY_SIZE(surf_keymap), .keymap = surf_keymap, }; static struct pmic8058_keypad_data surf_keypad_data = { .input_name = "surf_keypad", .input_phys_device = "surf_keypad/input0", .num_rows = 12, .num_cols = 8, .rows_gpio_start = 8, .cols_gpio_start = 0, .debounce_ms = {8, 10}, .scan_delay_ms = 32, .row_hold_ns = 91500, .wakeup = 1, .keymap_data = &surf_keymap_data, }; static struct matrix_keymap_data fluid_keymap_data = { .keymap_size = ARRAY_SIZE(fluid_keymap), .keymap = fluid_keymap, }; static struct pmic8058_keypad_data fluid_keypad_data = { .input_name = "fluid-keypad", .input_phys_device = "fluid-keypad/input0", .num_rows = 5, .num_cols = 5, .rows_gpio_start = 8, .cols_gpio_start = 0, .debounce_ms = {8, 10}, .scan_delay_ms = 32, .row_hold_ns = 91500, .wakeup = 1, .keymap_data = &fluid_keymap_data, }; #endif static struct pm8058_pwm_pdata pm8058_pwm_data = { .config = pm8058_pwm_config, .enable = pm8058_pwm_enable, }; /* Put sub devices with fixed location first in sub_devices array */ #define PM8058_SUBDEV_KPD 0 #define PM8058_SUBDEV_LED 1 static struct pm8058_gpio_platform_data pm8058_gpio_data = { .gpio_base = PM8058_GPIO_PM_TO_SYS(0), .irq_base = PM8058_GPIO_IRQ(PMIC8058_IRQ_BASE, 0), .init = pm8058_gpios_init, }; static struct pm8058_gpio_platform_data pm8058_mpp_data = { .gpio_base = PM8058_GPIO_PM_TO_SYS(PM8058_GPIOS), .irq_base = PM8058_MPP_IRQ(PMIC8058_IRQ_BASE, 0), }; #ifdef CONFIG_LEDS_PM8058 static struct pmic8058_led pmic8058_ffa_leds[] = { [0] = { .name = "keyboard-backlight", .max_brightness = 15, .id = PMIC8058_ID_LED_KB_LIGHT, }, }; static struct pmic8058_leds_platform_data pm8058_ffa_leds_data = { .num_leds = ARRAY_SIZE(pmic8058_ffa_leds), .leds = pmic8058_ffa_leds, }; static struct pmic8058_led pmic8058_surf_leds[] = { [0] = { .name = "keyboard-backlight", .max_brightness = 15, .id = PMIC8058_ID_LED_KB_LIGHT, }, [1] = { .name = "voice:red", .max_brightness = 20, .id = PMIC8058_ID_LED_0, }, [2] = { .name = "wlan:green", .max_brightness = 20, .id = PMIC8058_ID_LED_2, }, }; #endif // DIV2-SW2-BSP-FBx-VIB+ #ifdef CONFIG_PMIC8058_VIBRATOR static struct pmic8058_vibrator_pdata pmic_vib_pdata = { .initial_vibrate_ms = 0, .level_mV = 3000, .max_timeout_ms = 15000, }; #endif // DIV2-SW2-BSP-FBx-VIB- static struct mfd_cell pm8058_subdevs[] = { #ifdef CONFIG_KEYBOARD_PMIC8058 { .name = "pm8058-keypad", .id = -1, .num_resources = ARRAY_SIZE(resources_keypad), .resources = resources_keypad, }, #endif #ifdef CONFIG_LEDS_PMIC8058 { .name = "pm8058-led", .id = -1, }, #endif { .name = "pm8058-gpio", .id = -1, .platform_data = &pm8058_gpio_data, .data_size = sizeof(pm8058_gpio_data), }, { .name = "pm8058-mpp", .id = -1, .platform_data = &pm8058_mpp_data, .data_size = sizeof(pm8058_mpp_data), }, { .name = "pm8058-pwm", .id = -1, .platform_data = &pm8058_pwm_data, .data_size = sizeof(pm8058_pwm_data), }, { .name = "pm8058-nfc", .id = -1, }, { .name = "pm8058-upl", .id = -1, }, // DIV2-SW2-BSP-FBx-VIB+ #ifdef CONFIG_PMIC8058_VIBRATOR { .name = "pm8058-vib", .id = -1, .platform_data = &pmic_vib_pdata, .data_size = sizeof(pmic_vib_pdata), }, #endif // DIV2-SW2-BSP-FBx-VIB- }; #ifdef CONFIG_LEDS_PM8058 static struct pmic8058_leds_platform_data pm8058_surf_leds_data = { .num_leds = ARRAY_SIZE(pmic8058_surf_leds), .leds = pmic8058_surf_leds, }; static struct pmic8058_led pmic8058_fluid_leds[] = { [0] = { .name = "keyboard-backlight", .max_brightness = 15, .id = PMIC8058_ID_LED_KB_LIGHT, }, [1] = { .name = "flash:led_0", .max_brightness = 15, .id = PMIC8058_ID_FLASH_LED_0, }, [2] = { .name = "flash:led_1", .max_brightness = 15, .id = PMIC8058_ID_FLASH_LED_1, }, }; static struct pmic8058_leds_platform_data pm8058_fluid_leds_data = { .num_leds = ARRAY_SIZE(pmic8058_fluid_leds), .leds = pmic8058_fluid_leds, }; #endif /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ static struct gpio_switch_platform_data headset_sensor_device_data = { .name = "headset_sensor", .gpio = 26, .name_on = "", .name_off = "", .state_on = "", .state_off = "", }; static struct platform_device headset_sensor_device = { .name = "switch_gpio", .id = -1, .dev = { .platform_data = &headset_sensor_device_data }, }; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ static struct pm8058_platform_data pm8058_7x30_data = { .irq_base = PMIC8058_IRQ_BASE, .num_subdevs = ARRAY_SIZE(pm8058_subdevs), .sub_devices = pm8058_subdevs, .irq_trigger_flags = IRQF_TRIGGER_LOW, }; static struct i2c_board_info pm8058_boardinfo[] __initdata = { { I2C_BOARD_INFO("pm8058-core", 0x55), .irq = MSM_GPIO_TO_INT(PMIC_GPIO_INT), .platform_data = &pm8058_7x30_data, }, }; static struct i2c_board_info cy8info[] __initdata = { { I2C_BOARD_INFO(CY_I2C_NAME, 0x24), .platform_data = &cyttsp_data, #ifndef CY_USE_TIMER .irq = MSM_GPIO_TO_INT(CYTTSP_TS_GPIO_IRQ), #endif /* CY_USE_TIMER */ }, }; static struct i2c_board_info msm_camera_boardinfo[] __initdata = { #ifdef CONFIG_FIH_MT9P111 { I2C_BOARD_INFO("mt9p111", 0x78 >> 1), }, #endif #ifdef CONFIG_FIH_HM0356 { I2C_BOARD_INFO("hm0356", 0x68 >> 1), }, #endif #ifdef CONFIG_FIH_HM0357 { I2C_BOARD_INFO("hm0357", 0x60 >> 1), }, #endif #ifdef CONFIG_FIH_TCM9001MD { I2C_BOARD_INFO("tcm9001md", 0x7C >> 1), }, #endif #ifdef CONFIG_MT9D112 { I2C_BOARD_INFO("mt9d112", 0x78 >> 1), }, #endif #ifdef CONFIG_S5K3E2FX { I2C_BOARD_INFO("s5k3e2fx", 0x20 >> 1), }, #endif #ifdef CONFIG_MT9P012 { I2C_BOARD_INFO("mt9p012", 0x6C >> 1), }, #endif #ifdef CONFIG_VX6953 { I2C_BOARD_INFO("vx6953", 0x20), }, #endif #ifdef CONFIG_MT9E013 { I2C_BOARD_INFO("mt9e013", 0x6C >> 2), }, #endif #ifdef CONFIG_SN12M0PZ { I2C_BOARD_INFO("sn12m0pz", 0x34 >> 1), }, #endif #if defined(CONFIG_MT9T013) || defined(CONFIG_SENSORS_MT9T013) { I2C_BOARD_INFO("mt9t013", 0x6C), }, #endif }; #ifdef CONFIG_MSM_CAMERA #define CAM_STNDBY 143 static uint32_t camera_off_vcm_gpio_table[] = { //GPIO_CFG(1, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* VCM */ }; static uint32_t camera_off_gpio_table[] = { /* parallel CAMERA interfaces */ //GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* RST */ //GPIO_CFG(2, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT2 */ //GPIO_CFG(3, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT3 */ GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), GPIO_CFG(4, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT4 */ GPIO_CFG(5, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT5 */ GPIO_CFG(6, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT6 */ GPIO_CFG(7, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT7 */ GPIO_CFG(8, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT8 */ GPIO_CFG(9, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT9 */ GPIO_CFG(10, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT10 */ GPIO_CFG(11, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT11 */ GPIO_CFG(12, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* PCLK */ GPIO_CFG(13, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* HSYNC_IN */ GPIO_CFG(14, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* VSYNC_IN */ GPIO_CFG(15, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* MCLK */ #ifdef CONFIG_FIH_AAT1272 #ifdef CONFIG_FIH_PROJECT_SF4Y6 GPIO_CFG(30, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLASHLED_DRV_EN PIN*/ #else GPIO_CFG(39, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLASHLED_DRV_EN PIN*/ #endif #endif //GPIO_CFG(50, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* SWITCH PIN*/ }; static uint32_t camera_on_vcm_gpio_table[] = { //GPIO_CFG(1, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), /* VCM */ }; static uint32_t camera_on_gpio_table[] = { /* parallel CAMERA interfaces */ //GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* RST */ //GPIO_CFG(2, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT2 */ //GPIO_CFG(3, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT3 */ GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), //GPIO_CFG(1, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), //GPIO_CFG(2, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG(4, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT4 */ GPIO_CFG(5, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT5 */ GPIO_CFG(6, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT6 */ GPIO_CFG(7, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT7 */ GPIO_CFG(8, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT8 */ GPIO_CFG(9, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT9 */ GPIO_CFG(10, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT10 */ GPIO_CFG(11, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT11 */ GPIO_CFG(12, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* PCLK */ GPIO_CFG(13, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* HSYNC_IN */ GPIO_CFG(14, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* VSYNC_IN */ GPIO_CFG(15, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* MCLK */ #ifdef CONFIG_FIH_AAT1272 #ifdef CONFIG_FIH_PROJECT_SF4Y6 GPIO_CFG(30, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLASHLED_DRV_EN PIN*/ #else GPIO_CFG(39, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLASHLED_DRV_EN PIN*/ #endif #endif //GPIO_CFG(50, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* SWITCH PIN*/ }; static uint32_t camera_off_gpio_fluid_table[] = { /* FLUID: CAM_VGA_RST_N */ GPIO_CFG(31, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLUID: CAMIF_STANDBY */ GPIO_CFG(CAM_STNDBY, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) }; static uint32_t camera_on_gpio_fluid_table[] = { /* FLUID: CAM_VGA_RST_N */ GPIO_CFG(31, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLUID: CAMIF_STANDBY */ GPIO_CFG(CAM_STNDBY, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) }; static void config_gpio_table(uint32_t *table, int len) { int n, rc; for (n = 0; n < len; n++) { rc = gpio_tlmm_config(table[n], GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, table[n], rc); break; } } } static int config_camera_on_gpios(void) { config_gpio_table(camera_on_gpio_table, ARRAY_SIZE(camera_on_gpio_table)); if (adie_get_detected_codec_type() != TIMPANI_ID) /* GPIO1 is shared also used in Timpani RF card so only configure it for non-Timpani RF card */ config_gpio_table(camera_on_vcm_gpio_table, ARRAY_SIZE(camera_on_vcm_gpio_table)); if (machine_is_msm7x30_fluid()) { config_gpio_table(camera_on_gpio_fluid_table, ARRAY_SIZE(camera_on_gpio_fluid_table)); /* FLUID: turn on 5V booster */ gpio_set_value( PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_FLASH_BOOST_ENABLE), 1); /* FLUID: drive high to put secondary sensor to STANDBY */ gpio_set_value(CAM_STNDBY, 1); } return 0; } static void config_camera_off_gpios(void) { config_gpio_table(camera_off_gpio_table, ARRAY_SIZE(camera_off_gpio_table)); if (adie_get_detected_codec_type() != TIMPANI_ID) /* GPIO1 is shared also used in Timpani RF card so only configure it for non-Timpani RF card */ config_gpio_table(camera_off_vcm_gpio_table, ARRAY_SIZE(camera_off_vcm_gpio_table)); if (machine_is_msm7x30_fluid()) { config_gpio_table(camera_off_gpio_fluid_table, ARRAY_SIZE(camera_off_gpio_fluid_table)); /* FLUID: turn off 5V booster */ gpio_set_value( PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_FLASH_BOOST_ENABLE), 0); } } struct resource msm_camera_resources[] = { { .start = 0xA6000000, .end = 0xA6000000 + SZ_1M - 1, .flags = IORESOURCE_MEM, }, { .start = INT_VFE, .end = INT_VFE, .flags = IORESOURCE_IRQ, }, { .flags = IORESOURCE_DMA, } }; struct msm_camera_device_platform_data msm_camera_device_data = { .camera_gpio_on = config_camera_on_gpios, .camera_gpio_off = config_camera_off_gpios, .ioext.camifpadphy = 0xAB000000, .ioext.camifpadsz = 0x00000400, .ioext.csiphy = 0xA6100000, .ioext.csisz = 0x00000400, .ioext.csiirq = INT_CSI, .ioclk.mclk_clk_rate = 24000000, .ioclk.vfe_clk_rate = 122880000, }; static struct msm_camera_sensor_flash_src msm_flash_src_pwm = { .flash_sr_type = MSM_CAMERA_FLASH_SRC_PWM, ._fsrc.pwm_src.freq = 1000, ._fsrc.pwm_src.max_load = 300, ._fsrc.pwm_src.low_load = 30, ._fsrc.pwm_src.high_load = 100, ._fsrc.pwm_src.channel = 7, }; #ifdef CONFIG_FIH_MT9P111 static struct msm_camera_sensor_flash_data flash_mt9p111 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_parameters_data parameters_mt9p111 = { }; static struct msm_camera_sensor_info msm_camera_sensor_mt9p111_data = { .sensor_name = "mt9p111", .sensor_reset = 1, .sensor_pwd = 2, .sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_90, .vcm_pwd = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9p111, .parameters_data = &parameters_mt9p111, .csi_if = 0, /* Declare for camea pins */ .MCLK_PIN =15 , .mclk_sw_pin = 0xffff, .pwdn_pin = 0xffff, .rst_pin = 0xffff, .vga_pwdn_pin = 0xffff, .vga_rst_pin = 0xffff, .vga_power_en_pin = 0xffff, .standby_pin = 0xffff, .GPIO_FLASHLED = 0xffff, .GPIO_FLASHLED_DRV_EN = 0xffff, /* Declare for camera power */ .AF_pmic_en_pin= 0xffff, .cam_v2p8_en_pin = 0xffff, .cam_vreg_vddio_id = "NoVreg", .cam_vreg_acore_id = "NoVreg", /* Flash LED setting */ .flash_target_addr = 0xffff, .flash_target = 0xffff, .flash_bright = 0xffff, .flash_main_waittime = 0, .flash_main_starttime = 0, .flash_second_waittime = 0, .preflash_light = 0x31, .torch_light = 0x34, .fast_af_retest_target = 0xffff }; static struct platform_device msm_camera_sensor_mt9p111 = { .name = "msm_camera_mt9p111", .dev = { .platform_data = &msm_camera_sensor_mt9p111_data, }, }; #endif #ifdef CONFIG_FIH_HM0356 static struct msm_camera_sensor_flash_data flash_hm0356 = { .flash_type = MSM_CAMERA_FLASH_NONE, .flash_src = &msm_flash_src_pwm }; static struct msm_parameters_data parameters_hm0356 = { }; static struct msm_camera_sensor_info msm_camera_sensor_hm0356_data = { .sensor_name = "hm0356", .sensor_pwd = 0, .sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_hm0356, .parameters_data = &parameters_hm0356, .csi_if = 0, /* Declare for camea pins */ .MCLK_PIN =15 , .mclk_sw_pin = 0xffff, .pwdn_pin = 0xffff, .rst_pin = 0xffff, .vga_pwdn_pin = 0xffff, .vga_rst_pin = 0xffff, .vga_power_en_pin = 0xffff, .standby_pin = 0xffff, .GPIO_FLASHLED = 0xffff, .GPIO_FLASHLED_DRV_EN = 0xffff, /* Declare for camera power */ .AF_pmic_en_pin= 0xffff, .cam_v2p8_en_pin = 0xffff, .cam_vreg_vddio_id = "NoVreg", .cam_vreg_acore_id = "NoVreg" }; static struct platform_device msm_camera_sensor_hm0356 = { .name = "msm_camera_hm0356", .dev = { .platform_data = &msm_camera_sensor_hm0356_data, }, }; #endif #ifdef CONFIG_FIH_HM0357 static struct msm_camera_sensor_flash_data flash_hm0357 = { .flash_type = MSM_CAMERA_FLASH_NONE, .flash_src = &msm_flash_src_pwm }; static struct msm_parameters_data parameters_hm0357 = { }; static struct msm_camera_sensor_info msm_camera_sensor_hm0357_data = { .sensor_name = "hm0357", .sensor_pwd = 0, .sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_90, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_hm0357, .parameters_data = &parameters_hm0357, .csi_if = 0, /* Declare for camea pins */ .MCLK_PIN =15 , .mclk_sw_pin = 0xffff, .pwdn_pin = 0xffff, .rst_pin = 0xffff, .vga_pwdn_pin = 0xffff, .vga_rst_pin = 0xffff, .vga_power_en_pin = 0xffff, .standby_pin = 0xffff, .GPIO_FLASHLED = 0xffff, .GPIO_FLASHLED_DRV_EN = 0xffff, /* Declare for camera power */ .AF_pmic_en_pin= 0xffff, .cam_v2p8_en_pin = 0xffff, .cam_vreg_vddio_id = "NoVreg", .cam_vreg_acore_id = "NoVreg" }; static struct platform_device msm_camera_sensor_hm0357 = { .name = "msm_camera_hm0357", .dev = { .platform_data = &msm_camera_sensor_hm0357_data, }, }; #endif #ifdef CONFIG_FIH_TCM9001MD static struct msm_camera_sensor_flash_data flash_tcm9001md = { .flash_type = MSM_CAMERA_FLASH_NONE, .flash_src = &msm_flash_src_pwm }; static struct msm_parameters_data parameters_tcm9001md = { }; static struct msm_camera_sensor_info msm_camera_sensor_tcm9001md_data = { .sensor_name = "tcm9001md", .sensor_reset = 19, .sensor_pwd = 0, .sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_tcm9001md, .parameters_data = &parameters_tcm9001md, .csi_if = 0, /* Declare for camea pins */ .MCLK_PIN =15 , .mclk_sw_pin = 0xffff, .pwdn_pin = 0xffff, .rst_pin = 0xffff, .vga_pwdn_pin = 0xffff, .vga_rst_pin = 0xffff, .vga_power_en_pin = 0xffff, .standby_pin = 0xffff, .GPIO_FLASHLED = 0xffff, .GPIO_FLASHLED_DRV_EN = 0xffff, /* Declare for camera power */ .AF_pmic_en_pin= 0xffff, .cam_v2p8_en_pin = 0xffff, .cam_vreg_vddio_id = "NoVreg", .cam_vreg_acore_id = "NoVreg" }; static struct platform_device msm_camera_sensor_tcm9001md = { .name = "msm_camera_tcm9001md", .dev = { .platform_data = &msm_camera_sensor_tcm9001md_data, }, }; #endif #ifdef CONFIG_MT9D112 static struct msm_camera_sensor_flash_data flash_mt9d112 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_mt9d112_data = { .sensor_name = "mt9d112", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9d112, .csi_if = 0 }; static struct platform_device msm_camera_sensor_mt9d112 = { .name = "msm_camera_mt9d112", .dev = { .platform_data = &msm_camera_sensor_mt9d112_data, }, }; #endif #ifdef CONFIG_S5K3E2FX static struct msm_camera_sensor_flash_data flash_s5k3e2fx = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm, }; static struct msm_camera_sensor_info msm_camera_sensor_s5k3e2fx_data = { .sensor_name = "s5k3e2fx", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_s5k3e2fx, .csi_if = 0 }; static struct platform_device msm_camera_sensor_s5k3e2fx = { .name = "msm_camera_s5k3e2fx", .dev = { .platform_data = &msm_camera_sensor_s5k3e2fx_data, }, }; #endif #ifdef CONFIG_MT9P012 static struct msm_camera_sensor_flash_data flash_mt9p012 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_mt9p012_data = { .sensor_name = "mt9p012", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 1, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9p012, .csi_if = 0 }; static struct platform_device msm_camera_sensor_mt9p012 = { .name = "msm_camera_mt9p012", .dev = { .platform_data = &msm_camera_sensor_mt9p012_data, }, }; #endif #ifdef CONFIG_MT9E013 static struct msm_camera_sensor_flash_data flash_mt9e013 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_mt9e013_data = { .sensor_name = "mt9e013", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 1, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9e013, .csi_if = 1 }; static struct platform_device msm_camera_sensor_mt9e013 = { .name = "msm_camera_mt9e013", .dev = { .platform_data = &msm_camera_sensor_mt9e013_data, }, }; #endif #ifdef CONFIG_VX6953 static struct msm_camera_sensor_flash_data flash_vx6953 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_vx6953_data = { .sensor_name = "vx6953", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_vx6953, .csi_if = 1 }; static struct platform_device msm_camera_sensor_vx6953 = { .name = "msm_camera_vx6953", .dev = { .platform_data = &msm_camera_sensor_vx6953_data, }, }; #endif #ifdef CONFIG_SN12M0PZ static struct msm_camera_sensor_flash_src msm_flash_src_current_driver = { .flash_sr_type = MSM_CAMERA_FLASH_SRC_CURRENT_DRIVER, ._fsrc.current_driver_src.low_current = 210, ._fsrc.current_driver_src.high_current = 700, #ifdef CONFIG_LEDS_PMIC8058 ._fsrc.current_driver_src.driver_channel = &pm8058_fluid_leds_data, #endif }; static struct msm_camera_sensor_flash_data flash_sn12m0pz = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_current_driver }; static struct msm_camera_sensor_info msm_camera_sensor_sn12m0pz_data = { .sensor_name = "sn12m0pz", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 1, .pdata = &msm_camera_device_data, .flash_data = &flash_sn12m0pz, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .csi_if = 0 }; static struct platform_device msm_camera_sensor_sn12m0pz = { .name = "msm_camera_sn12m0pz", .dev = { .platform_data = &msm_camera_sensor_sn12m0pz_data, }, }; #endif #ifdef CONFIG_MT9T013 static struct msm_camera_sensor_flash_data flash_mt9t013 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_mt9t013_data = { .sensor_name = "mt9t013", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9t013, .csi_if = 1 }; static struct platform_device msm_camera_sensor_mt9t013 = { .name = "msm_camera_mt9t013", .dev = { .platform_data = &msm_camera_sensor_mt9t013_data, }, }; #endif #ifdef CONFIG_MSM_GEMINI static struct resource msm_gemini_resources[] = { { .start = 0xA3A00000, .end = 0xA3A00000 + 0x0150 - 1, .flags = IORESOURCE_MEM, }, { .start = INT_JPEG, .end = INT_JPEG, .flags = IORESOURCE_IRQ, }, }; static struct platform_device msm_gemini_device = { .name = "msm_gemini", .resource = msm_gemini_resources, .num_resources = ARRAY_SIZE(msm_gemini_resources), }; #endif #ifdef CONFIG_MSM_VPE static struct resource msm_vpe_resources[] = { { .start = 0xAD200000, .end = 0xAD200000 + SZ_1M - 1, .flags = IORESOURCE_MEM, }, { .start = INT_VPE, .end = INT_VPE, .flags = IORESOURCE_IRQ, }, }; static struct platform_device msm_vpe_device = { .name = "msm_vpe", .id = 0, .num_resources = ARRAY_SIZE(msm_vpe_resources), .resource = msm_vpe_resources, }; #endif void camera_sensor_hwpin_init(void) { int pid = 0; int phid = 0; pid = fih_get_product_id(); phid = fih_get_product_phase(); #ifdef CONFIG_FIH_MT9P111 #if 1 if (pid == Product_SF5) { /* Declare for camea pins */ if (phid <= Product_PR2) { msm_camera_sensor_mt9p111_data.rst_pin = 1; } else { msm_camera_sensor_mt9p111_data.rst_pin = 120; } msm_camera_sensor_mt9p111_data.pwdn_pin = 2; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 0; msm_camera_sensor_mt9p111_data.standby_pin=33; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED = 3; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED_DRV_EN = 39; /* Declare for camera power */ msm_camera_sensor_mt9p111_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_mt9p111_data.cam_vreg_acore_id = "gp10"; /* Flash LED setting */ msm_camera_sensor_mt9p111_data.flash_target_addr = 0xB80C; msm_camera_sensor_mt9p111_data.flash_target = 0x07BE; msm_camera_sensor_mt9p111_data.flash_bright = 0x20; msm_camera_sensor_mt9p111_data.flash_main_waittime = 150; msm_camera_sensor_mt9p111_data.flash_main_starttime = 150; msm_camera_sensor_mt9p111_data.flash_second_waittime = 200; /*Fast AF*/ msm_camera_sensor_mt9p111_data.fast_af_retest_target = 0x2000; } else if (pid == Product_SF6) { msm_camera_sensor_mt9p111_data.sensor_Orientation=MSM_CAMERA_SENSOR_ORIENTATION_270; /* Declare for camea pins */ msm_camera_sensor_mt9p111_data.rst_pin = 3; msm_camera_sensor_mt9p111_data.pwdn_pin = 2; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 0; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED = 164; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED_DRV_EN = 30; /* Declare for camera power */ msm_camera_sensor_mt9p111_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_mt9p111_data.cam_vreg_acore_id = "gp10"; /* Flash LED setting */ msm_camera_sensor_mt9p111_data.flash_target_addr = 0xB80C; msm_camera_sensor_mt9p111_data.flash_target = 0x2E00; msm_camera_sensor_mt9p111_data.flash_bright = 0x20; msm_camera_sensor_mt9p111_data.flash_main_waittime = 100; msm_camera_sensor_mt9p111_data.flash_main_starttime = 200; msm_camera_sensor_mt9p111_data.flash_second_waittime = 200; /*Fast AF*/ msm_camera_sensor_mt9p111_data.fast_af_retest_target = 0x3800; } else if (IS_SF8_SERIES_PRJ()) { /* Declare for camea pins */ if (pid == Product_SF8 && phid < Product_PR2) { msm_camera_sensor_mt9p111_data.rst_pin = 1; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 0; } else { msm_camera_sensor_mt9p111_data.rst_pin = 173; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 174; } msm_camera_sensor_mt9p111_data.pwdn_pin = 2; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED = 177; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED_DRV_EN = 3; /* Declare for camera power */ msm_camera_sensor_mt9p111_data.cam_v2p8_en_pin = 120; msm_camera_sensor_mt9p111_data.cam_vreg_vddio_id = "gp10"; msm_camera_sensor_mt9p111_data.cam_vreg_acore_id = "NoVreg"; /* Flash LED setting */ msm_camera_sensor_mt9p111_data.flash_target_addr = 0x3012; msm_camera_sensor_mt9p111_data.flash_target = 0x9C4; msm_camera_sensor_mt9p111_data.flash_bright = 0x30; msm_camera_sensor_mt9p111_data.flash_main_waittime = 100; msm_camera_sensor_mt9p111_data.flash_main_starttime = 200; msm_camera_sensor_mt9p111_data.flash_second_waittime = 200; /*Fast AF*/ msm_camera_sensor_mt9p111_data.fast_af_retest_target = 0x2000; } else// For FBx and FDx series project #endif { /* Declare for camea pins */ msm_camera_sensor_mt9p111_data.rst_pin = 1; msm_camera_sensor_mt9p111_data.pwdn_pin = 2; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 0; msm_camera_sensor_mt9p111_data.standby_pin=33; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED = 3; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED_DRV_EN = 39; msm_camera_sensor_mt9p111_data.AF_pmic_en_pin=16; msm_camera_sensor_mt9p111_data.mclk_sw_pin = 50; /* Declare for camera power */ msm_camera_sensor_mt9p111_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_mt9p111_data.cam_vreg_acore_id = "gp10"; /* Flash LED setting */ msm_camera_sensor_mt9p111_data.flash_target_addr = 0x3012; msm_camera_sensor_mt9p111_data.flash_target = 0x7AA; msm_camera_sensor_mt9p111_data.flash_bright = 0x14; msm_camera_sensor_mt9p111_data.flash_main_waittime = 300; msm_camera_sensor_mt9p111_data.flash_main_starttime = 90; msm_camera_sensor_mt9p111_data.flash_second_waittime = 200; /*Fast AF*/ msm_camera_sensor_mt9p111_data.fast_af_retest_target = 0x2000; #if 1 if(pid ==Product_FD1 ) { msm_camera_sensor_mt9p111_data.flash_target = 0x7D0; msm_camera_sensor_mt9p111_data.flash_main_starttime = 90; msm_camera_sensor_mt9p111_data.flash_main_waittime = 700; } if(pid ==Product_FB3 ) { msm_camera_sensor_mt9p111_data.torch_light = 0x3E; msm_camera_sensor_mt9p111_data.preflash_light=0x3E; } #endif } #endif #ifdef CONFIG_FIH_HM0356 /*Setting camera pins */ #if 1 if (IS_SF8_SERIES_PRJ()) { if (pid == Product_SF8 && phid < Product_PR2) { msm_camera_sensor_hm0356_data.rst_pin = 1; msm_camera_sensor_hm0356_data.vga_pwdn_pin = 0; } else { msm_camera_sensor_hm0356_data.rst_pin = 173; msm_camera_sensor_hm0356_data.vga_pwdn_pin = 174; } msm_camera_sensor_hm0356_data.pwdn_pin = 2; msm_camera_sensor_hm0356_data.mclk_sw_pin = 0xffff; /* Declare for camera power */ msm_camera_sensor_hm0356_data.cam_v2p8_en_pin = 120; msm_camera_sensor_hm0356_data.cam_vreg_vddio_id="gp10"; msm_camera_sensor_hm0356_data.cam_vreg_acore_id="NoVreg"; } else if (pid == Product_SF6) { msm_camera_sensor_hm0356_data.sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_180, msm_camera_sensor_hm0356_data.rst_pin = 3; msm_camera_sensor_hm0356_data.pwdn_pin = 2; msm_camera_sensor_hm0356_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0356_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_hm0356_data.cam_vreg_acore_id = "gp10"; } else// For FBx and FDx series project #endif { msm_camera_sensor_hm0356_data.rst_pin = 1; msm_camera_sensor_hm0356_data.pwdn_pin = 2; msm_camera_sensor_hm0356_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0356_data.mclk_sw_pin = 50; msm_camera_sensor_hm0356_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_hm0356_data.cam_vreg_acore_id = "gp10"; } #endif #ifdef CONFIG_FIH_HM0357 /*Setting camera pins */ #if 1 if (IS_SF8_SERIES_PRJ()) { if (pid == Product_SF8 && phid < Product_PR2) { msm_camera_sensor_hm0357_data.rst_pin = 1; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 0; } else { msm_camera_sensor_hm0357_data.rst_pin = 173; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 174; } msm_camera_sensor_hm0357_data.sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_270, msm_camera_sensor_hm0357_data.pwdn_pin = 2; msm_camera_sensor_hm0357_data.mclk_sw_pin = 0xffff; /* Declare for camera power */ msm_camera_sensor_hm0357_data.cam_v2p8_en_pin = 120; msm_camera_sensor_hm0357_data.cam_vreg_vddio_id="gp10"; msm_camera_sensor_hm0357_data.cam_vreg_acore_id="NoVreg"; } else if (pid == Product_SF6) { msm_camera_sensor_hm0357_data.sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_180, msm_camera_sensor_hm0357_data.rst_pin = 3; msm_camera_sensor_hm0357_data.pwdn_pin = 2; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0357_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_hm0357_data.cam_vreg_acore_id = "gp10"; } else if (pid == Product_SF5) { msm_camera_sensor_hm0357_data.rst_pin = 120; msm_camera_sensor_hm0357_data.pwdn_pin = 2; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0357_data.vga_power_en_pin = 98; } else// For FBx and FDx series project #endif { msm_camera_sensor_hm0357_data.rst_pin = 1; msm_camera_sensor_hm0357_data.pwdn_pin = 2; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0357_data.mclk_sw_pin = 50; msm_camera_sensor_hm0357_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_hm0357_data.cam_vreg_acore_id = "gp10"; } #endif #if 1 #ifdef CONFIG_FIH_TCM9001MD if (pid == Product_SF5) { /*5M sensor pins*/ if (phid <= Product_PR2) { msm_camera_sensor_tcm9001md_data.rst_pin = 1; } else { msm_camera_sensor_tcm9001md_data.rst_pin = 120; } msm_camera_sensor_tcm9001md_data.pwdn_pin = 2; /*VGA sensor pins*/ msm_camera_sensor_tcm9001md_data.vga_rst_pin = 19; msm_camera_sensor_tcm9001md_data.vga_pwdn_pin = 0; msm_camera_sensor_tcm9001md_data.vga_power_en_pin = 98; } else { /*5M sensor pins*/ if (phid <= Product_PR2) { msm_camera_sensor_tcm9001md_data.rst_pin = 1; } else { msm_camera_sensor_tcm9001md_data.rst_pin = 120; } msm_camera_sensor_tcm9001md_data.pwdn_pin = 2; /*VGA sensor pins*/ msm_camera_sensor_tcm9001md_data.vga_rst_pin = 19; msm_camera_sensor_tcm9001md_data.vga_pwdn_pin = 0; msm_camera_sensor_tcm9001md_data.vga_power_en_pin = 98; } #endif #endif } #endif /*CONFIG_MSM_CAMERA*/ #ifdef CONFIG_MSM7KV2_AUDIO static uint32_t audio_pamp_gpio_config = GPIO_CFG(82, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); static uint32_t audio_fluid_icodec_tx_config = GPIO_CFG(85, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ int SPK1_AMP = 36; int SPK2_AMP = 37; int HS_AMP = 55; static uint32_t audio_pamp_spk1_amp_gpio_config = 0; static uint32_t audio_pamp_spk2_amp_gpio_config = 0; static uint32_t audio_pamp_hs_amp_gpio_config = 0; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ static int __init snddev_poweramp_gpio_init(void) { int rc; /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ int pid =0; pid = fih_get_product_id(); if((pid==Product_SF5)||IS_SF8_SERIES_PRJ()) { SPK1_AMP = 36; } else if(pid==Product_SF6) { SPK1_AMP = 37; } else { SPK1_AMP = 36; SPK2_AMP = 37; } audio_pamp_spk1_amp_gpio_config = GPIO_CFG(SPK1_AMP, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); audio_pamp_spk2_amp_gpio_config = GPIO_CFG(SPK2_AMP, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); audio_pamp_hs_amp_gpio_config = GPIO_CFG(HS_AMP, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); pr_info("snddev_poweramp_gpio_init \n"); rc = gpio_tlmm_config(audio_pamp_spk1_amp_gpio_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_pamp_spk1_amp_gpio_config, rc); } rc = gpio_tlmm_config(audio_pamp_spk2_amp_gpio_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_pamp_spk2_amp_gpio_config, rc); } rc = gpio_tlmm_config(audio_pamp_hs_amp_gpio_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_pamp_hs_amp_gpio_config, rc); } /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ pr_info("snddev_poweramp_gpio_init \n"); rc = gpio_tlmm_config(audio_pamp_gpio_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_pamp_gpio_config, rc); } return rc; } void msm_snddev_tx_route_config(void) { int rc; pr_debug("%s()\n", __func__); if (machine_is_msm7x30_fluid()) { rc = gpio_tlmm_config(audio_fluid_icodec_tx_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_fluid_icodec_tx_config, rc); } else gpio_set_value(85, 0); } } void msm_snddev_tx_route_deconfig(void) { int rc; pr_debug("%s()\n", __func__); if (machine_is_msm7x30_fluid()) { rc = gpio_tlmm_config(audio_fluid_icodec_tx_config, GPIO_CFG_DISABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_fluid_icodec_tx_config, rc); } } } void msm_snddev_poweramp_on(void) { /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ pr_info("%s: power on amplifier\n", __func__); m_SpkAmpOn=true; /* enable spkr poweramp */ /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ } void msm_snddev_poweramp_off(void) { /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ pr_info("%s: power off amplifier\n", __func__); m_SpkAmpOn=false; /* disable spkr poweramp */ /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ } /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ #ifndef CONFIG_FIH_FBX_AUDIO static struct vreg *snddev_vreg_ncp, *snddev_vreg_gp4; #endif // CONFIG_FIH_FBX_AUDIO /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ void msm_snddev_hsed_voltage_on(void) { /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ #ifndef CONFIG_FIH_FBX_AUDIO int rc; snddev_vreg_gp4 = vreg_get(NULL, "gp4"); if (IS_ERR(snddev_vreg_gp4)) { pr_err("%s: vreg_get(%s) failed (%ld)\n", __func__, "gp4", PTR_ERR(snddev_vreg_gp4)); return; } rc = vreg_enable(snddev_vreg_gp4); if (rc) pr_err("%s: vreg_enable(gp4) failed (%d)\n", __func__, rc); snddev_vreg_ncp = vreg_get(NULL, "ncp"); if (IS_ERR(snddev_vreg_ncp)) { pr_err("%s: vreg_get(%s) failed (%ld)\n", __func__, "ncp", PTR_ERR(snddev_vreg_ncp)); return; } rc = vreg_enable(snddev_vreg_ncp); if (rc) pr_err("%s: vreg_enable(ncp) failed (%d)\n", __func__, rc); #endif // CONFIG_FIH_FBX_AUDIO /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ m_HsAmpOn=true; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ } void msm_snddev_hsed_voltage_off(void) { /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ #ifndef CONFIG_FIH_FBX_AUDIO int rc; if (IS_ERR(snddev_vreg_ncp)) { pr_err("%s: vreg_get(%s) failed (%ld)\n", __func__, "ncp", PTR_ERR(snddev_vreg_ncp)); return; } rc = vreg_disable(snddev_vreg_ncp); if (rc) pr_err("%s: vreg_disable(ncp) failed (%d)\n", __func__, rc); vreg_put(snddev_vreg_ncp); if (IS_ERR(snddev_vreg_gp4)) { pr_err("%s: vreg_get(%s) failed (%ld)\n", __func__, "gp4", PTR_ERR(snddev_vreg_gp4)); return; } rc = vreg_disable(snddev_vreg_gp4); if (rc) pr_err("%s: vreg_disable(gp4) failed (%d)\n", __func__, rc); vreg_put(snddev_vreg_gp4); #endif // CONFIG_FIH_FBX_AUDIO /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ m_HsAmpOn=false; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ } static unsigned aux_pcm_gpio_on[] = { GPIO_CFG(138, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* PCM_DOUT */ GPIO_CFG(139, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* PCM_DIN */ GPIO_CFG(140, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* PCM_SYNC */ GPIO_CFG(141, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* PCM_CLK */ }; static int __init aux_pcm_gpio_init(void) { int pin, rc; pr_info("aux_pcm_gpio_init \n"); for (pin = 0; pin < ARRAY_SIZE(aux_pcm_gpio_on); pin++) { rc = gpio_tlmm_config(aux_pcm_gpio_on[pin], GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, aux_pcm_gpio_on[pin], rc); } } return rc; } static struct msm_gpio mi2s_clk_gpios[] = { { GPIO_CFG(145, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_SCLK"}, { GPIO_CFG(144, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_WS"}, }; //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+{ static struct msm_gpio mi2s_mclk_gpios[] = { { GPIO_CFG(120, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_MCLK_A"}, }; //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+} static struct msm_gpio mi2s_rx_data_lines_gpios[] = { { GPIO_CFG(121, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD0_A"}, { GPIO_CFG(122, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD1_A"}, { GPIO_CFG(123, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD2_A"}, { GPIO_CFG(146, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD3"}, }; static struct msm_gpio mi2s_tx_data_lines_gpios[] = { { GPIO_CFG(146, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD3"}, }; int mi2s_config_clk_gpio(void) { //MM-RC-ChangeFMPath-00*{ if(!IS_SF8_SERIES_PRJ()){ int rc = 0; rc = msm_gpios_request_enable(mi2s_clk_gpios, ARRAY_SIZE(mi2s_clk_gpios)); if (rc) { pr_err("%s: enable mi2s clk gpios failed\n", __func__); return rc; } //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+{ if ((fih_get_product_id() != Product_SF5) || (fih_get_product_phase() != Product_PCR)) { rc = msm_gpios_request_enable(mi2s_mclk_gpios, ARRAY_SIZE(mi2s_mclk_gpios)); if (rc) { pr_err("%s: enable mi2s clk gpios failed\n", __func__); return rc; } } //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+} } //MM-RC-ChangeFMPath-00*} return 0; } int mi2s_unconfig_data_gpio(u32 direction, u8 sd_line_mask) { int i, rc = 0; //MM-RC-ChangeFMPath-01*{ if(IS_SF8_SERIES_PRJ()) return rc; //MM-RC-ChangeFMPath-01*} sd_line_mask &= MI2S_SD_LINE_MASK; switch (direction) { case DIR_TX: msm_gpios_disable_free(mi2s_tx_data_lines_gpios, 1); break; case DIR_RX: i = 0; while (sd_line_mask) { if (sd_line_mask & 0x1) msm_gpios_disable_free( mi2s_rx_data_lines_gpios + i , 1); sd_line_mask = sd_line_mask >> 1; i++; } break; default: pr_err("%s: Invaild direction direction = %u\n", __func__, direction); rc = -EINVAL; break; } return rc; } int mi2s_config_data_gpio(u32 direction, u8 sd_line_mask) { int i , rc = 0; u8 sd_config_done_mask = 0; //MM-RC-ChangeFMPath-01*{ if(IS_SF8_SERIES_PRJ()) return rc; //MM-RC-ChangeFMPath-01*} sd_line_mask &= MI2S_SD_LINE_MASK; switch (direction) { case DIR_TX: if ((sd_line_mask & MI2S_SD_0) || (sd_line_mask & MI2S_SD_1) || (sd_line_mask & MI2S_SD_2) || !(sd_line_mask & MI2S_SD_3)) { pr_err("%s: can not use SD0 or SD1 or SD2 for TX" ".only can use SD3. sd_line_mask = 0x%x\n", __func__ , sd_line_mask); rc = -EINVAL; } else { rc = msm_gpios_request_enable(mi2s_tx_data_lines_gpios, 1); if (rc) pr_err("%s: enable mi2s gpios for TX failed\n", __func__); } break; case DIR_RX: i = 0; while (sd_line_mask && (rc == 0)) { if (sd_line_mask & 0x1) { rc = msm_gpios_request_enable( mi2s_rx_data_lines_gpios + i , 1); if (rc) { pr_err("%s: enable mi2s gpios for" "RX failed. SD line = %s\n", __func__, (mi2s_rx_data_lines_gpios + i)->label); mi2s_unconfig_data_gpio(DIR_RX, sd_config_done_mask); } else sd_config_done_mask |= (1 << i); } sd_line_mask = sd_line_mask >> 1; i++; } break; default: pr_err("%s: Invaild direction direction = %u\n", __func__, direction); rc = -EINVAL; break; } return rc; } int mi2s_unconfig_clk_gpio(void) { //MM-RC-ChangeFMPath-00*{ if(!IS_SF8_SERIES_PRJ()){ msm_gpios_disable_free(mi2s_clk_gpios, ARRAY_SIZE(mi2s_clk_gpios)); //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+{ if ((fih_get_product_id() != Product_SF5) || (fih_get_product_phase() != Product_PCR)) { msm_gpios_disable_free(mi2s_mclk_gpios, ARRAY_SIZE(mi2s_mclk_gpios)); } //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+} } //MM-RC-ChangeFMPath-00*} return 0; } #endif /* CONFIG_MSM7KV2_AUDIO */ static int __init buses_init(void) { if (gpio_tlmm_config(GPIO_CFG(PMIC_GPIO_INT, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE)) pr_err("%s: gpio_tlmm_config (gpio=%d) failed\n", __func__, PMIC_GPIO_INT); #ifdef CONFIG_KEYBOARD_PMIC8058 if (machine_is_msm7x30_fluid()) { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_KPD].platform_data = &fluid_keypad_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_KPD].data_size = sizeof(fluid_keypad_data); } else { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_KPD].platform_data = &surf_keypad_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_KPD].data_size = sizeof(surf_keypad_data); } #endif i2c_register_board_info(6 /* I2C_SSBI ID */, pm8058_boardinfo, ARRAY_SIZE(pm8058_boardinfo)); return 0; } #define TIMPANI_RESET_GPIO 1 struct bahama_config_register{ u8 reg; u8 value; u8 mask; }; enum version{ VER_1_0, VER_2_0, VER_UNSUPPORTED = 0xFF }; static struct vreg *vreg_marimba_1; static struct vreg *vreg_marimba_2; static struct vreg *vreg_marimba_3; static struct msm_gpio timpani_reset_gpio_cfg[] = { { GPIO_CFG(TIMPANI_RESET_GPIO, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "timpani_reset"} }; static u8 read_bahama_ver(void) { int rc; struct marimba config = { .mod_id = SLAVE_ID_BAHAMA }; u8 bahama_version; rc = marimba_read_bit_mask(&config, 0x00, &bahama_version, 1, 0x1F); if (rc < 0) { printk(KERN_ERR "%s: version read failed: %d\n", __func__, rc); return rc; } else { printk(KERN_INFO "%s: version read got: 0x%x\n", __func__, bahama_version); } switch (bahama_version) { case 0x08: /* varient of bahama v1 */ case 0x10: case 0x00: return VER_1_0; case 0x09: /* variant of bahama v2 */ return VER_2_0; default: return VER_UNSUPPORTED; } } static int config_timpani_reset(void) { int rc; rc = msm_gpios_request_enable(timpani_reset_gpio_cfg, ARRAY_SIZE(timpani_reset_gpio_cfg)); if (rc < 0) { printk(KERN_ERR "%s: msm_gpios_request_enable failed (%d)\n", __func__, rc); } return rc; } static unsigned int msm_timpani_setup_power(void) { int rc; rc = config_timpani_reset(); if (rc < 0) goto out; rc = vreg_enable(vreg_marimba_1); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d\n", __func__, rc); goto out; } rc = vreg_enable(vreg_marimba_2); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d\n", __func__, rc); goto fail_disable_vreg_marimba_1; } rc = gpio_direction_output(TIMPANI_RESET_GPIO, 1); if (rc < 0) { printk(KERN_ERR "%s: gpio_direction_output failed (%d)\n", __func__, rc); msm_gpios_free(timpani_reset_gpio_cfg, ARRAY_SIZE(timpani_reset_gpio_cfg)); vreg_disable(vreg_marimba_2); } else goto out; fail_disable_vreg_marimba_1: vreg_disable(vreg_marimba_1); out: return rc; }; static void msm_timpani_shutdown_power(void) { int rc; rc = vreg_disable(vreg_marimba_1); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } rc = vreg_disable(vreg_marimba_2); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } rc = gpio_direction_output(TIMPANI_RESET_GPIO, 0); if (rc < 0) { printk(KERN_ERR "%s: gpio_direction_output failed (%d)\n", __func__, rc); } msm_gpios_free(timpani_reset_gpio_cfg, ARRAY_SIZE(timpani_reset_gpio_cfg)); }; static unsigned int msm_bahama_core_config(int type) { int rc = 0; if (type == BAHAMA_ID) { int i; struct marimba config = { .mod_id = SLAVE_ID_BAHAMA }; const struct bahama_config_register v20_init[] = { /* reg, value, mask */ { 0xF4, 0x84, 0xFF }, /* AREG */ { 0xF0, 0x04, 0xFF } /* DREG */ }; if (read_bahama_ver() == VER_2_0) { for (i = 0; i < ARRAY_SIZE(v20_init); i++) { u8 value = v20_init[i].value; rc = marimba_write_bit_mask(&config, v20_init[i].reg, &value, sizeof(v20_init[i].value), v20_init[i].mask); if (rc < 0) { printk(KERN_ERR "%s: reg %d write failed: %d\n", __func__, v20_init[i].reg, rc); return rc; } printk(KERN_INFO "%s: reg 0x%02x value 0x%02x" " mask 0x%02x\n", __func__, v20_init[i].reg, v20_init[i].value, v20_init[i].mask); } } } printk(KERN_INFO "core type: %d\n", type); return rc; } static unsigned int msm_bahama_setup_power(void) { int rc; rc = vreg_enable(vreg_marimba_3); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d\n", __func__, rc); } return rc; }; static unsigned int msm_bahama_shutdown_power(int value) { int rc = 0; if (value != BAHAMA_ID) { rc = vreg_disable(vreg_marimba_3); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } } return rc; }; static struct msm_gpio marimba_svlte_config_clock[] = { { GPIO_CFG(34, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MARIMBA_SVLTE_CLOCK_ENABLE" }, }; static unsigned int msm_marimba_gpio_config_svlte(int gpio_cfg_marimba) { if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { if (gpio_cfg_marimba) gpio_set_value(GPIO_PIN (marimba_svlte_config_clock->gpio_cfg), 1); else gpio_set_value(GPIO_PIN (marimba_svlte_config_clock->gpio_cfg), 0); } return 0; }; static unsigned int msm_marimba_setup_power(void) { int rc; rc = vreg_enable(vreg_marimba_1); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); goto out; } rc = vreg_enable(vreg_marimba_2); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); goto out; } if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = msm_gpios_request_enable(marimba_svlte_config_clock, ARRAY_SIZE(marimba_svlte_config_clock)); if (rc < 0) { printk(KERN_ERR "%s: msm_gpios_request_enable failed (%d)\n", __func__, rc); return rc; } rc = gpio_direction_output(GPIO_PIN (marimba_svlte_config_clock->gpio_cfg), 0); if (rc < 0) { printk(KERN_ERR "%s: gpio_direction_output failed (%d)\n", __func__, rc); return rc; } } out: return rc; }; static void msm_marimba_shutdown_power(void) { int rc; rc = vreg_disable(vreg_marimba_1); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } rc = vreg_disable(vreg_marimba_2); if (rc) { printk(KERN_ERR "%s: return val: %d \n", __func__, rc); } }; static int bahama_present(void) { int id; switch (id = adie_get_detected_connectivity_type()) { case BAHAMA_ID: return 1; case MARIMBA_ID: return 0; case TIMPANI_ID: default: printk(KERN_ERR "%s: unexpected adie connectivity type: %d\n", __func__, id); return -ENODEV; } } /* +++ AlbertYCFang, 2011.06.13, FM +++ */ #ifdef CONFIG_FIH_FM_LNA //FB0 add LNA in FM, so we need to control FM_LNA_EN and GPS_FM_LNA_2V8_EN to turn on/off FM LNA. #define FM_LNA_EN 78 static struct msm_gpio fm_gpio_table[] = { //{ GPIO_CFG(GPS_FM_LNA_2V8_EN, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "gps_fm_lna_2v8_en" }, { GPIO_CFG(FM_LNA_EN, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "fm_lna_en" }, }; #endif /* --- AlbertYCFang, 2011.06.13, FM --- */ struct vreg *fm_regulator; struct vreg *fm_gp16; static int fm_radio_setup(struct marimba_fm_platform_data *pdata) { int rc; uint32_t irqcfg; const char *id = "FMPW"; int bahama_not_marimba = bahama_present(); /* +++ AlbertYCFang, 2011.06.13, FM +++ */ fm_gp16 = vreg_get(NULL, "gp16"); if (IS_ERR(fm_gp16)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(fm_gp16)); return -1; } rc = vreg_enable(fm_gp16); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); return rc; } /* --- AlbertYCFang, 2011.06.13, FM --- */ if (bahama_not_marimba == -1) { printk(KERN_WARNING "%s: bahama_present: %d\n", __func__, bahama_not_marimba); return -ENODEV; } if (bahama_not_marimba) fm_regulator = vreg_get(NULL, "s3"); else fm_regulator = vreg_get(NULL, "s2"); if (IS_ERR(fm_regulator)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(fm_regulator)); return -1; } if (!bahama_not_marimba) { rc = pmapp_vreg_level_vote(id, PMAPP_VREG_S2, 1300); if (rc < 0) { printk(KERN_ERR "%s: voltage level vote failed (%d)\n", __func__, rc); return rc; } } rc = vreg_enable(fm_regulator); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d\n", __func__, rc); return rc; } /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_ON); } else { /* +++ AlbertYCFang, 2011.06.13, FM +++ */ rc = pmapp_clock_vote(id, /*PMAPP_CLOCK_ID_DO*/QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_ON); /* --- AlbertYCFang, 2011.06.13, FM --- */ } if (rc < 0) { printk(KERN_ERR "%s: clock vote failed (%d)\n", __func__, rc); goto fm_clock_vote_fail; } /*Request the Clock Using GPIO34/AP2MDM_MRMBCK_EN in case of svlte*/ if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = marimba_gpio_config(1); if (rc < 0) printk(KERN_ERR "%s: clock enable for svlte : %d\n", __func__, rc); } irqcfg = GPIO_CFG(147, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); rc = gpio_tlmm_config(irqcfg, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, irqcfg, rc); rc = -EIO; goto fm_gpio_config_fail; } /* +++ AlbertYCFang, 2011.06.13, FM +++ */ #ifdef CONFIG_FIH_FM_LNA //FB0 add LNA in FM, so we need to control FM_LNA_EN and GPS_FM_LNA_2V8_EN to turn LNA. printk(KERN_INFO "%s : config and enable FM LNA control.\n", __func__); rc = msm_gpios_enable(fm_gpio_table, ARRAY_SIZE(fm_gpio_table)); if (rc<0) goto fm_gpio_config_fail; /* FB0.B-396 */ rc = enable_gps_fm_lna(true); if (rc<0) goto fm_gpio_config_fail; gpio_set_value(FM_LNA_EN, 1); #endif /* --- AlbertYCFang, 2011.06.13, FM --- */ return 0; fm_gpio_config_fail: /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_OFF); } else { pmapp_clock_vote(id, /*PMAPP_CLOCK_ID_DO*/QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_OFF); } fm_clock_vote_fail: vreg_disable(fm_regulator); vreg_disable(fm_gp16); return rc; }; static void fm_radio_shutdown(struct marimba_fm_platform_data *pdata) { int rc; const char *id = "FMPW"; uint32_t irqcfg = GPIO_CFG(147, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA); int bahama_not_marimba = bahama_present(); /* +++ AlbertYCFang, 2011.06.13, FM +++ */ #ifdef CONFIG_FIH_FM_LNA /* FB0 add LNA in FM, so we need to control FM_LNA_EN and GPS_FM_LNA_2V8_EN to turn LNA. FB0.B-396 */ enable_gps_fm_lna(false); gpio_set_value(FM_LNA_EN, 0); #endif /* --- AlbertYCFang, 2011.06.13, FM --- */ if (bahama_not_marimba == -1) { printk(KERN_WARNING "%s: bahama_present: %d\n", __func__, bahama_not_marimba); return; } rc = gpio_tlmm_config(irqcfg, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, irqcfg, rc); } if (fm_regulator != NULL) { rc = vreg_disable(fm_regulator); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } fm_regulator = NULL; } /* +++ AlbertYCFang, 2011.06.13, FM +++ */ rc = vreg_disable(fm_gp16); if (rc) { printk(KERN_ERR "%s: return val: %d \n", __func__, rc); } /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_OFF); } else { rc = pmapp_clock_vote(id, /*PMAPP_CLOCK_ID_DO*/QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_OFF); } /* --- AlbertYCFang, 2011.06.13, FM --- */ if (rc < 0) printk(KERN_ERR "%s: clock_vote return val: %d\n", __func__, rc); /*Disable the Clock Using GPIO34/AP2MDM_MRMBCK_EN in case of svlte*/ if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = marimba_gpio_config(0); if (rc < 0) printk(KERN_ERR "%s: clock disable for svlte : %d\n", __func__, rc); } if (!bahama_not_marimba) { rc = pmapp_vreg_level_vote(id, PMAPP_VREG_S2, 0); if (rc < 0) printk(KERN_ERR "%s: vreg level vote return val: %d\n", __func__, rc); } } static struct marimba_fm_platform_data marimba_fm_pdata = { .fm_setup = fm_radio_setup, .fm_shutdown = fm_radio_shutdown, .irq = MSM_GPIO_TO_INT(147), .vreg_s2 = NULL, .vreg_xo_out = NULL, }; /* Slave id address for FM/CDC/QMEMBIST * Values can be programmed using Marimba slave id 0 * should there be a conflict with other I2C devices * */ #define MARIMBA_SLAVE_ID_FM_ADDR 0x2A #define MARIMBA_SLAVE_ID_CDC_ADDR 0x77 #define MARIMBA_SLAVE_ID_QMEMBIST_ADDR 0X66 #define BAHAMA_SLAVE_ID_FM_ADDR 0x2A #define BAHAMA_SLAVE_ID_QMEMBIST_ADDR 0x7B static const char *tsadc_id = "MADC"; static const char *vregs_tsadc_name[] = { "gp12", "s2", }; static struct vreg *vregs_tsadc[ARRAY_SIZE(vregs_tsadc_name)]; static const char *vregs_timpani_tsadc_name[] = { "s3", "gp12", "gp16" }; static struct vreg *vregs_timpani_tsadc[ARRAY_SIZE(vregs_timpani_tsadc_name)]; static int marimba_tsadc_power(int vreg_on) { int i, rc = 0; int tsadc_adie_type = adie_get_detected_codec_type(); if (tsadc_adie_type == TIMPANI_ID) { for (i = 0; i < ARRAY_SIZE(vregs_timpani_tsadc_name); i++) { if (!vregs_timpani_tsadc[i]) { pr_err("%s: vreg_get %s failed(%d)\n", __func__, vregs_timpani_tsadc_name[i], rc); goto vreg_fail; } rc = vreg_on ? vreg_enable(vregs_timpani_tsadc[i]) : vreg_disable(vregs_timpani_tsadc[i]); if (rc < 0) { pr_err("%s: vreg %s %s failed(%d)\n", __func__, vregs_timpani_tsadc_name[i], vreg_on ? "enable" : "disable", rc); goto vreg_fail; } } /* Vote for D0 and D1 buffer */ /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(tsadc_id, PMAPP_CLOCK_ID_DO, vreg_on ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); } else { rc = pmapp_clock_vote(tsadc_id, /*PMAPP_CLOCK_ID_D1*/QTR8x00_WCN_CLK, vreg_on ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); } if (rc) { pr_err("%s: unable to %svote for d1 clk\n", __func__, vreg_on ? "" : "de-"); goto do_vote_fail; } rc = pmapp_clock_vote(tsadc_id, PMAPP_CLOCK_ID_DO, vreg_on ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); if (rc) { pr_err("%s: unable to %svote for d1 clk\n", __func__, vreg_on ? "" : "de-"); goto do_vote_fail; } } else if (tsadc_adie_type == MARIMBA_ID) { for (i = 0; i < ARRAY_SIZE(vregs_tsadc_name); i++) { if (!vregs_tsadc[i]) { pr_err("%s: vreg_get %s failed (%d)\n", __func__, vregs_tsadc_name[i], rc); goto vreg_fail; } rc = vreg_on ? vreg_enable(vregs_tsadc[i]) : vreg_disable(vregs_tsadc[i]); if (rc < 0) { pr_err("%s: vreg %s %s failed (%d)\n", __func__, vregs_tsadc_name[i], vreg_on ? "enable" : "disable", rc); goto vreg_fail; } } /* If marimba vote for DO buffer */ rc = pmapp_clock_vote(tsadc_id, PMAPP_CLOCK_ID_DO, vreg_on ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); if (rc) { pr_err("%s: unable to %svote for d0 clk\n", __func__, vreg_on ? "" : "de-"); goto do_vote_fail; } } else { pr_err("%s:Adie %d not supported\n", __func__, tsadc_adie_type); return -ENODEV; } msleep(5); /* ensure power is stable */ return 0; do_vote_fail: vreg_fail: while (i) { if (vreg_on) { if (tsadc_adie_type == TIMPANI_ID) vreg_disable(vregs_timpani_tsadc[--i]); else if (tsadc_adie_type == MARIMBA_ID) vreg_disable(vregs_tsadc[--i]); } else { if (tsadc_adie_type == TIMPANI_ID) vreg_enable(vregs_timpani_tsadc[--i]); else if (tsadc_adie_type == MARIMBA_ID) vreg_enable(vregs_tsadc[--i]); } } return rc; } static int marimba_tsadc_vote(int vote_on) { int rc = 0; if (adie_get_detected_codec_type() == MARIMBA_ID) { int level = vote_on ? 1300 : 0; rc = pmapp_vreg_level_vote(tsadc_id, PMAPP_VREG_S2, level); if (rc < 0) pr_err("%s: vreg level %s failed (%d)\n", __func__, vote_on ? "on" : "off", rc); } return rc; } static int marimba_tsadc_init(void) { int i, rc = 0; int tsadc_adie_type = adie_get_detected_codec_type(); if (tsadc_adie_type == TIMPANI_ID) { for (i = 0; i < ARRAY_SIZE(vregs_timpani_tsadc_name); i++) { vregs_timpani_tsadc[i] = vreg_get(NULL, vregs_timpani_tsadc_name[i]); if (IS_ERR(vregs_timpani_tsadc[i])) { pr_err("%s: vreg get %s failed (%ld)\n", __func__, vregs_timpani_tsadc_name[i], PTR_ERR(vregs_timpani_tsadc[i])); rc = PTR_ERR(vregs_timpani_tsadc[i]); goto vreg_get_fail; } } } else if (tsadc_adie_type == MARIMBA_ID) { for (i = 0; i < ARRAY_SIZE(vregs_tsadc_name); i++) { vregs_tsadc[i] = vreg_get(NULL, vregs_tsadc_name[i]); if (IS_ERR(vregs_tsadc[i])) { pr_err("%s: vreg get %s failed (%ld)\n", __func__, vregs_tsadc_name[i], PTR_ERR(vregs_tsadc[i])); rc = PTR_ERR(vregs_tsadc[i]); goto vreg_get_fail; } } } else { pr_err("%s:Adie %d not supported\n", __func__, tsadc_adie_type); return -ENODEV; } return 0; vreg_get_fail: while (i) { if (tsadc_adie_type == TIMPANI_ID) vreg_put(vregs_timpani_tsadc[--i]); else if (tsadc_adie_type == MARIMBA_ID) vreg_put(vregs_tsadc[--i]); } return rc; } static int marimba_tsadc_exit(void) { int i, rc = 0; int tsadc_adie_type = adie_get_detected_codec_type(); if (tsadc_adie_type == TIMPANI_ID) { for (i = 0; i < ARRAY_SIZE(vregs_timpani_tsadc_name); i++) { if (vregs_tsadc[i]) vreg_put(vregs_timpani_tsadc[i]); } } else if (tsadc_adie_type == MARIMBA_ID) { for (i = 0; i < ARRAY_SIZE(vregs_tsadc_name); i++) { if (vregs_tsadc[i]) vreg_put(vregs_tsadc[i]); } rc = pmapp_vreg_level_vote(tsadc_id, PMAPP_VREG_S2, 0); if (rc < 0) pr_err("%s: vreg level off failed (%d)\n", __func__, rc); } else { pr_err("%s:Adie %d not supported\n", __func__, tsadc_adie_type); rc = -ENODEV; } return rc; } static struct msm_ts_platform_data msm_ts_data = { .min_x = 0, .max_x = 4096, .min_y = 0, .max_y = 4096, .min_press = 0, .max_press = 255, .inv_x = 4096, .inv_y = 4096, .can_wakeup = false, }; static struct marimba_tsadc_platform_data marimba_tsadc_pdata = { .marimba_tsadc_power = marimba_tsadc_power, .init = marimba_tsadc_init, .exit = marimba_tsadc_exit, .level_vote = marimba_tsadc_vote, .tsadc_prechg_en = true, .can_wakeup = false, .setup = { .pen_irq_en = true, .tsadc_en = true, }, .params2 = { .input_clk_khz = 2400, .sample_prd = TSADC_CLK_3, }, .params3 = { .prechg_time_nsecs = 6400, .stable_time_nsecs = 6400, .tsadc_test_mode = 0, }, .tssc_data = &msm_ts_data, }; static struct vreg *vreg_codec_s4; static int msm_marimba_codec_power(int vreg_on) { int rc = 0; if (!vreg_codec_s4) { vreg_codec_s4 = vreg_get(NULL, "s4"); if (IS_ERR(vreg_codec_s4)) { printk(KERN_ERR "%s: vreg_get() failed (%ld)\n", __func__, PTR_ERR(vreg_codec_s4)); rc = PTR_ERR(vreg_codec_s4); goto vreg_codec_s4_fail; } } if (vreg_on) { rc = vreg_enable(vreg_codec_s4); if (rc) printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); goto vreg_codec_s4_fail; } else { rc = vreg_disable(vreg_codec_s4); if (rc) printk(KERN_ERR "%s: vreg_disable() = %d \n", __func__, rc); goto vreg_codec_s4_fail; } vreg_codec_s4_fail: return rc; } static struct marimba_codec_platform_data mariba_codec_pdata = { .marimba_codec_power = msm_marimba_codec_power, #ifdef CONFIG_MARIMBA_CODEC .snddev_profile_init = msm_snddev_init, #endif }; static struct marimba_platform_data marimba_pdata = { .slave_id[MARIMBA_SLAVE_ID_FM] = MARIMBA_SLAVE_ID_FM_ADDR, .slave_id[MARIMBA_SLAVE_ID_CDC] = MARIMBA_SLAVE_ID_CDC_ADDR, .slave_id[MARIMBA_SLAVE_ID_QMEMBIST] = MARIMBA_SLAVE_ID_QMEMBIST_ADDR, .slave_id[SLAVE_ID_BAHAMA_FM] = BAHAMA_SLAVE_ID_FM_ADDR, .slave_id[SLAVE_ID_BAHAMA_QMEMBIST] = BAHAMA_SLAVE_ID_QMEMBIST_ADDR, .marimba_setup = msm_marimba_setup_power, .marimba_shutdown = msm_marimba_shutdown_power, .bahama_setup = msm_bahama_setup_power, .bahama_shutdown = msm_bahama_shutdown_power, .marimba_gpio_config = msm_marimba_gpio_config_svlte, .bahama_core_config = msm_bahama_core_config, .fm = &marimba_fm_pdata, .codec = &mariba_codec_pdata, }; static void __init msm7x30_init_marimba(void) { int rc; vreg_marimba_1 = vreg_get(NULL, "s3"); if (IS_ERR(vreg_marimba_1)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_marimba_1)); return; } rc = vreg_set_level(vreg_marimba_1, 1800); vreg_marimba_2 = vreg_get(NULL, "gp16"); if (IS_ERR(vreg_marimba_1)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_marimba_1)); return; } rc = vreg_set_level(vreg_marimba_2, 1200); vreg_marimba_3 = vreg_get(NULL, "usb2"); if (IS_ERR(vreg_marimba_3)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_marimba_3)); return; } rc = vreg_set_level(vreg_marimba_3, 1800); } static struct marimba_codec_platform_data timpani_codec_pdata = { .marimba_codec_power = msm_marimba_codec_power, #ifdef CONFIG_TIMPANI_CODEC .snddev_profile_init = msm_snddev_init_timpani, #endif }; static struct marimba_platform_data timpani_pdata = { .slave_id[MARIMBA_SLAVE_ID_CDC] = MARIMBA_SLAVE_ID_CDC_ADDR, .slave_id[MARIMBA_SLAVE_ID_QMEMBIST] = MARIMBA_SLAVE_ID_QMEMBIST_ADDR, .marimba_setup = msm_timpani_setup_power, .marimba_shutdown = msm_timpani_shutdown_power, .codec = &timpani_codec_pdata, .tsadc = &marimba_tsadc_pdata, }; #define TIMPANI_I2C_SLAVE_ADDR 0xD static struct i2c_board_info msm_i2c_gsbi7_timpani_info[] = { { I2C_BOARD_INFO("timpani", TIMPANI_I2C_SLAVE_ADDR), .platform_data = &timpani_pdata, }, }; #ifdef CONFIG_MSM7KV2_AUDIO static struct resource msm_aictl_resources[] = { { .name = "aictl", .start = 0xa5000100, .end = 0xa5000100, .flags = IORESOURCE_MEM, } }; static struct resource msm_mi2s_resources[] = { { .name = "hdmi", .start = 0xac900000, .end = 0xac900038, .flags = IORESOURCE_MEM, }, { .name = "codec_rx", .start = 0xac940040, .end = 0xac940078, .flags = IORESOURCE_MEM, }, { .name = "codec_tx", .start = 0xac980080, .end = 0xac9800B8, .flags = IORESOURCE_MEM, } }; static struct msm_lpa_platform_data lpa_pdata = { .obuf_hlb_size = 0x2BFF8, .dsp_proc_id = 0, .app_proc_id = 2, .nosb_config = { .llb_min_addr = 0, .llb_max_addr = 0x3ff8, .sb_min_addr = 0, .sb_max_addr = 0, }, .sb_config = { .llb_min_addr = 0, .llb_max_addr = 0x37f8, .sb_min_addr = 0x3800, .sb_max_addr = 0x3ff8, } }; static struct resource msm_lpa_resources[] = { { .name = "lpa", .start = 0xa5000000, .end = 0xa50000a0, .flags = IORESOURCE_MEM, } }; static struct resource msm_aux_pcm_resources[] = { { .name = "aux_codec_reg_addr", .start = 0xac9c00c0, .end = 0xac9c00c8, .flags = IORESOURCE_MEM, }, { .name = "aux_pcm_dout", .start = 138, .end = 138, .flags = IORESOURCE_IO, }, { .name = "aux_pcm_din", .start = 139, .end = 139, .flags = IORESOURCE_IO, }, { .name = "aux_pcm_syncout", .start = 140, .end = 140, .flags = IORESOURCE_IO, }, { .name = "aux_pcm_clkin_a", .start = 141, .end = 141, .flags = IORESOURCE_IO, }, }; static struct platform_device msm_aux_pcm_device = { .name = "msm_aux_pcm", .id = 0, .num_resources = ARRAY_SIZE(msm_aux_pcm_resources), .resource = msm_aux_pcm_resources, }; struct platform_device msm_aictl_device = { .name = "audio_interct", .id = 0, .num_resources = ARRAY_SIZE(msm_aictl_resources), .resource = msm_aictl_resources, }; struct platform_device msm_mi2s_device = { .name = "mi2s", .id = 0, .num_resources = ARRAY_SIZE(msm_mi2s_resources), .resource = msm_mi2s_resources, }; struct platform_device msm_lpa_device = { .name = "lpa", .id = 0, .num_resources = ARRAY_SIZE(msm_lpa_resources), .resource = msm_lpa_resources, .dev = { .platform_data = &lpa_pdata, }, }; #endif /* CONFIG_MSM7KV2_AUDIO */ #define DEC0_FORMAT ((1<<MSM_ADSP_CODEC_MP3)| \ (1<<MSM_ADSP_CODEC_AAC)|(1<<MSM_ADSP_CODEC_WMA)| \ (1<<MSM_ADSP_CODEC_WMAPRO)|(1<<MSM_ADSP_CODEC_AMRWB)| \ (1<<MSM_ADSP_CODEC_AMRNB)|(1<<MSM_ADSP_CODEC_WAV)| \ (1<<MSM_ADSP_CODEC_ADPCM)|(1<<MSM_ADSP_CODEC_YADPCM)| \ (1<<MSM_ADSP_CODEC_EVRC)|(1<<MSM_ADSP_CODEC_QCELP)) #define DEC1_FORMAT ((1<<MSM_ADSP_CODEC_MP3)| \ (1<<MSM_ADSP_CODEC_AAC)|(1<<MSM_ADSP_CODEC_WMA)| \ (1<<MSM_ADSP_CODEC_WMAPRO)|(1<<MSM_ADSP_CODEC_AMRWB)| \ (1<<MSM_ADSP_CODEC_AMRNB)|(1<<MSM_ADSP_CODEC_WAV)| \ (1<<MSM_ADSP_CODEC_ADPCM)|(1<<MSM_ADSP_CODEC_YADPCM)| \ (1<<MSM_ADSP_CODEC_EVRC)|(1<<MSM_ADSP_CODEC_QCELP)) #define DEC2_FORMAT ((1<<MSM_ADSP_CODEC_MP3)| \ (1<<MSM_ADSP_CODEC_AAC)|(1<<MSM_ADSP_CODEC_WMA)| \ (1<<MSM_ADSP_CODEC_WMAPRO)|(1<<MSM_ADSP_CODEC_AMRWB)| \ (1<<MSM_ADSP_CODEC_AMRNB)|(1<<MSM_ADSP_CODEC_WAV)| \ (1<<MSM_ADSP_CODEC_ADPCM)|(1<<MSM_ADSP_CODEC_YADPCM)| \ (1<<MSM_ADSP_CODEC_EVRC)|(1<<MSM_ADSP_CODEC_QCELP)) #define DEC3_FORMAT ((1<<MSM_ADSP_CODEC_MP3)| \ (1<<MSM_ADSP_CODEC_AAC)|(1<<MSM_ADSP_CODEC_WMA)| \ (1<<MSM_ADSP_CODEC_WMAPRO)|(1<<MSM_ADSP_CODEC_AMRWB)| \ (1<<MSM_ADSP_CODEC_AMRNB)|(1<<MSM_ADSP_CODEC_WAV)| \ (1<<MSM_ADSP_CODEC_ADPCM)|(1<<MSM_ADSP_CODEC_YADPCM)| \ (1<<MSM_ADSP_CODEC_EVRC)|(1<<MSM_ADSP_CODEC_QCELP)) #define DEC4_FORMAT (1<<MSM_ADSP_CODEC_MIDI) static unsigned int dec_concurrency_table[] = { /* Audio LP */ 0, (DEC3_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_MODE_LP)| (1<<MSM_ADSP_OP_DM)), /* Concurrency 1 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 2 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 3 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 4 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 5 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 6 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), }; #define DEC_INFO(name, queueid, decid, nr_codec) { .module_name = name, \ .module_queueid = queueid, .module_decid = decid, \ .nr_codec_support = nr_codec} #define DEC_INSTANCE(max_instance_same, max_instance_diff) { \ .max_instances_same_dec = max_instance_same, \ .max_instances_diff_dec = max_instance_diff} static struct msm_adspdec_info dec_info_list[] = { DEC_INFO("AUDPLAY4TASK", 17, 4, 1), /* AudPlay4BitStreamCtrlQueue */ DEC_INFO("AUDPLAY3TASK", 16, 3, 11), /* AudPlay3BitStreamCtrlQueue */ DEC_INFO("AUDPLAY2TASK", 15, 2, 11), /* AudPlay2BitStreamCtrlQueue */ DEC_INFO("AUDPLAY1TASK", 14, 1, 11), /* AudPlay1BitStreamCtrlQueue */ DEC_INFO("AUDPLAY0TASK", 13, 0, 11), /* AudPlay0BitStreamCtrlQueue */ }; static struct dec_instance_table dec_instance_list[][MSM_MAX_DEC_CNT] = { /* Non Turbo Mode */ { DEC_INSTANCE(4, 3), /* WAV */ DEC_INSTANCE(4, 3), /* ADPCM */ DEC_INSTANCE(4, 2), /* MP3 */ DEC_INSTANCE(0, 0), /* Real Audio */ DEC_INSTANCE(4, 2), /* WMA */ DEC_INSTANCE(3, 2), /* AAC */ DEC_INSTANCE(0, 0), /* Reserved */ DEC_INSTANCE(0, 0), /* MIDI */ DEC_INSTANCE(4, 3), /* YADPCM */ DEC_INSTANCE(4, 3), /* QCELP */ DEC_INSTANCE(4, 3), /* AMRNB */ DEC_INSTANCE(1, 1), /* AMRWB/WB+ */ DEC_INSTANCE(4, 3), /* EVRC */ DEC_INSTANCE(1, 1), /* WMAPRO */ }, /* Turbo Mode */ { DEC_INSTANCE(4, 3), /* WAV */ DEC_INSTANCE(4, 3), /* ADPCM */ DEC_INSTANCE(4, 3), /* MP3 */ DEC_INSTANCE(0, 0), /* Real Audio */ DEC_INSTANCE(4, 3), /* WMA */ DEC_INSTANCE(4, 3), /* AAC */ DEC_INSTANCE(0, 0), /* Reserved */ DEC_INSTANCE(0, 0), /* MIDI */ DEC_INSTANCE(4, 3), /* YADPCM */ DEC_INSTANCE(4, 3), /* QCELP */ DEC_INSTANCE(4, 3), /* AMRNB */ DEC_INSTANCE(2, 3), /* AMRWB/WB+ */ DEC_INSTANCE(4, 3), /* EVRC */ DEC_INSTANCE(1, 2), /* WMAPRO */ }, }; static struct msm_adspdec_database msm_device_adspdec_database = { .num_dec = ARRAY_SIZE(dec_info_list), .num_concurrency_support = (ARRAY_SIZE(dec_concurrency_table) / \ ARRAY_SIZE(dec_info_list)), .dec_concurrency_table = dec_concurrency_table, .dec_info_list = dec_info_list, .dec_instance_list = &dec_instance_list[0][0], }; static struct platform_device msm_device_adspdec = { .name = "msm_adspdec", .id = -1, .dev = { .platform_data = &msm_device_adspdec_database }, }; /* Div2-SW2-BSP-FBX-OW { */ #ifdef CONFIG_SMC91X static struct resource smc91x_resources[] = { [0] = { .start = 0x8A000300, .end = 0x8A0003ff, .flags = IORESOURCE_MEM, }, [1] = { .start = MSM_GPIO_TO_INT(156), .end = MSM_GPIO_TO_INT(156), .flags = IORESOURCE_IRQ, }, }; static struct platform_device smc91x_device = { .name = "smc91x", .id = 0, .num_resources = ARRAY_SIZE(smc91x_resources), .resource = smc91x_resources, }; #endif #ifdef CONFIG_SMSC911X static struct smsc911x_platform_config smsc911x_config = { .phy_interface = PHY_INTERFACE_MODE_MII, .irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW, .irq_type = SMSC911X_IRQ_TYPE_PUSH_PULL, .flags = SMSC911X_USE_32BIT, }; static struct resource smsc911x_resources[] = { [0] = { .start = 0x8D000000, .end = 0x8D000100, .flags = IORESOURCE_MEM, }, [1] = { .start = MSM_GPIO_TO_INT(88), .end = MSM_GPIO_TO_INT(88), .flags = IORESOURCE_IRQ, }, }; static struct platform_device smsc911x_device = { .name = "smsc911x", .id = -1, .num_resources = ARRAY_SIZE(smsc911x_resources), .resource = smsc911x_resources, .dev = { .platform_data = &smsc911x_config, }, }; static struct msm_gpio smsc911x_gpios[] = { { GPIO_CFG(172, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr6" }, { GPIO_CFG(173, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr5" }, { GPIO_CFG(174, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr4" }, { GPIO_CFG(175, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr3" }, { GPIO_CFG(176, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr2" }, { GPIO_CFG(177, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr1" }, { GPIO_CFG(178, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr0" }, { GPIO_CFG(88, 2, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "smsc911x_irq" }, }; static void msm7x30_cfg_smsc911x(void) { int rc; rc = msm_gpios_request_enable(smsc911x_gpios, ARRAY_SIZE(smsc911x_gpios)); if (rc) pr_err("%s: unable to enable gpios\n", __func__); } #endif /* } Div2-SW2-BSP-FBX-OW */ #ifdef CONFIG_USB_FUNCTION static struct usb_mass_storage_platform_data usb_mass_storage_pdata = { .nluns = 0x02, .buf_size = 16384, .vendor = "GOOGLE", .product = "Mass storage", .release = 0xffff, }; static struct platform_device mass_storage_device = { .name = "usb_mass_storage", .id = -1, .dev = { .platform_data = &usb_mass_storage_pdata, }, }; #endif #ifdef CONFIG_USB_ANDROID static char *usb_functions_default[] = { "diag", "modem", "nmea", "rmnet", "usb_mass_storage", }; static char *usb_functions_default_adb[] = { "diag", "adb", "modem", "nmea", "rmnet", "usb_mass_storage", }; static char *fusion_usb_functions_default[] = { "diag", "nmea", "usb_mass_storage", }; static char *fusion_usb_functions_default_adb[] = { "diag", "adb", "nmea", "usb_mass_storage", }; static char *usb_functions_rndis[] = { "rndis", }; static char *usb_functions_rndis_adb[] = { "rndis", "adb", }; static char *usb_functions_rndis_diag[] = { "rndis", "diag", }; static char *usb_functions_rndis_adb_diag[] = { "rndis", "diag", "adb", }; /* FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid { */ #ifdef CONFIG_FIH_FXX static char *usb_functions_c000[] = { "nmea", "modem", "adb", "diag", "usb_mass_storage", }; static char *usb_functions_c001[] = { "modem", "adb", "usb_mass_storage", }; static char *usb_functions_c002[] = { "diag", }; static char *usb_functions_c003[] = { "modem", }; static char *usb_functions_c004[] = { "usb_mass_storage", }; static char *usb_functions_c007[] = { "rndis", "adb", "diag", }; static char *usb_functions_c008[] = { "rndis", "adb", }; #ifdef CONFIG_USB_ANDROID_ACCESSORY static char *usb_functions_accessory[] = { "accessory" }; static char *usb_functions_accessory_adb[] = { "accessory", "adb" }; #endif // CONFIG_USB_ANDROID_ACCESSORY static char *usb_functions_all[] = { #ifdef CONFIG_USB_ANDROID_RNDIS "rndis", #endif #ifdef CONFIG_USB_ANDROID_ACCESSORY "accessory", #endif // CONFIG_USB_ANDROID_ACCESSORY "usb_mass_storage", #ifdef CONFIG_USB_ANDROID_DIAG "diag", #endif "adb", #ifdef CONFIG_USB_F_SERIAL "modem", "nmea", #endif #ifdef CONFIG_USB_ANDROID_RMNET "rmnet", #endif #ifdef CONFIG_USB_ANDROID_ACM "acm", #endif }; #else // CONFIG_FIH_FXX static char *usb_functions_all[] = { #ifdef CONFIG_USB_ANDROID_RNDIS "rndis", #endif #ifdef CONFIG_USB_ANDROID_DIAG "diag", #endif "adb", #ifdef CONFIG_USB_F_SERIAL "modem", "nmea", #endif #ifdef CONFIG_USB_ANDROID_RMNET "rmnet", #endif "usb_mass_storage", #ifdef CONFIG_USB_ANDROID_ACM "acm", #endif }; #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid */ static struct android_usb_product usb_products[] = { /* FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid { */ #ifdef CONFIG_FIH_FXX { /* RNDIS + ADB */ .product_id = 0xC008, .num_functions = ARRAY_SIZE(usb_functions_c008), .functions = usb_functions_c008, }, { /* RNDIS + ADB + DIAG */ .product_id = 0xC007, .num_functions = ARRAY_SIZE(usb_functions_c007), .functions = usb_functions_c007, }, { /* USB_MASS_STORAGE */ .product_id = 0xC004, .num_functions = ARRAY_SIZE(usb_functions_c004), .functions = usb_functions_c004, }, { /* MODEM */ .product_id = 0xC003, .num_functions = ARRAY_SIZE(usb_functions_c003), .functions = usb_functions_c003, }, { /* DIAG */ .product_id = 0xC002, .num_functions = ARRAY_SIZE(usb_functions_c002), .functions = usb_functions_c002, }, { /* MODEM + ADB + USB_MASS_STORAGE */ .product_id = 0xC001, .num_functions = ARRAY_SIZE(usb_functions_c001), .functions = usb_functions_c001, }, { /* NMEA + MODEM + ADB + DIAG + USB_MASS_STORAGE */ .product_id = 0xC000, .num_functions = ARRAY_SIZE(usb_functions_c000), .functions = usb_functions_c000, }, #ifdef CONFIG_USB_ANDROID_ACCESSORY { .vendor_id = USB_ACCESSORY_VENDOR_ID, .product_id = USB_ACCESSORY_PRODUCT_ID, .num_functions = ARRAY_SIZE(usb_functions_accessory), .functions = usb_functions_accessory, }, { .vendor_id = USB_ACCESSORY_VENDOR_ID, .product_id = USB_ACCESSORY_ADB_PRODUCT_ID, .num_functions = ARRAY_SIZE(usb_functions_accessory_adb), .functions = usb_functions_accessory_adb, }, #endif // CONFIG_USB_ANDROID_ACCESSORY #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid */ { .product_id = 0x9026, .num_functions = ARRAY_SIZE(usb_functions_default), .functions = usb_functions_default, }, { .product_id = 0x9025, .num_functions = ARRAY_SIZE(usb_functions_default_adb), .functions = usb_functions_default_adb, }, { /* RNDIS + DIAG */ .product_id = 0x902C, .num_functions = ARRAY_SIZE(usb_functions_rndis_diag), .functions = usb_functions_rndis_diag, }, { /* RNDIS + ADB + DIAG */ .product_id = 0x902D, .num_functions = ARRAY_SIZE(usb_functions_rndis_adb_diag), .functions = usb_functions_rndis_adb_diag, }, }; /* FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized { */ #ifdef CONFIG_FIH_FXX /*Huawei*/ static struct android_usb_product usb_products_12d1[] = { { .product_id = 0x1028, .num_functions = ARRAY_SIZE(usb_functions_c008), .functions = usb_functions_c008, }, { .product_id = 0x1027, .num_functions = ARRAY_SIZE(usb_functions_c007), .functions = usb_functions_c007, }, { .product_id = 0x1024, .num_functions = ARRAY_SIZE(usb_functions_c004), .functions = usb_functions_c004, }, { .product_id = 0x1023, .num_functions = ARRAY_SIZE(usb_functions_c003), .functions = usb_functions_c003, }, { .product_id = 0x1022, .num_functions = ARRAY_SIZE(usb_functions_c002), .functions = usb_functions_c002, }, { .product_id = 0x103c, .num_functions = ARRAY_SIZE(usb_functions_c001), .functions = usb_functions_c001, }, { .product_id = 0x1021, .num_functions = ARRAY_SIZE(usb_functions_c000), .functions = usb_functions_c000, }, }; #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized */ static struct android_usb_product fusion_usb_products[] = { { .product_id = 0x9028, .num_functions = ARRAY_SIZE(fusion_usb_functions_default), .functions = fusion_usb_functions_default, }, { .product_id = 0x9029, .num_functions = ARRAY_SIZE(fusion_usb_functions_default_adb), .functions = fusion_usb_functions_default_adb, }, { .product_id = 0xf00e, .num_functions = ARRAY_SIZE(usb_functions_rndis), .functions = usb_functions_rndis, }, { .product_id = 0x9024, .num_functions = ARRAY_SIZE(usb_functions_rndis_adb), .functions = usb_functions_rndis_adb, }, }; static struct usb_mass_storage_platform_data mass_storage_pdata = { /* FIHTDC, Div2-SW2-BSP, Penho, PCtool { */ #ifdef CONFIG_FIH_FXX .nluns = 2, #else // CONFIG_FIH_FXX .nluns = 1, #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, PCtool */ .vendor = "Qualcomm Incorporated", .product = "Mass storage", .release = 0x0100, .can_stall = 1, }; static struct platform_device usb_mass_storage_device = { .name = "usb_mass_storage", .id = -1, .dev = { .platform_data = &mass_storage_pdata, }, }; static struct usb_ether_platform_data rndis_pdata = { /* ethaddr is filled by board_serialno_setup */ .vendorID = 0x05C6, .vendorDescr = "Qualcomm Incorporated", }; static struct platform_device rndis_device = { .name = "rndis", .id = -1, .dev = { .platform_data = &rndis_pdata, }, }; static struct android_usb_platform_data android_usb_pdata = { /* FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid { */ #ifdef CONFIG_FIH_FXX .vendor_id = 0x0489, .product_id = 0xC001, #else // CONFIG_FIH_FXX .vendor_id = 0x05C6, .product_id = 0x9026, #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid */ .version = 0x0100, .product_name = "Qualcomm HSUSB Device", .manufacturer_name = "Qualcomm Incorporated", .num_products = ARRAY_SIZE(usb_products), .products = usb_products, .num_functions = ARRAY_SIZE(usb_functions_all), .functions = usb_functions_all, .serial_number = "1234567890ABCDEF", }; static struct platform_device android_usb_device = { .name = "android_usb", .id = -1, .dev = { .platform_data = &android_usb_pdata, }, }; static int __init board_serialno_setup(char *serialno) { int i; char *src = serialno; /* create a fake MAC address from our serial number. * first byte is 0x02 to signify locally administered. */ rndis_pdata.ethaddr[0] = 0x02; for (i = 0; *src; i++) { /* XOR the USB serial across the remaining bytes */ rndis_pdata.ethaddr[i % (ETH_ALEN - 1) + 1] ^= *src++; } android_usb_pdata.serial_number = serialno; return 1; } __setup("androidboot.serialno=", board_serialno_setup); #endif static struct msm_gpio optnav_config_data[] = { { GPIO_CFG(OPTNAV_CHIP_SELECT, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "optnav_chip_select" }, }; static void __iomem *virtual_optnav; static int optnav_gpio_setup(void) { int rc = -ENODEV; rc = msm_gpios_request_enable(optnav_config_data, ARRAY_SIZE(optnav_config_data)); /* Configure the FPGA for GPIOs */ virtual_optnav = ioremap(FPGA_OPTNAV_GPIO_ADDR, 0x4); if (!virtual_optnav) { pr_err("%s:Could not ioremap region\n", __func__); return -ENOMEM; } /* * Configure the FPGA to set GPIO 19 as * normal, active(enabled), output(MSM to SURF) */ writew(0x311E, virtual_optnav); return rc; } static void optnav_gpio_release(void) { msm_gpios_disable_free(optnav_config_data, ARRAY_SIZE(optnav_config_data)); iounmap(virtual_optnav); } static struct vreg *vreg_gp7; static struct vreg *vreg_gp4; static struct vreg *vreg_gp9; static struct vreg *vreg_usb3_3; static int optnav_enable(void) { int rc; /* * Enable the VREGs L8(gp7), L10(gp4), L12(gp9), L6(usb) * for I2C communication with keyboard. */ vreg_gp7 = vreg_get(NULL, "gp7"); rc = vreg_set_level(vreg_gp7, 1800); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_gp7; } rc = vreg_enable(vreg_gp7); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_gp7; } vreg_gp4 = vreg_get(NULL, "gp4"); rc = vreg_set_level(vreg_gp4, 2600); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_gp4; } rc = vreg_enable(vreg_gp4); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_gp4; } vreg_gp9 = vreg_get(NULL, "gp9"); rc = vreg_set_level(vreg_gp9, 1800); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_gp9; } rc = vreg_enable(vreg_gp9); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_gp9; } vreg_usb3_3 = vreg_get(NULL, "usb"); rc = vreg_set_level(vreg_usb3_3, 3300); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_3_3; } rc = vreg_enable(vreg_usb3_3); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_3_3; } /* Enable the chip select GPIO */ gpio_set_value(OPTNAV_CHIP_SELECT, 1); gpio_set_value(OPTNAV_CHIP_SELECT, 0); return 0; fail_vreg_3_3: vreg_disable(vreg_gp9); fail_vreg_gp9: vreg_disable(vreg_gp4); fail_vreg_gp4: vreg_disable(vreg_gp7); fail_vreg_gp7: return rc; } static void optnav_disable(void) { vreg_disable(vreg_usb3_3); vreg_disable(vreg_gp9); vreg_disable(vreg_gp4); vreg_disable(vreg_gp7); gpio_set_value(OPTNAV_CHIP_SELECT, 1); } static struct ofn_atlab_platform_data optnav_data = { .gpio_setup = optnav_gpio_setup, .gpio_release = optnav_gpio_release, .optnav_on = optnav_enable, .optnav_off = optnav_disable, .rotate_xy = 0, .function1 = { .no_motion1_en = true, .touch_sensor_en = true, .ofn_en = true, .clock_select_khz = 1500, .cpi_selection = 1200, }, .function2 = { .invert_y = false, .invert_x = true, .swap_x_y = false, .hold_a_b_en = true, .motion_filter_en = true, }, }; /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static int hdmi_comm_power(int on, int show); static int hdmi_init_irq(void); static int hdmi_enable_5v(int on); static int hdmi_core_power(int on, int show); static int hdmi_cec_power(int on); static bool hdmi_check_hdcp_hw_support(void); static struct msm_hdmi_platform_data adv7520_hdmi_data = { .irq = MSM_GPIO_TO_INT(18), .comm_power = hdmi_comm_power, .init_irq = hdmi_init_irq, .enable_5v = hdmi_enable_5v, .core_power = hdmi_core_power, .cec_power = hdmi_cec_power, .check_hdcp_hw_support = hdmi_check_hdcp_hw_support, }; #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL static void hdmi_setup_int_power(int on) { gpio_tlmm_config(GPIO_HDMI_5V_EN, GPIO_CFG_ENABLE); if (on) gpio_set_value(GPIO_PIN(GPIO_HDMI_5V_EN), 1); else gpio_set_value(GPIO_PIN(GPIO_HDMI_5V_EN), 0); } static int hdmi_interrupt_detect(void) { return gpio_get_value(HDMI_INT); } static struct msm_hdmi_platform_data adv7525_hdmi_data = { .irq = MSM_GPIO_TO_INT(HDMI_INT), .intr_detect = hdmi_interrupt_detect, .setup_int_power = hdmi_setup_int_power, }; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ #ifdef CONFIG_BOSCH_BMA150 static struct vreg *vreg_gp6; static int sensors_ldo_enable(void) { int rc; /* * Enable the VREGs L8(gp7), L15(gp6) * for I2C communication with sensors. */ pr_info("sensors_ldo_enable called!!\n"); vreg_gp7 = vreg_get(NULL, "gp7"); if (IS_ERR(vreg_gp7)) { pr_err("%s: vreg_get gp7 failed\n", __func__); rc = PTR_ERR(vreg_gp7); goto fail_gp7_get; } rc = vreg_set_level(vreg_gp7, 1800); if (rc) { pr_err("%s: vreg_set_level gp7 failed\n", __func__); goto fail_gp7_level; } rc = vreg_enable(vreg_gp7); if (rc) { pr_err("%s: vreg_enable gp7 failed\n", __func__); goto fail_gp7_level; } vreg_gp6 = vreg_get(NULL, "gp6"); if (IS_ERR(vreg_gp6)) { pr_err("%s: vreg_get gp6 failed\n", __func__); rc = PTR_ERR(vreg_gp6); goto fail_gp6_get; } rc = vreg_set_level(vreg_gp6, 2800); if (rc) { pr_err("%s: vreg_set_level gp6 failed\n", __func__); goto fail_gp6_level; } rc = vreg_enable(vreg_gp6); if (rc) { pr_err("%s: vreg_enable gp6 failed\n", __func__); goto fail_gp6_level; } return 0; fail_gp6_level: vreg_put(vreg_gp6); fail_gp6_get: vreg_disable(vreg_gp7); fail_gp7_level: vreg_put(vreg_gp7); fail_gp7_get: return rc; } static void sensors_ldo_disable(void) { pr_info("sensors_ldo_disable called!!\n"); vreg_disable(vreg_gp6); vreg_put(vreg_gp6); vreg_disable(vreg_gp7); vreg_put(vreg_gp7); } static struct bma150_platform_data bma150_data = { .power_on = sensors_ldo_enable, .power_off = sensors_ldo_disable, }; static struct i2c_board_info bma150_board_info[] __initdata = { { I2C_BOARD_INFO("bma150", 0x38), .flags = I2C_CLIENT_WAKE, .irq = MSM_GPIO_TO_INT(BMA150_GPIO_INT), .platform_data = &bma150_data, }, }; #endif static struct i2c_board_info msm_i2c_board_info[] = { { I2C_BOARD_INFO("m33c01", OPTNAV_I2C_SLAVE_ADDR), .irq = MSM_GPIO_TO_INT(OPTNAV_IRQ), .platform_data = &optnav_data, }, /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL { I2C_BOARD_INFO("adv7520", ADV7520_I2C_ADDR), .platform_data = &adv7520_hdmi_data, }, #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL { I2C_BOARD_INFO("adv7525", 0x72 >> 1), .platform_data = &adv7525_hdmi_data, }, #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ //Div2-SW2-BSP-Touch, Vincent + #ifdef CONFIG_FIH_TOUCHSCREEN_INNOLUX { I2C_BOARD_INFO("innolux_ts", 0x09), }, #endif #ifdef CONFIG_FIH_TOUCHSCREEN_BU21018MWV { I2C_BOARD_INFO("bu21018mwv", 0x5C), }, #endif #ifdef CONFIG_FIH_TOUCHSCREEN_BI041P { I2C_BOARD_INFO("bi041p", 0x08), .irq = MSM_GPIO_TO_INT(42), }, #endif //Div2-SW2-BSP-Touch, Vincent - //Div2-D5-Peripheral-FG-4H8TouchPorting-00+[ #ifdef CONFIG_FIH_TOUCHSCREEN_ATMEL_MXT165 { I2C_BOARD_INFO("atmel_mxt165", 0x4A), }, #endif //Div2-D5-Peripheral-FG-4H8TouchPorting-00+] #ifdef CONFIG_FIH_AAT1272 { I2C_BOARD_INFO("aat1272", 0x37), }, #endif //Div2D5-OwenHuang-BSP4040_Sensors_Porting-00+{ #ifdef CONFIG_INPUT_YAS529 { I2C_BOARD_INFO("yas529", 0x2E), //yamaha yas529 }, #endif #ifdef CONFIG_INPUT_BMA150 { I2C_BOARD_INFO("bma150", 0x38), //bosch bma150/bosch bma023 }, #endif //Div2D5-OwenHuang-SF8_Sensor_Porting-00+{ #ifdef CONFIG_SENSORS_CM3623 { #ifdef CONFIG_SENSORS_CM3623_IS_AD I2C_BOARD_INFO("cm3623", 0x49), #else I2C_BOARD_INFO("cm3623", 0x11), #endif }, #endif //Div2D5-OwenHuang-SF8_Sensor_Porting-00+} #ifdef CONFIG_SENSORS_LTR502ALS { #ifdef CONFIG_FIH_PROJECT_SF4V5 I2C_BOARD_INFO("ltr502als", 0x1c), .irq = MSM_GPIO_TO_INT(20), #else I2C_BOARD_INFO("ltr502als", 0x1d), .irq = MSM_GPIO_TO_INT(49), #endif }, #endif //Div2D5-OwenHuang-BSP4040_Sensors_Porting-00+} }; static struct i2c_board_info msm_marimba_board_info[] = { { I2C_BOARD_INFO("marimba", 0xc), .platform_data = &marimba_pdata, } }; #ifdef CONFIG_USB_FUNCTION static struct usb_function_map usb_functions_map[] = { {"diag", 0}, {"adb", 1}, {"modem", 2}, {"nmea", 3}, {"mass_storage", 4}, {"ethernet", 5}, }; static struct usb_composition usb_func_composition[] = { { .product_id = 0x9012, .functions = 0x5, /* 0101 */ }, { .product_id = 0x9013, .functions = 0x15, /* 10101 */ }, { .product_id = 0x9014, .functions = 0x30, /* 110000 */ }, { .product_id = 0x9016, .functions = 0xD, /* 01101 */ }, { .product_id = 0x9017, .functions = 0x1D, /* 11101 */ }, { .product_id = 0xF000, .functions = 0x10, /* 10000 */ }, { .product_id = 0xF009, .functions = 0x20, /* 100000 */ }, { .product_id = 0x9018, .functions = 0x1F, /* 011111 */ }, }; static struct msm_hsusb_platform_data msm_hsusb_pdata = { .version = 0x0100, .phy_info = USB_PHY_INTEGRATED | USB_PHY_MODEL_45NM, .vendor_id = 0x5c6, .product_name = "Qualcomm HSUSB Device", .serial_number = "1234567890ABCDEF", .manufacturer_name = "Qualcomm Incorporated", .compositions = usb_func_composition, .num_compositions = ARRAY_SIZE(usb_func_composition), .function_map = usb_functions_map, .num_functions = ARRAY_SIZE(usb_functions_map), .core_clk = 1, }; #endif static struct msm_handset_platform_data hs_platform_data = { .hs_name = "7k_handset", //SW2-5-1-MP-Force_Ramdump-00*[ // .pwr_key_delay_ms = 500, /* 0 will disable end key */ .pwr_key_delay_ms = 0, /* 0 will disable end key */ //SW2-5-1-MP-Force_Ramdump-00*] }; static struct platform_device hs_device = { .name = "msm-handset", .id = -1, .dev = { .platform_data = &hs_platform_data, }, }; static struct msm_pm_platform_data msm_pm_data[MSM_PM_SLEEP_MODE_NR] = { [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].supported = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].suspend_enabled = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].idle_enabled = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].latency = 8594, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].residency = 23740, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].supported = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].suspend_enabled = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].idle_enabled = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].latency = 4594, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].residency = 23740, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].supported = 1, #ifdef CONFIG_MSM_STANDALONE_POWER_COLLAPSE [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].suspend_enabled = 0, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].idle_enabled = 1, #else /*CONFIG_MSM_STANDALONE_POWER_COLLAPSE*/ [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].suspend_enabled = 0, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].idle_enabled = 0, #endif /*CONFIG_MSM_STANDALONE_POWER_COLLAPSE*/ [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].latency = 500, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].residency = 6000, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].supported = 1, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].suspend_enabled = 1, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].idle_enabled = 0, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].latency = 443, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].residency = 1098, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].supported = 1, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].suspend_enabled = 1, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].idle_enabled = 1, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].latency = 2, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].residency = 0, }; static struct resource qsd_spi_resources[] = { { .name = "spi_irq_in", .start = INT_SPI_INPUT, .end = INT_SPI_INPUT, .flags = IORESOURCE_IRQ, }, { .name = "spi_irq_out", .start = INT_SPI_OUTPUT, .end = INT_SPI_OUTPUT, .flags = IORESOURCE_IRQ, }, { .name = "spi_irq_err", .start = INT_SPI_ERROR, .end = INT_SPI_ERROR, .flags = IORESOURCE_IRQ, }, { .name = "spi_base", .start = 0xA8000000, .end = 0xA8000000 + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .name = "spidm_channels", .flags = IORESOURCE_DMA, }, { .name = "spidm_crci", .flags = IORESOURCE_DMA, }, }; #define AMDH0_BASE_PHYS 0xAC200000 #define ADMH0_GP_CTL (ct_adm_base + 0x3D8) static int msm_qsd_spi_dma_config(void) { void __iomem *ct_adm_base = 0; u32 spi_mux = 0; int ret = 0; ct_adm_base = ioremap(AMDH0_BASE_PHYS, PAGE_SIZE); if (!ct_adm_base) { pr_err("%s: Could not remap %x\n", __func__, AMDH0_BASE_PHYS); return -ENOMEM; } spi_mux = (ioread32(ADMH0_GP_CTL) & (0x3 << 12)) >> 12; qsd_spi_resources[4].start = DMOV_USB_CHAN; qsd_spi_resources[4].end = DMOV_TSIF_CHAN; switch (spi_mux) { case (1): qsd_spi_resources[5].start = DMOV_HSUART1_RX_CRCI; qsd_spi_resources[5].end = DMOV_HSUART1_TX_CRCI; break; case (2): qsd_spi_resources[5].start = DMOV_HSUART2_RX_CRCI; qsd_spi_resources[5].end = DMOV_HSUART2_TX_CRCI; break; case (3): qsd_spi_resources[5].start = DMOV_CE_OUT_CRCI; qsd_spi_resources[5].end = DMOV_CE_IN_CRCI; break; default: ret = -ENOENT; } iounmap(ct_adm_base); return ret; } static struct platform_device qsd_device_spi = { .name = "spi_qsd", .id = 0, .num_resources = ARRAY_SIZE(qsd_spi_resources), .resource = qsd_spi_resources, }; #ifdef CONFIG_SPI_QSD static struct spi_board_info lcdc_sharp_spi_board_info[] __initdata = { { .modalias = "lcdc_sharp_ls038y7dx01", .mode = SPI_MODE_1, .bus_num = 0, .chip_select = 0, .max_speed_hz = 26331429, } }; static struct spi_board_info lcdc_toshiba_spi_board_info[] __initdata = { { .modalias = "lcdc_toshiba_ltm030dd40", .mode = SPI_MODE_3|SPI_CS_HIGH, .bus_num = 0, .chip_select = 0, .max_speed_hz = 9963243, } }; #endif static struct msm_gpio qsd_spi_gpio_config_data[] = { { GPIO_CFG(45, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_clk" }, { GPIO_CFG(46, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_cs0" }, { GPIO_CFG(47, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), "spi_mosi" }, { GPIO_CFG(48, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_miso" }, }; static int msm_qsd_spi_gpio_config(void) { return msm_gpios_request_enable(qsd_spi_gpio_config_data, ARRAY_SIZE(qsd_spi_gpio_config_data)); } static void msm_qsd_spi_gpio_release(void) { msm_gpios_disable_free(qsd_spi_gpio_config_data, ARRAY_SIZE(qsd_spi_gpio_config_data)); } static struct msm_spi_platform_data qsd_spi_pdata = { .max_clock_speed = 26331429, .clk_name = "spi_clk", .pclk_name = "spi_pclk", .gpio_config = msm_qsd_spi_gpio_config, .gpio_release = msm_qsd_spi_gpio_release, .dma_config = msm_qsd_spi_dma_config, }; static void __init msm_qsd_spi_init(void) { qsd_device_spi.dev.platform_data = &qsd_spi_pdata; } #ifdef CONFIG_USB_EHCI_MSM static void msm_hsusb_vbus_power(unsigned phy_info, int on) { int rc; static int vbus_is_on; struct pm8058_gpio usb_vbus = { .direction = PM_GPIO_DIR_OUT, .pull = PM_GPIO_PULL_NO, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .vin_sel = 2, .out_strength = PM_GPIO_STRENGTH_MED, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, }; /* If VBUS is already on (or off), do nothing. */ if (unlikely(on == vbus_is_on)) return; if (on) { rc = pm8058_gpio_config(36, &usb_vbus); if (rc) { pr_err("%s PMIC GPIO 36 write failed\n", __func__); return; } } else { gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(36), 0); } vbus_is_on = on; } static struct msm_usb_host_platform_data msm_usb_host_pdata = { .phy_info = (USB_PHY_INTEGRATED | USB_PHY_MODEL_45NM), .vbus_power = msm_hsusb_vbus_power, .power_budget = 180, }; #endif #ifdef CONFIG_USB_MSM_OTG_72K static int hsusb_rpc_connect(int connect) { if (connect) return msm_hsusb_rpc_connect(); else return msm_hsusb_rpc_close(); } #endif #ifdef CONFIG_USB_MSM_OTG_72K static struct vreg *vreg_3p3; static int msm_hsusb_ldo_init(int init) { uint32_t version = 0; int def_vol = 3400; version = socinfo_get_version(); if (SOCINFO_VERSION_MAJOR(version) >= 2 && SOCINFO_VERSION_MINOR(version) >= 1) { def_vol = 3075; pr_debug("%s: default voltage:%d\n", __func__, def_vol); } if (init) { vreg_3p3 = vreg_get(NULL, "usb"); if (IS_ERR(vreg_3p3)) return PTR_ERR(vreg_3p3); vreg_set_level(vreg_3p3, def_vol); } else vreg_put(vreg_3p3); return 0; } static int msm_hsusb_ldo_enable(int enable) { static int ldo_status; if (!vreg_3p3 || IS_ERR(vreg_3p3)) return -ENODEV; if (ldo_status == enable) return 0; ldo_status = enable; if (enable) return vreg_enable(vreg_3p3); return vreg_disable(vreg_3p3); } static int msm_hsusb_ldo_set_voltage(int mV) { static int cur_voltage = 3400; if (!vreg_3p3 || IS_ERR(vreg_3p3)) return -ENODEV; if (cur_voltage == mV) return 0; cur_voltage = mV; pr_debug("%s: (%d)\n", __func__, mV); return vreg_set_level(vreg_3p3, mV); } #endif #ifndef CONFIG_USB_EHCI_MSM static int msm_hsusb_pmic_notif_init(void (*callback)(int online), int init); #endif static struct msm_otg_platform_data msm_otg_pdata = { .rpc_connect = hsusb_rpc_connect, #ifndef CONFIG_USB_EHCI_MSM .pmic_vbus_notif_init = msm_hsusb_pmic_notif_init, #else .vbus_power = msm_hsusb_vbus_power, #endif .core_clk = 1, .pemp_level = PRE_EMPHASIS_WITH_20_PERCENT, .cdr_autoreset = CDR_AUTO_RESET_DISABLE, .drv_ampl = HS_DRV_AMPLITUDE_DEFAULT, .se1_gating = SE1_GATING_DISABLE, .chg_vbus_draw = hsusb_chg_vbus_draw, .chg_connected = hsusb_chg_connected, .chg_init = hsusb_chg_init, .ldo_enable = msm_hsusb_ldo_enable, .ldo_init = msm_hsusb_ldo_init, .ldo_set_voltage = msm_hsusb_ldo_set_voltage, }; #ifdef CONFIG_USB_GADGET static struct msm_hsusb_gadget_platform_data msm_gadget_pdata = { .is_phy_status_timer_on = 1, }; #endif #ifndef CONFIG_USB_EHCI_MSM typedef void (*notify_vbus_state) (int); notify_vbus_state notify_vbus_state_func_ptr; int vbus_on_irq; static irqreturn_t pmic_vbus_on_irq(int irq, void *data) { pr_info("%s: vbus notification from pmic\n", __func__); (*notify_vbus_state_func_ptr) (1); return IRQ_HANDLED; } static int msm_hsusb_pmic_notif_init(void (*callback)(int online), int init) { int ret; if (init) { if (!callback) return -ENODEV; notify_vbus_state_func_ptr = callback; vbus_on_irq = platform_get_irq_byname(&msm_device_otg, "vbus_on"); if (vbus_on_irq <= 0) { pr_err("%s: unable to get vbus on irq\n", __func__); return -ENODEV; } ret = request_any_context_irq(vbus_on_irq, pmic_vbus_on_irq, IRQF_TRIGGER_RISING, "msm_otg_vbus_on", NULL); if (ret < 0) { pr_info("%s: request_irq for vbus_on" "interrupt failed\n", __func__); return ret; } msm_otg_pdata.pmic_vbus_irq = vbus_on_irq; return 0; } else { free_irq(vbus_on_irq, 0); notify_vbus_state_func_ptr = NULL; return 0; } } #endif static struct android_pmem_platform_data android_pmem_pdata = { .name = "pmem", .allocator_type = PMEM_ALLOCATORTYPE_ALLORNOTHING, .cached = 1, }; static struct platform_device android_pmem_device = { .name = "android_pmem", .id = 0, .dev = { .platform_data = &android_pmem_pdata }, }; //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 #ifndef CONFIG_SPI_QSD static int lcdc_gpio_array_num[] = { 45, /* spi_clk */ 46, /* spi_cs */ 47, /* spi_mosi */ 48, /* spi_miso */ }; static struct msm_gpio lcdc_gpio_config_data[] = { { GPIO_CFG(45, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_clk" }, { GPIO_CFG(46, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_cs0" }, { GPIO_CFG(47, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_mosi" }, { GPIO_CFG(48, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_miso" }, }; static void lcdc_config_gpios(int enable) { if (enable) { msm_gpios_request_enable(lcdc_gpio_config_data, ARRAY_SIZE( lcdc_gpio_config_data)); } else msm_gpios_disable_free(lcdc_gpio_config_data, ARRAY_SIZE( lcdc_gpio_config_data)); } #endif static struct msm_panel_common_pdata lcdc_sharp_panel_data = { #ifndef CONFIG_SPI_QSD .panel_config_gpio = lcdc_config_gpios, .gpio_num = lcdc_gpio_array_num, #endif .gpio = 2, /* LPG PMIC_GPIO26 channel number */ }; static struct platform_device lcdc_sharp_panel_device = { .name = "lcdc_sharp_wvga", .id = 0, .dev = { .platform_data = &lcdc_sharp_panel_data, } }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00- /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static struct msm_gpio dtv_panel_irq_gpios[] = { { GPIO_CFG(18, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "hdmi_int" }, }; #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL static struct msm_gpio hdmi_panel_gpios[] = { { GPIO_CFG(34, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_4MA), "hdmi_5v_en" }, { GPIO_CFG(HDMI_INT, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "hdmi_int" }, }; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ #if defined(CONFIG_FB_MSM_HDMI_ADV7525_PANEL) || defined(CONFIG_FB_MSM_HDMI_ADV7520_PANEL) static struct msm_gpio dtv_panel_gpios[] = { { GPIO_CFG(120, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "wca_mclk" }, { GPIO_CFG(121, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "wca_sd0" }, { GPIO_CFG(122, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "wca_sd1" }, { GPIO_CFG(123, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "wca_sd2" }, { GPIO_CFG(124, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), "dtv_pclk" }, { GPIO_CFG(125, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_en" }, { GPIO_CFG(126, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_vsync" }, { GPIO_CFG(127, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_hsync" }, { GPIO_CFG(128, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data0" }, { GPIO_CFG(129, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data1" }, { GPIO_CFG(130, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data2" }, { GPIO_CFG(131, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data3" }, { GPIO_CFG(132, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data4" }, { GPIO_CFG(160, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data5" }, { GPIO_CFG(161, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data6" }, { GPIO_CFG(162, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data7" }, { GPIO_CFG(163, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data8" }, { GPIO_CFG(164, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data9" }, { GPIO_CFG(165, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat10" }, { GPIO_CFG(166, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat11" }, { GPIO_CFG(167, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat12" }, { GPIO_CFG(168, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat13" }, { GPIO_CFG(169, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat14" }, { GPIO_CFG(170, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat15" }, { GPIO_CFG(171, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat16" }, { GPIO_CFG(172, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat17" }, { GPIO_CFG(173, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat18" }, { GPIO_CFG(174, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat19" }, { GPIO_CFG(175, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat20" }, { GPIO_CFG(176, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat21" }, { GPIO_CFG(177, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat22" }, { GPIO_CFG(178, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat23" }, }; #endif #ifdef HDMI_RESET static unsigned dtv_reset_gpio = GPIO_CFG(37, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static int gpio_set(const char *label, const char *name, int level, int on) { struct vreg *vreg = vreg_get(NULL, label); int rc; if (IS_ERR(vreg)) { rc = PTR_ERR(vreg); pr_err("%s: vreg %s get failed (%d)\n", __func__, name, rc); return rc; } rc = vreg_set_level(vreg, level); if (rc) { pr_err("%s: vreg %s set level failed (%d)\n", __func__, name, rc); return rc; } if (on) rc = vreg_enable(vreg); else rc = vreg_disable(vreg); if (rc) pr_err("%s: vreg %s enable failed (%d)\n", __func__, name, rc); return rc; } #endif ///#if defined(CONFIG_FB_MSM_HDMI_ADV7520_PANEL) || defined(CONFIG_BOSCH_BMA150) /* there is an i2c address conflict between adv7520 and bma150 sensor after * power up on fluid. As a solution, the default address of adv7520's packet * memory is changed as soon as possible */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static int __init fluid_i2c_address_fixup(void) { unsigned char wBuff[16]; unsigned char rBuff[16]; struct i2c_msg msgs[3]; int res; int rc = -EINVAL; struct vreg *vreg_ldo8; struct i2c_adapter *adapter; if (machine_is_msm7x30_fluid()) { adapter = i2c_get_adapter(0); if (!adapter) { pr_err("%s: invalid i2c adapter\n", __func__); return PTR_ERR(adapter); } /* turn on LDO8 */ vreg_ldo8 = vreg_get(NULL, "gp7"); if (!vreg_ldo8) { pr_err("%s: VREG L8 get failed\n", __func__); goto adapter_put; } rc = vreg_set_level(vreg_ldo8, 1800); if (rc) { pr_err("%s: VREG L8 set failed\n", __func__); goto ldo8_put; } rc = vreg_enable(vreg_ldo8); if (rc) { pr_err("%s: VREG L8 enable failed\n", __func__); goto ldo8_put; } /* change packet memory address to 0x74 */ wBuff[0] = 0x45; wBuff[1] = 0x74; msgs[0].addr = ADV7520_I2C_ADDR; msgs[0].flags = 0; msgs[0].buf = (unsigned char *) wBuff; msgs[0].len = 2; res = i2c_transfer(adapter, msgs, 1); if (res != 1) { pr_err("%s: error writing adv7520\n", __func__); goto ldo8_disable; } /* powerdown adv7520 using bit 6 */ /* i2c read first */ wBuff[0] = 0x41; msgs[0].addr = ADV7520_I2C_ADDR; msgs[0].flags = 0; msgs[0].buf = (unsigned char *) wBuff; msgs[0].len = 1; msgs[1].addr = ADV7520_I2C_ADDR; msgs[1].flags = I2C_M_RD; msgs[1].buf = rBuff; msgs[1].len = 1; res = i2c_transfer(adapter, msgs, 2); if (res != 2) { pr_err("%s: error reading adv7520\n", __func__); goto ldo8_disable; } /* i2c write back */ wBuff[0] = 0x41; wBuff[1] = rBuff[0] | 0x40; msgs[0].addr = ADV7520_I2C_ADDR; msgs[0].flags = 0; msgs[0].buf = (unsigned char *) wBuff; msgs[0].len = 2; res = i2c_transfer(adapter, msgs, 1); if (res != 1) { pr_err("%s: error writing adv7520\n", __func__); goto ldo8_disable; } /* for successful fixup, we release the i2c adapter */ /* but leave ldo8 on so that the adv7520 is not repowered */ i2c_put_adapter(adapter); pr_info("%s: fluid i2c address conflict resolved\n", __func__); } return 0; ldo8_disable: vreg_disable(vreg_ldo8); ldo8_put: vreg_put(vreg_ldo8); adapter_put: i2c_put_adapter(adapter); return rc; } subsys_initcall_sync(fluid_i2c_address_fixup); #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static int hdmi_comm_power(int on, int show) { int rc = gpio_set("gp7", "LDO8", 1800, on); if (rc) { pr_warning("hdmi_comm_power: LDO8 gpio failed: rc=%d\n", rc); return rc; } rc = gpio_set("gp4", "LDO10", 2600, on); if (rc) pr_warning("hdmi_comm_power: LDO10 gpio failed: rc=%d\n", rc); if (show) pr_info("%s: i2c comm: %d <LDO8+LDO10>\n", __func__, on); return rc; } static int hdmi_init_irq(void) { int rc = msm_gpios_enable(dtv_panel_irq_gpios, ARRAY_SIZE(dtv_panel_irq_gpios)); if (rc < 0) { pr_err("%s: gpio enable failed: %d\n", __func__, rc); return rc; } pr_info("%s\n", __func__); return 0; } static int hdmi_enable_5v(int on) { int pmic_gpio_hdmi_5v_en ; if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa() || machine_is_msm7x30_fluid()) pmic_gpio_hdmi_5v_en = PMIC_GPIO_HDMI_5V_EN_V2 ; else pmic_gpio_hdmi_5v_en = PMIC_GPIO_HDMI_5V_EN_V3 ; pr_info("%s: %d\n", __func__, on); if (on) { int rc; rc = gpio_request(PM8058_GPIO_PM_TO_SYS(pmic_gpio_hdmi_5v_en), "hdmi_5V_en"); if (rc) { pr_err("%s PMIC_GPIO_HDMI_5V_EN gpio_request failed\n", __func__); return rc; } gpio_set_value_cansleep( PM8058_GPIO_PM_TO_SYS(pmic_gpio_hdmi_5v_en), 1); } else { gpio_set_value_cansleep( PM8058_GPIO_PM_TO_SYS(pmic_gpio_hdmi_5v_en), 0); gpio_free(PM8058_GPIO_PM_TO_SYS(pmic_gpio_hdmi_5v_en)); } return 0; } static int hdmi_core_power(int on, int show) { if (show) pr_info("%s: %d <LDO8>\n", __func__, on); return gpio_set("gp7", "LDO8", 1800, on); } static int hdmi_cec_power(int on) { pr_info("%s: %d <LDO17>\n", __func__, on); return gpio_set("gp11", "LDO17", 2600, on); } static bool hdmi_check_hdcp_hw_support(void) { if (machine_is_msm7x30_fluid()) return false; else return true; } static int dtv_panel_power(int on) { int flag_on = !!on; static int dtv_power_save_on; int rc; if (dtv_power_save_on == flag_on) return 0; dtv_power_save_on = flag_on; pr_info("%s: %d\n", __func__, on); #ifdef HDMI_RESET if (on) { /* reset Toshiba WeGA chip -- toggle reset pin -- gpio_180 */ rc = gpio_tlmm_config(dtv_reset_gpio, GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, dtv_reset_gpio, rc); return rc; } /* bring reset line low to hold reset*/ gpio_set_value(37, 0); } #endif if (on) { rc = msm_gpios_enable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); return rc; } } else { rc = msm_gpios_disable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio disable failed: %d\n", __func__, rc); return rc; } } mdelay(5); /* ensure power is stable */ #ifdef HDMI_RESET if (on) { gpio_set_value(37, 1); /* bring reset line high */ mdelay(10); /* 10 msec before IO can be accessed */ } #endif return rc; } #endif /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL static int dtv_panel_power(int on) { int flag_on = !!on; static int dtv_power_save_on; int rc; struct vreg *vreg_ldo11; if (dtv_power_save_on == flag_on) return 0; dtv_power_save_on = flag_on; pr_info("%s: %d >>\n", __func__, on); if(!on){ rc = msm_gpios_disable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio disable failed: %d\n", __func__, rc); return rc; } printk("dtv_panel_power always turn on\n"); return 0; }else if(hdmi_init_done){ rc = msm_gpios_enable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); return rc; } return 0; } if (on) { rc = msm_gpios_enable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); return rc; } rc = msm_gpios_enable(hdmi_panel_gpios, ARRAY_SIZE(hdmi_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); return rc; } } else { rc = msm_gpios_disable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio disable failed: %d\n", __func__, rc); return rc; } } /* VDDIO 1.8V -- LDO11*/ vreg_ldo11 = vreg_get(NULL, "gp2"); if (IS_ERR(vreg_ldo11)) { rc = PTR_ERR(vreg_ldo11); printk("%s: gp2 vreg get failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo11, 1800); if (rc) { printk("%s: vreg LDO11 set level failed (%d)\n", __func__, rc); return rc; } if (on) rc = vreg_enable(vreg_ldo11); else rc = vreg_disable(vreg_ldo11); if (rc) { printk("%s: LDO11 vreg enable failed (%d)\n", __func__, rc); return rc; } mdelay(5); gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_HDMI_18V_EN), on); gpio_tlmm_config(GPIO_HDMI_5V_EN, GPIO_CFG_ENABLE); if (on) gpio_set_value(GPIO_PIN(GPIO_HDMI_5V_EN), 1); else { printk("dtv_panel_power 5V always turn on\n"); ///gpio_set_value(GPIO_PIN(GPIO_HDMI_5V_EN), 0); } mdelay(5); /* ensure power is stable */ pr_info("%s: %d <<\n", __func__, on); hdmi_init_done = true; return rc; } #endif #if defined(CONFIG_FB_MSM_HDMI_ADV7525_PANEL) || defined(CONFIG_FB_MSM_HDMI_ADV7520_PANEL) static struct lcdc_platform_data dtv_pdata = { .lcdc_power_save = dtv_panel_power, }; #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL static struct platform_device hdmi_adv7525_panel_device = { .name = "adv7525", .id = 0, }; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ static struct msm_serial_hs_platform_data msm_uart_dm1_pdata = { .inject_rx_on_wakeup = 1, .rx_to_inject = 0xFD, }; static struct resource msm_fb_resources[] = { { .flags = IORESOURCE_DMA, } }; static int msm_fb_detect_panel(const char *name) { if (machine_is_msm7x30_fluid()) { if (!strcmp(name, "lcdc_sharp_wvga_pt")) return 0; } else { if (!strncmp(name, "mddi_toshiba_wvga_pt", 20)) return -EPERM; else if (!strncmp(name, "lcdc_toshiba_wvga_pt", 20)) return 0; else if (!strcmp(name, "mddi_orise")) return -EPERM; else if (!strcmp(name, "mddi_quickvx")) return -EPERM; } return -ENODEV; } static struct msm_fb_platform_data msm_fb_pdata = { .detect_client = msm_fb_detect_panel, .mddi_prescan = 1, }; static struct platform_device msm_fb_device = { .name = "msm_fb", .id = 0, .num_resources = ARRAY_SIZE(msm_fb_resources), .resource = msm_fb_resources, .dev = { .platform_data = &msm_fb_pdata, } }; static struct platform_device msm_migrate_pages_device = { .name = "msm_migrate_pages", .id = -1, }; static struct android_pmem_platform_data android_pmem_kernel_ebi1_pdata = { .name = PMEM_KERNEL_EBI1_DATA_NAME, /* if no allocator_type, defaults to PMEM_ALLOCATORTYPE_BITMAP, * the only valid choice at this time. The board structure is * set to all zeros by the C runtime initialization and that is now * the enum value of PMEM_ALLOCATORTYPE_BITMAP, now forced to 0 in * include/linux/android_pmem.h. */ .cached = 0, }; static struct android_pmem_platform_data android_pmem_adsp_pdata = { .name = "pmem_adsp", .allocator_type = PMEM_ALLOCATORTYPE_BITMAP, .cached = 0, }; static struct android_pmem_platform_data android_pmem_audio_pdata = { .name = "pmem_audio", .allocator_type = PMEM_ALLOCATORTYPE_BITMAP, .cached = 0, }; static struct platform_device android_pmem_kernel_ebi1_device = { .name = "android_pmem", .id = 1, .dev = { .platform_data = &android_pmem_kernel_ebi1_pdata }, }; static struct platform_device android_pmem_adsp_device = { .name = "android_pmem", .id = 2, .dev = { .platform_data = &android_pmem_adsp_pdata }, }; static struct platform_device android_pmem_audio_device = { .name = "android_pmem", .id = 4, .dev = { .platform_data = &android_pmem_audio_pdata }, }; static struct resource kgsl_3d0_resources[] = { { .name = KGSL_3D0_REG_MEMORY, .start = 0xA3500000, /* 3D GRP address */ .end = 0xA351ffff, .flags = IORESOURCE_MEM, }, { .name = KGSL_3D0_IRQ, .start = INT_GRP_3D, .end = INT_GRP_3D, .flags = IORESOURCE_IRQ, }, }; static struct kgsl_device_platform_data kgsl_3d0_pdata = { .pwrlevel = { { .gpu_freq = 245760000, .bus_freq = 192000000, }, { .gpu_freq = 192000000, .bus_freq = 153000000, }, { .gpu_freq = 192000000, .bus_freq = 0, }, }, .init_level = 0, .num_levels = 3, .set_grp_async = set_grp3d_async, .idle_timeout = HZ/20, .nap_allowed = true, .clk = { .clk = "grp_clk", .pclk = "grp_pclk", }, .imem_clk_name = { .clk = "imem_clk", .pclk = NULL, }, }; static struct platform_device msm_kgsl_3d0 = { .name = "kgsl-3d0", .id = 0, .num_resources = ARRAY_SIZE(kgsl_3d0_resources), .resource = kgsl_3d0_resources, .dev = { .platform_data = &kgsl_3d0_pdata, }, }; #ifdef CONFIG_MSM_KGSL_2D static struct resource kgsl_2d0_resources[] = { { .name = KGSL_2D0_REG_MEMORY, .start = 0xA3900000, /* Z180 base address */ .end = 0xA3900FFF, .flags = IORESOURCE_MEM, }, { .name = KGSL_2D0_IRQ, .start = INT_GRP_2D, .end = INT_GRP_2D, .flags = IORESOURCE_IRQ, }, }; static struct kgsl_device_platform_data kgsl_2d0_pdata = { .pwrlevel = { { .gpu_freq = 0, .bus_freq = 192000000, }, }, .init_level = 0, .num_levels = 1, /* HW workaround, run Z180 SYNC @ 192 MHZ */ .set_grp_async = NULL, .idle_timeout = HZ/10, .nap_allowed = true, .clk = { .clk = "grp_2d_clk", .pclk = "grp_2d_pclk", }, }; static struct platform_device msm_kgsl_2d0 = { .name = "kgsl-2d0", .id = 0, .num_resources = ARRAY_SIZE(kgsl_2d0_resources), .resource = kgsl_2d0_resources, .dev = { .platform_data = &kgsl_2d0_pdata, }, }; #endif //SW2-D5-OwenHung-SF4V5/SF4Y6 keypad backlight+ #if defined(CONFIG_FIH_PROJECT_SF4V5) || defined(CONFIG_FIH_PROJECT_SF4Y6) || defined(CONFIG_FIH_PROJECT_SF8) static struct platform_device msm_device_pmic_leds = { .name = "pmic-leds", .id = -1, }; #endif //SW2-D5-OwenHung-SF4V5/SF4Y6 keypad backlight- #if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \ defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE) || \ defined(CONFIG_CRYPTO_DEV_QCEDEV) || \ defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE) #define QCE_SIZE 0x10000 #define QCE_0_BASE 0xA8400000 #define QCE_HW_KEY_SUPPORT 1 #define QCE_SHARE_CE_RESOURCE 0 #define QCE_CE_SHARED 0 static struct resource qce_resources[] = { [0] = { .start = QCE_0_BASE, .end = QCE_0_BASE + QCE_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .name = "crypto_channels", .start = DMOV_CE_IN_CHAN, .end = DMOV_CE_OUT_CHAN, .flags = IORESOURCE_DMA, }, [2] = { .name = "crypto_crci_in", .start = DMOV_CE_IN_CRCI, .end = DMOV_CE_IN_CRCI, .flags = IORESOURCE_DMA, }, [3] = { .name = "crypto_crci_out", .start = DMOV_CE_OUT_CRCI, .end = DMOV_CE_OUT_CRCI, .flags = IORESOURCE_DMA, }, [4] = { .name = "crypto_crci_hash", .start = DMOV_CE_HASH_CRCI, .end = DMOV_CE_HASH_CRCI, .flags = IORESOURCE_DMA, }, }; #endif #if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \ defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE) static struct msm_ce_hw_support qcrypto_ce_hw_suppport = { .ce_shared = QCE_CE_SHARED, .shared_ce_resource = QCE_SHARE_CE_RESOURCE, .hw_key_support = QCE_HW_KEY_SUPPORT, }; static struct platform_device qcrypto_device = { .name = "qcrypto", .id = 0, .num_resources = ARRAY_SIZE(qce_resources), .resource = qce_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), .platform_data = &qcrypto_ce_hw_suppport, }, }; #endif #if defined(CONFIG_CRYPTO_DEV_QCEDEV) || \ defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE) static struct msm_ce_hw_support qcedev_ce_hw_suppport = { .ce_shared = QCE_CE_SHARED, .shared_ce_resource = QCE_SHARE_CE_RESOURCE, .hw_key_support = QCE_HW_KEY_SUPPORT, }; static struct platform_device qcedev_device = { .name = "qce", .id = 0, .num_resources = ARRAY_SIZE(qce_resources), .resource = qce_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), .platform_data = &qcedev_ce_hw_suppport, }, }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 static int mddi_toshiba_pmic_bl(int level) { int ret = -EPERM; // DIV2-SW2-BSP-FBx-LEDS+ #ifndef CONFIG_LEDS_FIH_FBX_PWM ret = pmic_set_led_intensity(LED_LCD, level); #endif // DIV2-SW2-BSP-FBx-LEDS- if (ret) printk(KERN_WARNING "%s: can't set lcd backlight!\n", __func__); return ret; } static struct msm_panel_common_pdata mddi_toshiba_pdata = { .pmic_backlight = mddi_toshiba_pmic_bl, }; static struct platform_device mddi_toshiba_device = { .name = "mddi_toshiba", .id = 0, .dev = { .platform_data = &mddi_toshiba_pdata, } }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00- #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static unsigned lcdc_reset_gpio = GPIO_CFG(35, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA); static int display_common_power(int on) { int rc = 0, flag_on = !!on; static int display_common_power_save_on = 0; struct vreg *vreg_ldo11, *vreg_ldo15 = NULL; printk(KERN_INFO "[DISPLAY] %s(%d): current power status = %d.\n", __func__, on, display_common_power_save_on); if (display_common_power_save_on == flag_on) return 0; display_common_power_save_on = flag_on; if (on) { /* reset LCM -- toggle reset pin -- gpio_35 */ rc = gpio_tlmm_config(lcdc_reset_gpio, GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, lcdc_reset_gpio, rc); return rc; } gpio_set_value(35, 0); /* bring reset line low to hold reset*/ mdelay(1); /* wait 1 ms */ } else { /* Hard Reset, Reset Pin from high to low */ gpio_set_value(35, 0); } /* LCM power -- has 2 power source */ /* VDDIO 1.8V -- LDO11*/ vreg_ldo11 = vreg_get(NULL, "gp2"); if (IS_ERR(vreg_ldo11)) { pr_err("%s: gp2 vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_ldo11)); return rc; } /* VDC 3.05V -- LDO15 */ vreg_ldo15 = vreg_get(NULL, "gp6"); if (IS_ERR(vreg_ldo15)) { rc = PTR_ERR(vreg_ldo15); pr_err("%s: gp6 vreg get failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo11, 1800); if (rc) { pr_err("%s: vreg LDO11 set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo15, 3050); if (rc) { pr_err("%s: vreg LDO15 set level failed (%d)\n", __func__, rc); return rc; } if (on) { rc = vreg_enable(vreg_ldo11); /* PMIC GPIO VREG_LCM_V1P8_EN pull high */ gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_LCM_V1P8_EN), 1); } else { /* Use PMIC_GPIO_LCM_V1P8_EN to control LCM_V1P8 when display off */ //rc = vreg_disable(vreg_ldo11); /* PMIC GPIO VREG_LCM_V1P8_EN pull low */ gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_LCM_V1P8_EN), 0); } if (rc) { pr_err("%s: LDO11 vreg enable failed (%d)\n", __func__, rc); return rc; } if (on) { rc = vreg_enable(vreg_ldo15); } else { rc = vreg_disable(vreg_ldo15); } if (rc) { pr_err("%s: LDO15 vreg enable failed (%d)\n", __func__, rc); return rc; } if (on) { mdelay(1); /* wait 1 ms */ /* Div2-SW2-BSP,JOE HSU,Add LCM reset line hi -> lo -> hi */ gpio_set_value(35, 1); /* bring reset line high */ mdelay(5); /* 10 msec before IO can be accessed */ gpio_set_value(35, 0); mdelay(5); gpio_set_value(35, 1); mdelay(5); } if (on) { rc = pmapp_display_clock_config(1); if (rc) { pr_err("%s pmapp_display_clock_config rc=%d\n", __func__, rc); return rc; } } else { rc = pmapp_display_clock_config(0); if (rc) { pr_err("%s pmapp_display_clock_config rc=%d\n", __func__, rc); return rc; } } return rc; } #endif // CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT #if 0 static unsigned wega_reset_gpio = GPIO_CFG(180, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); static struct msm_gpio fluid_vee_reset_gpio[] = { { GPIO_CFG(20, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "vee_reset" }, }; #endif static unsigned char quickvx_mddi_client = 1; #if 0 static unsigned quickvx_vlp_gpio = GPIO_CFG(97, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); static struct pm8058_gpio pmic_quickvx_clk_gpio = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S3, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_2, }; #endif #if 0 static int display_common_power(int on) { int rc = 0, flag_on = !!on; static int display_common_power_save_on; struct vreg *vreg_ldo12, *vreg_ldo15 = NULL; struct vreg *vreg_ldo20, *vreg_ldo16, *vreg_ldo8 = NULL; if (display_common_power_save_on == flag_on) return 0; display_common_power_save_on = flag_on; if (on) { /* reset Toshiba WeGA chip -- toggle reset pin -- gpio_180 */ rc = gpio_tlmm_config(wega_reset_gpio, GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, wega_reset_gpio, rc); return rc; } /* bring reset line low to hold reset*/ gpio_set_value(180, 0); if (quickvx_mddi_client) { /* QuickVX chip -- VLP pin -- gpio 97 */ rc = gpio_tlmm_config(quickvx_vlp_gpio, GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, quickvx_vlp_gpio, rc); return rc; } /* bring QuickVX VLP line low */ gpio_set_value(97, 0); rc = pm8058_gpio_config(PMIC_GPIO_QUICKVX_CLK, &pmic_quickvx_clk_gpio); if (rc) { pr_err("%s: pm8058_gpio_config(%#x)=%d\n", __func__, PMIC_GPIO_QUICKVX_CLK + 1, rc); return rc; } gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS( PMIC_GPIO_QUICKVX_CLK), 0); } } /* Toshiba WeGA power -- has 3 power source */ /* 1.5V -- LDO20*/ vreg_ldo20 = vreg_get(NULL, "gp13"); if (IS_ERR(vreg_ldo20)) { rc = PTR_ERR(vreg_ldo20); pr_err("%s: gp13 vreg get failed (%d)\n", __func__, rc); return rc; } /* 1.8V -- LDO12 */ vreg_ldo12 = vreg_get(NULL, "gp9"); if (IS_ERR(vreg_ldo12)) { rc = PTR_ERR(vreg_ldo12); pr_err("%s: gp9 vreg get failed (%d)\n", __func__, rc); return rc; } /* 2.6V -- LDO16 */ vreg_ldo16 = vreg_get(NULL, "gp10"); if (IS_ERR(vreg_ldo16)) { rc = PTR_ERR(vreg_ldo16); pr_err("%s: gp10 vreg get failed (%d)\n", __func__, rc); return rc; } if (machine_is_msm7x30_fluid()) { /* 1.8V -- LDO8 */ vreg_ldo8 = vreg_get(NULL, "gp7"); if (IS_ERR(vreg_ldo8)) { rc = PTR_ERR(vreg_ldo8); pr_err("%s: gp7 vreg get failed (%d)\n", __func__, rc); return rc; } } else { /* lcd panel power */ /* 3.1V -- LDO15 */ vreg_ldo15 = vreg_get(NULL, "gp6"); if (IS_ERR(vreg_ldo15)) { rc = PTR_ERR(vreg_ldo15); pr_err("%s: gp6 vreg get failed (%d)\n", __func__, rc); return rc; } } /* For QuickLogic chip, LDO20 requires 1.8V */ /* Toshiba chip requires 1.5V, but can tolerate 1.8V since max is 3V */ if (quickvx_mddi_client) rc = vreg_set_level(vreg_ldo20, 1800); else rc = vreg_set_level(vreg_ldo20, 1500); if (rc) { pr_err("%s: vreg LDO20 set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo12, 1800); if (rc) { pr_err("%s: vreg LDO12 set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo16, 2600); if (rc) { pr_err("%s: vreg LDO16 set level failed (%d)\n", __func__, rc); return rc; } if (machine_is_msm7x30_fluid()) { rc = vreg_set_level(vreg_ldo8, 1800); if (rc) { pr_err("%s: vreg LDO8 set level failed (%d)\n", __func__, rc); return rc; } } else { rc = vreg_set_level(vreg_ldo15, 3100); if (rc) { pr_err("%s: vreg LDO15 set level failed (%d)\n", __func__, rc); return rc; } } if (on) { rc = vreg_enable(vreg_ldo20); if (rc) { pr_err("%s: LDO20 vreg enable failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_ldo12); if (rc) { pr_err("%s: LDO12 vreg enable failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_ldo16); if (rc) { pr_err("%s: LDO16 vreg enable failed (%d)\n", __func__, rc); return rc; } if (machine_is_msm7x30_fluid()) { rc = vreg_enable(vreg_ldo8); if (rc) { pr_err("%s: LDO8 vreg enable failed (%d)\n", __func__, rc); return rc; } } else { rc = vreg_enable(vreg_ldo15); if (rc) { pr_err("%s: LDO15 vreg enable failed (%d)\n", __func__, rc); return rc; } } mdelay(5); /* ensure power is stable */ if (machine_is_msm7x30_fluid()) { rc = msm_gpios_request_enable(fluid_vee_reset_gpio, ARRAY_SIZE(fluid_vee_reset_gpio)); if (rc) pr_err("%s gpio_request_enable failed rc=%d\n", __func__, rc); else { /* assert vee reset_n */ gpio_set_value(20, 1); gpio_set_value(20, 0); mdelay(1); gpio_set_value(20, 1); } } gpio_set_value(180, 1); /* bring reset line high */ mdelay(10); /* 10 msec before IO can be accessed */ if (quickvx_mddi_client) { gpio_set_value(97, 1); msleep(2); gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS( PMIC_GPIO_QUICKVX_CLK), 1); msleep(2); } rc = pmapp_display_clock_config(1); if (rc) { pr_err("%s pmapp_display_clock_config rc=%d\n", __func__, rc); return rc; } } else { rc = vreg_disable(vreg_ldo20); if (rc) { pr_err("%s: LDO20 vreg enable failed (%d)\n", __func__, rc); return rc; } rc = vreg_disable(vreg_ldo16); if (rc) { pr_err("%s: LDO16 vreg enable failed (%d)\n", __func__, rc); return rc; } gpio_set_value(180, 0); /* bring reset line low */ if (quickvx_mddi_client) { gpio_set_value(97, 0); gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS( PMIC_GPIO_QUICKVX_CLK), 0); } if (machine_is_msm7x30_fluid()) { rc = vreg_disable(vreg_ldo8); if (rc) { pr_err("%s: LDO8 vreg enable failed (%d)\n", __func__, rc); return rc; } } else { rc = vreg_disable(vreg_ldo15); if (rc) { pr_err("%s: LDO15 vreg enable failed (%d)\n", __func__, rc); return rc; } } mdelay(5); /* ensure power is stable */ rc = vreg_disable(vreg_ldo12); if (rc) { pr_err("%s: LDO12 vreg enable failed (%d)\n", __func__, rc); return rc; } if (machine_is_msm7x30_fluid()) { msm_gpios_disable_free(fluid_vee_reset_gpio, ARRAY_SIZE(fluid_vee_reset_gpio)); } rc = pmapp_display_clock_config(0); if (rc) { pr_err("%s pmapp_display_clock_config rc=%d\n", __func__, rc); return rc; } } return rc; } #endif // static int msm_fb_mddi_sel_clk(u32 *clk_rate) { *clk_rate *= 2; return 0; } static int msm_fb_mddi_client_power(u32 client_id) { struct vreg *vreg_ldo20; int rc; printk(KERN_NOTICE "\n client_id = 0x%x", client_id); /* Check if it is Quicklogic client */ if (client_id == 0xc5835800) printk(KERN_NOTICE "\n Quicklogic MDDI client"); else { printk(KERN_NOTICE "\n Non-Quicklogic MDDI client"); quickvx_mddi_client = 0; gpio_set_value(97, 0); gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS( PMIC_GPIO_QUICKVX_CLK), 0); vreg_ldo20 = vreg_get(NULL, "gp13"); if (IS_ERR(vreg_ldo20)) { rc = PTR_ERR(vreg_ldo20); pr_err("%s: gp13 vreg get failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo20, 1500); if (rc) { pr_err("%s: vreg LDO20 set level failed (%d)\n", __func__, rc); return rc; } } return 0; } static struct mddi_platform_data mddi_pdata = { #ifndef CONFIG_FIH_CONFIG_GROUP .mddi_power_save = display_common_power, #endif .mddi_sel_clk = msm_fb_mddi_sel_clk, .mddi_client_power = msm_fb_mddi_client_power, }; int mdp_core_clk_rate_table[] = { 122880000, 122880000, 192000000, 192000000, }; static struct msm_panel_common_pdata mdp_pdata = { .hw_revision_addr = 0xac001270, // DIV2-SW2-BSP-FBx-LEDS+ #ifndef CONFIG_LEDS_FIH_FBX_PWM .gpio = 30, #endif // DIV2-SW2-BSP-FBx-LEDS- .mdp_core_clk_rate = 122880000, .mdp_core_clk_table = mdp_core_clk_rate_table, .num_mdp_clk = ARRAY_SIZE(mdp_core_clk_rate_table), }; /* FIHTDC, Div2-SW2-BSP, Ming, LCM { */ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static int lcd_panel_spi_gpio_num[] = { 45, /* spi_clk */ 46, /* spi_cs */ 47, /* spi_mosi */ 48, /* spi_miso */ }; static struct msm_gpio lcd_panel_gpios[] = { { GPIO_CFG(18, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn0" }, { GPIO_CFG(19, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn1" }, { GPIO_CFG(20, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu0" }, { GPIO_CFG(21, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu1" }, { GPIO_CFG(22, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu2" }, { GPIO_CFG(23, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red0" }, { GPIO_CFG(24, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red1" }, { GPIO_CFG(25, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red2" }, { GPIO_CFG(45, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "spi_clk" }, { GPIO_CFG(46, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "spi_cs0" }, { GPIO_CFG(47, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "spi_mosi" }, { GPIO_CFG(48, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "spi_miso" }, { GPIO_CFG(90, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_4MA), "lcdc_pclk" }, // FIHTDC-Div2-SW2-BSP, Ming, 4mA /// { GPIO_CFG(91, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_en" }, { GPIO_CFG(92, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_vsync" }, { GPIO_CFG(93, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_hsync" }, { GPIO_CFG(94, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn2" }, { GPIO_CFG(95, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn3" }, { GPIO_CFG(96, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn4" }, { GPIO_CFG(97, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn5" }, /// { GPIO_CFG(98, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn6" }, /// { GPIO_CFG(99, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn7" }, { GPIO_CFG(100, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu3" }, { GPIO_CFG(101, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu4" }, { GPIO_CFG(102, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu5" }, /// { GPIO_CFG(103, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu6" }, /// { GPIO_CFG(104, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu7" }, { GPIO_CFG(105, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red3" }, { GPIO_CFG(106, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red4" }, { GPIO_CFG(107, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red5" }, /// { GPIO_CFG(108, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red6" }, /// { GPIO_CFG(109, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red7" }, }; #endif // CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT #if 0 static struct msm_gpio lcd_panel_gpios[] = { /* Workaround, since HDMI_INT is using the same GPIO line (18), and is used as * input. if there is a hardware revision; we should reassign this GPIO to a * new open line; and removing it will just ensure that this will be missed in * the future. { GPIO_CFG(18, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn0" }, */ { GPIO_CFG(19, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn1" }, { GPIO_CFG(20, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu0" }, { GPIO_CFG(21, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu1" }, { GPIO_CFG(22, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu2" }, { GPIO_CFG(23, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red0" }, { GPIO_CFG(24, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red1" }, { GPIO_CFG(25, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red2" }, #ifndef CONFIG_SPI_QSD { GPIO_CFG(45, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_clk" }, { GPIO_CFG(46, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_cs0" }, { GPIO_CFG(47, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_mosi" }, { GPIO_CFG(48, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_miso" }, #endif { GPIO_CFG(90, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_pclk" }, { GPIO_CFG(91, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_en" }, { GPIO_CFG(92, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_vsync" }, { GPIO_CFG(93, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_hsync" }, { GPIO_CFG(94, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn2" }, { GPIO_CFG(95, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn3" }, { GPIO_CFG(96, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn4" }, { GPIO_CFG(97, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn5" }, { GPIO_CFG(98, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn6" }, { GPIO_CFG(99, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn7" }, { GPIO_CFG(100, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu3" }, { GPIO_CFG(101, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu4" }, { GPIO_CFG(102, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu5" }, { GPIO_CFG(103, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu6" }, { GPIO_CFG(104, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu7" }, { GPIO_CFG(105, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red3" }, { GPIO_CFG(106, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red4" }, { GPIO_CFG(107, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red5" }, { GPIO_CFG(108, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red6" }, { GPIO_CFG(109, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red7" }, }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 static struct msm_gpio lcd_sharp_panel_gpios[] = { { GPIO_CFG(22, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu2" }, { GPIO_CFG(25, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red2" }, { GPIO_CFG(90, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_pclk" }, { GPIO_CFG(91, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_en" }, { GPIO_CFG(92, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_vsync" }, { GPIO_CFG(93, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_hsync" }, { GPIO_CFG(94, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn2" }, { GPIO_CFG(95, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn3" }, { GPIO_CFG(96, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn4" }, { GPIO_CFG(97, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn5" }, { GPIO_CFG(98, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn6" }, { GPIO_CFG(99, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn7" }, { GPIO_CFG(100, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu3" }, { GPIO_CFG(101, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu4" }, { GPIO_CFG(102, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu5" }, { GPIO_CFG(103, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu6" }, { GPIO_CFG(104, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu7" }, { GPIO_CFG(105, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red3" }, { GPIO_CFG(106, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red4" }, { GPIO_CFG(107, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red5" }, { GPIO_CFG(108, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red6" }, { GPIO_CFG(109, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red7" }, }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00- //SW2-6-MM-JH-Display_Flag-00+ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static int lcdc_toshiba_panel_power(int on) { int rc, i; struct msm_gpio *gp; rc = display_common_power(on); if (rc < 0) { printk(KERN_ERR "%s display_common_power failed: %d\n", __func__, rc); return rc; } if (on) { rc = msm_gpios_enable(lcd_panel_gpios, ARRAY_SIZE(lcd_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); } } else { /* off */ gp = lcd_panel_gpios; for (i = 0; i < ARRAY_SIZE(lcd_panel_gpios); i++) { /* ouput low */ gpio_set_value(GPIO_PIN(gp->gpio_cfg), 0); gp++; } } return rc; } #endif //SW2-6-MM-JH-Display_Flag-00- //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 static int lcdc_sharp_panel_power(int on) { int rc, i; struct msm_gpio *gp; rc = display_common_power(on); if (rc < 0) { printk(KERN_ERR "%s display_common_power failed: %d\n", __func__, rc); return rc; } if (on) { rc = msm_gpios_enable(lcd_sharp_panel_gpios, ARRAY_SIZE(lcd_sharp_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); } } else { /* off */ gp = lcd_sharp_panel_gpios; for (i = 0; i < ARRAY_SIZE(lcd_sharp_panel_gpios); i++) { /* ouput low */ gpio_set_value(GPIO_PIN(gp->gpio_cfg), 0); gp++; } } return rc; } #endif //SW2-6-MM-JH-Unused_Display_Codes-00- //SW2-6-MM-JH-Display_Flag-00+ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static int lcdc_panel_power(int on) { int flag_on = !!on; static int lcdc_power_save_on; if (lcdc_power_save_on == flag_on) return 0; lcdc_power_save_on = flag_on; quickvx_mddi_client = 0; //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 if (machine_is_msm7x30_fluid()) return lcdc_sharp_panel_power(on); else return lcdc_toshiba_panel_power(on); #else return lcdc_toshiba_panel_power(on); #endif //SW2-6-MM-JH-Unused_Display_Codes-00- } #endif // CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT //SW2-6-MM-JH-Display_Flag-00- static struct lcdc_platform_data lcdc_pdata = { #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT .lcdc_power_save = lcdc_panel_power, #endif }; static int atv_dac_power(int on) { int rc = 0; struct vreg *vreg_s4, *vreg_ldo9; vreg_s4 = vreg_get(NULL, "s4"); if (IS_ERR(vreg_s4)) { rc = PTR_ERR(vreg_s4); pr_err("%s: s4 vreg get failed (%d)\n", __func__, rc); return -1; } vreg_ldo9 = vreg_get(NULL, "gp1"); if (IS_ERR(vreg_ldo9)) { rc = PTR_ERR(vreg_ldo9); pr_err("%s: ldo9 vreg get failed (%d)\n", __func__, rc); return rc; } if (on) { rc = vreg_enable(vreg_s4); if (rc) { pr_err("%s: s4 vreg enable failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_ldo9); if (rc) { pr_err("%s: ldo9 vreg enable failed (%d)\n", __func__, rc); return rc; } } else { rc = vreg_disable(vreg_ldo9); if (rc) { pr_err("%s: ldo9 vreg disable failed (%d)\n", __func__, rc); return rc; } rc = vreg_disable(vreg_s4); if (rc) { pr_err("%s: s4 vreg disable failed (%d)\n", __func__, rc); return rc; } } return rc; } static struct tvenc_platform_data atv_pdata = { .poll = 1, .pm_vid_en = atv_dac_power, }; static void __init msm_fb_add_devices(void) { msm_fb_register_device("mdp", &mdp_pdata); msm_fb_register_device("pmdh", &mddi_pdata); msm_fb_register_device("lcdc", &lcdc_pdata); #if defined(CONFIG_FB_MSM_HDMI_ADV7525_PANEL) || defined(CONFIG_FB_MSM_HDMI_ADV7520_PANEL) msm_fb_register_device("dtv", &dtv_pdata); #endif msm_fb_register_device("tvenc", &atv_pdata); #ifdef CONFIG_FB_MSM_TVOUT msm_fb_register_device("tvout_device", NULL); #endif } //SW2-6-MM-JH-Display_Flag-00+ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static struct msm_panel_common_pdata lcdc_toshiba_panel_data = { .gpio_num = lcd_panel_spi_gpio_num, }; static struct platform_device lcdc_toshiba_panel_device = { .name = "lcdc_toshiba_wvga", .id = 0, .dev = { .platform_data = &lcdc_toshiba_panel_data, } }; #endif // CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT //SW2-6-MM-JH-Display_Flag-00- // FIHTDC-SW2-Div6-CW-Project BCM4329 For SF8 +[ #if defined(CONFIG_BROADCOM_BCM4329) && \ (defined(CONFIG_BROADCOM_BCM4329_BLUETOOTH_POWER) || defined(CONFIG_BROADCOM_BCM4329_WLAN_POWER)) #define BT_MASK 0x01 #define WLAN_MASK 0x02 #define FM_MASK 0x04 #define GPIO_WLAN_BT_REG_ON 168 static unsigned int bcm4329_power_status = 0; #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 For SF8 +] // FIHTDC-SW2-Div6-CW-Project BCM4329 Bluetooth driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_BLUETOOTH_POWER #define GPIO_BTUART_RFR 134 #define GPIO_BTUART_CTS 135 #define GPIO_BTUART_RX 136 #define GPIO_BTUART_TX 137 #define GPIO_PCM_DIN 138 #define GPIO_PCM_DOUT 139 #define GPIO_PCM_SYNC 140 #define GPIO_PCM_BCLK 141 #define GPIO_BT_RST_N 144 #define GPIO_BT_IRQ 147 #define GPIO_BT_WAKEUP 170 static struct platform_device bcm4329_bt_power_device = { .name = "bcm4329_bt_power", .id = -1 }; static struct msm_gpio bt_config_power_on[] = { { GPIO_CFG(GPIO_BTUART_RFR, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_RFR" }, { GPIO_CFG(GPIO_BTUART_CTS, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_CTS" }, { GPIO_CFG(GPIO_BTUART_RX, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_RX" }, { GPIO_CFG(GPIO_BTUART_TX, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_TX" }, { GPIO_CFG(GPIO_BT_IRQ, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "BT_HOST_WAKE" }, { GPIO_CFG(GPIO_BT_WAKEUP, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "BT_WAKE" } }; static struct msm_gpio bt_config_power_off[] = { { GPIO_CFG(GPIO_BTUART_RFR, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_RFR" }, { GPIO_CFG(GPIO_BTUART_CTS, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_CTS" }, { GPIO_CFG(GPIO_BTUART_RX, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_RX" }, { GPIO_CFG(GPIO_BTUART_TX, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_TX" }, { GPIO_CFG(GPIO_BT_IRQ, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "BT_HOST_WAKE" }, { GPIO_CFG(GPIO_BT_WAKEUP, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "BT_WAKE" } }; static int bluetooth_fm_power(int on) { int rc; printk("KERN_DEBUG %s: POWER %s\r\n", __FUNCTION__, on?"ON":"OFF"); if (on) { rc = msm_gpios_enable(bt_config_power_on, ARRAY_SIZE(bt_config_power_on)); if (rc < 0) { printk(KERN_DEBUG "%s: Power ON bluetooth failed.\r\n", __FUNCTION__); return rc; } if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL UP GPIO_WLAN_BT_REG_ON\r\n", __FUNCTION__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 1); mdelay(20); } gpio_set_value(GPIO_BT_RST_N, 0); mdelay(20); gpio_set_value(GPIO_BT_RST_N, 1); mdelay(100); printk(KERN_DEBUG "%s: GPIO_BT_RST (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_BT_RST_N)?"HIGH":"LOW"); printk(KERN_DEBUG "%s: GPIO_WLAN_BT_REG_ON (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_BT_REG_ON)?"HIGH":"LOW"); } else { rc = msm_gpios_enable(bt_config_power_off, ARRAY_SIZE(bt_config_power_off)); if (rc < 0) { printk(KERN_DEBUG "%s: Power OFF bluetooth failed.\r\n", __FUNCTION__); return rc; } gpio_set_value(GPIO_BT_RST_N, 0); if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL DOWN GPIO_WLAN_BT_REG_ON\r\n", __FUNCTION__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); } mdelay(100); printk(KERN_DEBUG "%s: GPIO_BT_RST (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_BT_RST_N)?"HIGH":"LOW"); printk(KERN_DEBUG "%s: GPIO_WLAN_BT_REG_ON (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_BT_REG_ON)?"HIGH":"LOW"); } return 0; } static int bluetooth_power(int on) { int ret = 0; printk("KERN_DEBUG %s: POWER %s\r\n", __FUNCTION__, on?"ON":"OFF"); if (on) { if ((bcm4329_power_status & ~WLAN_MASK) != 0) { printk("KERN_DEBUG %s: FM has been enable the power\r\n", __FUNCTION__); bcm4329_power_status |= BT_MASK; return 0; } ret = bluetooth_fm_power(on); if (ret < 0) { printk(KERN_DEBUG "%s: Power ON bluetooth failed.\r\n", __FUNCTION__); return ret; } bcm4329_power_status |= BT_MASK; } else { if ((bcm4329_power_status & ~(WLAN_MASK | BT_MASK)) != 0) { printk("KERN_DEBUG %s: FM enabled, can't turn bcm4329 bt/fm power\r\n", __FUNCTION__); bcm4329_power_status &= ~BT_MASK; return 0; } bcm4329_power_status &= ~BT_MASK; ret = bluetooth_fm_power(on); if (ret < 0) { printk(KERN_DEBUG "%s: Power ON bluetooth failed.\r\n", __FUNCTION__); return ret; } } return 0; } static void __init bcm4329_bt_power_init(void) { gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); gpio_set_value(GPIO_BT_RST_N, 0); bcm4329_bt_power_device.dev.platform_data = &bluetooth_power; } #else //#define bt_power_init(x) do {} while (0) #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 Bluetooth driver For SF8 +] #if defined(CONFIG_BROADCOM_BCM4329) static struct platform_device bcm4329_fm_power_device = { .name = "bcm4329_fm_power", .id = -1 }; static int fm_power(int on) { int ret = 0; printk("KERN_DEBUG %s: POWER %s\r\n", __FUNCTION__, on?"ON":"OFF"); if (on) { if ((bcm4329_power_status & ~WLAN_MASK) != 0) { printk("KERN_DEBUG %s: Bluetooth has been enable the power\r\n", __FUNCTION__); bcm4329_power_status |= FM_MASK; return 0; } ret = bluetooth_fm_power(on); if (ret < 0) { printk(KERN_DEBUG "%s: Power ON FM failed.\r\n", __FUNCTION__); return ret; } bcm4329_power_status |= FM_MASK; } else { if ((bcm4329_power_status & ~(WLAN_MASK | FM_MASK)) != 0) { printk("KERN_DEBUG %s: Bluetooth enabled, can't turn bcm4329 bt/fm power\r\n", __FUNCTION__); bcm4329_power_status &= ~FM_MASK; return 0; } bcm4329_power_status &= ~FM_MASK; ret = bluetooth_fm_power(on); if (ret < 0) { printk(KERN_DEBUG "%s: Power ON FM failed.\r\n", __FUNCTION__); return ret; } } return 0; } static void __init bcm4329_fm_power_init(void) { bcm4329_fm_power_device.dev.platform_data = &fm_power; } #endif #if defined(CONFIG_BROADCOM_BCM4329) static struct resource bluesleep_resources[] = { { .name = "gpio_host_wake", .start = GPIO_BT_IRQ, .end = GPIO_BT_IRQ, .flags = IORESOURCE_IO, }, { .name = "gpio_ext_wake", .start = GPIO_BT_WAKEUP, .end = GPIO_BT_WAKEUP, .flags = IORESOURCE_IO, }, { .name = "host_wake", .start = MSM_GPIO_TO_INT(GPIO_BT_IRQ), .end = MSM_GPIO_TO_INT(GPIO_BT_IRQ), .flags = IORESOURCE_IO, }, }; static struct platform_device msm_bluesleep_device = { .name = "bluesleep", .id = -1, .num_resources = ARRAY_SIZE(bluesleep_resources), .resource = bluesleep_resources, }; #endif // FihtdcCode@20110908 WeiChu add for WiFi porting begin // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_WLAN_POWER #define GPIO_WLAN_RST_N 146 #define GPIO_WLAN_IRQ 145 #define GPIO_WLAN_WAKEUP 169 static struct platform_device bcm4329_wifi_power_device = { .name = "bcm4329_wifi_power", .id = -1 }; int wifi_power(int on) //SW5-PT1-Connectivity_FredYu_FixPowerSequence { printk(KERN_DEBUG "%s: POWER %s\r\n", __FUNCTION__, on?"ON":"OFF"); if (on) { if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL UP GPIO_WLAN_BT_REG_ON\r\n", __FUNCTION__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 1); mdelay(20); } gpio_set_value(GPIO_WLAN_RST_N, 1); mdelay(20); bcm4329_power_status |= WLAN_MASK; printk(KERN_DEBUG "%s: GPIO_WLAN_RST (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_RST_N)?"HIGH":"LOW"); printk(KERN_DEBUG "%s: GPIO_WLAN_BT_REG_ON (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_BT_REG_ON)?"HIGH":"LOW"); } else { bcm4329_power_status &= ~WLAN_MASK; gpio_set_value(GPIO_WLAN_RST_N, 0); if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL DOWN GPIO_WLAN_BT_REG_ON\r\n", __FUNCTION__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); } printk(KERN_DEBUG "%s: GPIO_WLAN_RST (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_RST_N)?"HIGH":"LOW"); printk(KERN_DEBUG "%s: GPIO_WLAN_BT_REG_ON (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_BT_REG_ON)?"HIGH":"LOW"); } return 0; } EXPORT_SYMBOL(wifi_power); //SW5-PT1-Connectivity_FredYu_FixPowerSequence int bcm4329_wifi_resume(void) { printk(KERN_DEBUG "%s: START bcm4329_power_status=0x%x\r\n", __func__, bcm4329_power_status); if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL UP GPIO_WLAN_BT_REG_ON\r\n", __func__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 1); mdelay(45); } gpio_set_value(GPIO_WLAN_RST_N, 1); mdelay(20); bcm4329_power_status |= WLAN_MASK; return 0; } EXPORT_SYMBOL(bcm4329_wifi_resume); int bcm4329_wifi_suspend(void) { printk(KERN_DEBUG "%s: START bcm4329_power_status=0x%x\r\n", __func__, bcm4329_power_status); bcm4329_power_status &= ~WLAN_MASK; gpio_set_value(GPIO_WLAN_RST_N, 0); if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL DOWN GPIO_WLAN_BT_REG_ON\r\n", __func__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); } return 0; } EXPORT_SYMBOL(bcm4329_wifi_suspend); static void __init bcm4329_wifi_power_init(void) { gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); gpio_set_value(GPIO_WLAN_RST_N, 0); bcm4329_wifi_power_device.dev.platform_data = &wifi_power; } #else #define wifi_power_init(x) do {} while (0) #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +] // FihtdcCode@20110908 WeiChu add for WiFi porting end #if defined(CONFIG_MARIMBA_CORE) && \ (defined(CONFIG_MSM_BT_POWER) || defined(CONFIG_MSM_BT_POWER_MODULE)) static struct platform_device msm_bt_power_device = { .name = "bt_power", .id = -1 }; enum { BT_RFR, BT_CTS, BT_RX, BT_TX, }; static struct msm_gpio bt_config_power_on[] = { { GPIO_CFG(134, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_RFR" }, { GPIO_CFG(135, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_CTS" }, { GPIO_CFG(136, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_Rx" }, { GPIO_CFG(137, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_Tx" } }; static struct msm_gpio bt_config_power_off[] = { { GPIO_CFG(134, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_RFR" }, { GPIO_CFG(135, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_CTS" }, { GPIO_CFG(136, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_Rx" }, { GPIO_CFG(137, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_Tx" } }; static const char *vregs_bt_marimba_name[] = { "s3", "s2", "gp16", "wlan" }; static struct vreg *vregs_bt_marimba[ARRAY_SIZE(vregs_bt_marimba_name)]; static const char *vregs_bt_bahama_name[] = { "s3", "usb2", "s2", "wlan" }; static struct vreg *vregs_bt_bahama[ARRAY_SIZE(vregs_bt_bahama_name)]; static u8 bahama_version; static int marimba_bt(int on) { int rc; int i; struct marimba config = { .mod_id = MARIMBA_SLAVE_ID_MARIMBA }; struct marimba_config_register { u8 reg; u8 value; u8 mask; }; struct marimba_variant_register { const size_t size; const struct marimba_config_register *set; }; const struct marimba_config_register *p; u8 version; const struct marimba_config_register v10_bt_on[] = { { 0xE5, 0x0B, 0x0F }, { 0x05, 0x02, 0x07 }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x21, 0x21 }, { 0xE3, 0x38, 0xFF }, { 0xE4, 0x06, 0xFF }, }; const struct marimba_config_register v10_bt_off[] = { { 0xE5, 0x0B, 0x0F }, { 0x05, 0x08, 0x0F }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x00, 0x21 }, { 0xE3, 0x00, 0xFF }, { 0xE4, 0x00, 0xFF }, }; const struct marimba_config_register v201_bt_on[] = { { 0x05, 0x08, 0x07 }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x21, 0x21 }, { 0xE3, 0x38, 0xFF }, { 0xE4, 0x06, 0xFF }, }; const struct marimba_config_register v201_bt_off[] = { { 0x05, 0x08, 0x07 }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x00, 0x21 }, { 0xE3, 0x00, 0xFF }, { 0xE4, 0x00, 0xFF }, }; const struct marimba_config_register v210_bt_on[] = { { 0xE9, 0x01, 0x01 }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x21, 0x21 }, { 0xE3, 0x38, 0xFF }, { 0xE4, 0x06, 0xFF }, }; const struct marimba_config_register v210_bt_off[] = { { 0x06, 0x88, 0xFF }, { 0xE7, 0x00, 0x21 }, { 0xE9, 0x00, 0x01 }, { 0xE3, 0x00, 0xFF }, { 0xE4, 0x00, 0xFF }, }; const struct marimba_variant_register bt_marimba[2][4] = { { { ARRAY_SIZE(v10_bt_off), v10_bt_off }, { 0, NULL }, { ARRAY_SIZE(v201_bt_off), v201_bt_off }, { ARRAY_SIZE(v210_bt_off), v210_bt_off } }, { { ARRAY_SIZE(v10_bt_on), v10_bt_on }, { 0, NULL }, { ARRAY_SIZE(v201_bt_on), v201_bt_on }, { ARRAY_SIZE(v210_bt_on), v210_bt_on } } }; on = on ? 1 : 0; rc = marimba_read_bit_mask(&config, 0x11, &version, 1, 0x1F); if (rc < 0) { printk(KERN_ERR "%s: version read failed: %d\n", __func__, rc); return rc; } if ((version >= ARRAY_SIZE(bt_marimba[on])) || (bt_marimba[on][version].size == 0)) { printk(KERN_ERR "%s: unsupported version\n", __func__); return -EIO; } p = bt_marimba[on][version].set; printk(KERN_INFO "%s: found version %d\n", __func__, version); for (i = 0; i < bt_marimba[on][version].size; i++) { u8 value = (p+i)->value; rc = marimba_write_bit_mask(&config, (p+i)->reg, &value, sizeof((p+i)->value), (p+i)->mask); if (rc < 0) { printk(KERN_ERR "%s: reg %d write failed: %d\n", __func__, (p+i)->reg, rc); return rc; } printk(KERN_INFO "%s: reg 0x%02x value 0x%02x mask 0x%02x\n", __func__, (p+i)->reg, value, (p+i)->mask); } return 0; } static int bahama_bt(int on) { int rc; int i; struct marimba config = { .mod_id = SLAVE_ID_BAHAMA }; struct bahama_variant_register { const size_t size; const struct bahama_config_register *set; }; const struct bahama_config_register *p; const struct bahama_config_register v10_bt_on[] = { { 0xE9, 0x00, 0xFF }, { 0xF4, 0x80, 0xFF }, { 0xF0, 0x06, 0xFF }, { 0xE4, 0x00, 0xFF }, { 0xE5, 0x00, 0x0F }, #ifdef CONFIG_WLAN { 0xE6, 0x38, 0x7F }, { 0xE7, 0x06, 0xFF }, #endif { 0x11, 0x13, 0xFF }, { 0xE9, 0x21, 0xFF }, { 0x01, 0x0C, 0x1F }, { 0x01, 0x08, 0x1F }, }; const struct bahama_config_register v20_bt_on_fm_off[] = { { 0x11, 0x0C, 0xFF }, { 0x13, 0x01, 0xFF }, { 0xF4, 0x80, 0xFF }, { 0xF0, 0x00, 0xFF }, { 0xE9, 0x00, 0xFF }, #ifdef CONFIG_WLAN { 0x81, 0x00, 0xFF }, { 0x82, 0x00, 0xFF }, { 0xE6, 0x38, 0x7F }, { 0xE7, 0x06, 0xFF }, #endif { 0xE9, 0x21, 0xFF } }; const struct bahama_config_register v20_bt_on_fm_on[] = { { 0x11, 0x0C, 0xFF }, { 0x13, 0x01, 0xFF }, { 0xF4, 0x86, 0xFF }, { 0xF0, 0x06, 0xFF }, { 0xE9, 0x00, 0xFF }, #ifdef CONFIG_WLAN { 0x81, 0x00, 0xFF }, { 0x82, 0x00, 0xFF }, { 0xE6, 0x38, 0x7F }, { 0xE7, 0x06, 0xFF }, #endif { 0xE9, 0x21, 0xFF } }; const struct bahama_config_register v10_bt_off[] = { { 0xE9, 0x00, 0xFF }, }; const struct bahama_config_register v20_bt_off_fm_off[] = { { 0xF4, 0x84, 0xFF }, { 0xF0, 0x04, 0xFF }, { 0xE9, 0x00, 0xFF } }; const struct bahama_config_register v20_bt_off_fm_on[] = { { 0xF4, 0x86, 0xFF }, { 0xF0, 0x06, 0xFF }, { 0xE9, 0x00, 0xFF } }; const struct bahama_variant_register bt_bahama[2][3] = { { { ARRAY_SIZE(v10_bt_off), v10_bt_off }, { ARRAY_SIZE(v20_bt_off_fm_off), v20_bt_off_fm_off }, { ARRAY_SIZE(v20_bt_off_fm_on), v20_bt_off_fm_on } }, { { ARRAY_SIZE(v10_bt_on), v10_bt_on }, { ARRAY_SIZE(v20_bt_on_fm_off), v20_bt_on_fm_off }, { ARRAY_SIZE(v20_bt_on_fm_on), v20_bt_on_fm_on } } }; u8 offset = 0; /* index into bahama configs */ /* Init mutex to get/set FM/BT status respectively */ mutex_init(&config.xfer_lock); on = on ? 1 : 0; bahama_version = read_bahama_ver(); if (bahama_version == VER_UNSUPPORTED) { dev_err(&msm_bt_power_device.dev, "%s: unsupported version\n", __func__); return -EIO; } if (bahama_version == VER_2_0) { if (marimba_get_fm_status(&config)) offset = 0x01; } p = bt_bahama[on][bahama_version + offset].set; dev_info(&msm_bt_power_device.dev, "%s: found version %d\n", __func__, bahama_version); for (i = 0; i < bt_bahama[on][bahama_version + offset].size; i++) { u8 value = (p+i)->value; rc = marimba_write_bit_mask(&config, (p+i)->reg, &value, sizeof((p+i)->value), (p+i)->mask); if (rc < 0) { dev_err(&msm_bt_power_device.dev, "%s: reg %d write failed: %d\n", __func__, (p+i)->reg, rc); return rc; } dev_info(&msm_bt_power_device.dev, "%s: reg 0x%02x write value 0x%02x mask 0x%02x\n", __func__, (p+i)->reg, value, (p+i)->mask); } /* Update BT status */ if (on) marimba_set_bt_status(&config, true); else marimba_set_bt_status(&config, false); /* Destory mutex */ mutex_destroy(&config.xfer_lock); if (bahama_version == VER_2_0 && on) { /* variant of bahama v2 */ /* Disable s2 as bahama v2 uses internal LDO regulator */ for (i = 0; i < ARRAY_SIZE(vregs_bt_bahama_name); i++) { if (!strcmp(vregs_bt_bahama_name[i], "s2")) { rc = vreg_disable(vregs_bt_bahama[i]); if (rc < 0) { printk(KERN_ERR "%s: vreg %s disable " "failed (%d)\n", __func__, vregs_bt_bahama_name[i], rc); return -EIO; } rc = pmapp_vreg_level_vote("BTPW", PMAPP_VREG_S2, 0); if (rc < 0) { printk(KERN_ERR "%s: vreg " "level off failed (%d)\n", __func__, rc); return -EIO; } printk(KERN_INFO "%s: vreg disable & " "level off successful (%d)\n", __func__, rc); } } } return 0; } static int bluetooth_power_regulators(int on, int bahama_not_marimba) { int i, rc; const char **vregs_name; struct vreg **vregs; int vregs_size; if (bahama_not_marimba) { vregs_name = vregs_bt_bahama_name; vregs = vregs_bt_bahama; vregs_size = ARRAY_SIZE(vregs_bt_bahama_name); } else { vregs_name = vregs_bt_marimba_name; vregs = vregs_bt_marimba; vregs_size = ARRAY_SIZE(vregs_bt_marimba_name); } for (i = 0; i < vregs_size; i++) { if (bahama_not_marimba && (bahama_version == VER_2_0) && !on && !strcmp(vregs_bt_bahama_name[i], "s2")) continue; rc = on ? vreg_enable(vregs[i]) : vreg_disable(vregs[i]); if (rc < 0) { printk(KERN_ERR "%s: vreg %s %s failed (%d)\n", __func__, vregs_name[i], on ? "enable" : "disable", rc); return -EIO; } } return 0; } static int bluetooth_power(int on) { int rc; const char *id = "BTPW"; int bahama_not_marimba = bahama_present(); if (bahama_not_marimba == -1) { printk(KERN_WARNING "%s: bahama_present: %d\n", __func__, bahama_not_marimba); return -ENODEV; } if (on) { rc = pmapp_vreg_level_vote(id, PMAPP_VREG_S2, 1300); if (rc < 0) { printk(KERN_ERR "%s: vreg level on failed (%d)\n", __func__, rc); return rc; } rc = bluetooth_power_regulators(on, bahama_not_marimba); if (rc < 0) return -EIO; /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_ON); } else { rc = pmapp_clock_vote(id, QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_ON); } if (rc < 0) return -EIO; if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = marimba_gpio_config(1); if (rc < 0) return -EIO; } rc = (bahama_not_marimba ? bahama_bt(on) : marimba_bt(on)); if (rc < 0) return -EIO; msleep(10); /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_PIN_CTRL); } else { rc = pmapp_clock_vote(id, QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_PIN_CTRL); } if (rc < 0) return -EIO; if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = marimba_gpio_config(0); if (rc < 0) return -EIO; } rc = msm_gpios_enable(bt_config_power_on, ARRAY_SIZE(bt_config_power_on)); if (rc < 0) return rc; } else { rc = msm_gpios_enable(bt_config_power_off, ARRAY_SIZE(bt_config_power_off)); if (rc < 0) return rc; /* check for initial RFKILL block (power off) */ if (platform_get_drvdata(&msm_bt_power_device) == NULL) goto out; rc = (bahama_not_marimba ? bahama_bt(on) : marimba_bt(on)); if (rc < 0) return -EIO; /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_OFF); } else { rc = pmapp_clock_vote(id, QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_OFF); } if (rc < 0) return -EIO; rc = bluetooth_power_regulators(on, bahama_not_marimba); if (rc < 0) return -EIO; if (bahama_version == VER_1_0) { rc = pmapp_vreg_level_vote(id, PMAPP_VREG_S2, 0); if (rc < 0) { printk(KERN_ERR "%s: vreg level off failed " "(%d)\n", __func__, rc); return -EIO; } } } out: printk(KERN_DEBUG "Bluetooth power switch: %d\n", on); return 0; } static void __init bt_power_init(void) { int i; for (i = 0; i < ARRAY_SIZE(vregs_bt_marimba_name); i++) { vregs_bt_marimba[i] = vreg_get(NULL, vregs_bt_marimba_name[i]); if (IS_ERR(vregs_bt_marimba[i])) { printk(KERN_ERR "%s: vreg get %s failed (%ld)\n", __func__, vregs_bt_marimba_name[i], PTR_ERR(vregs_bt_marimba[i])); return; } } for (i = 0; i < ARRAY_SIZE(vregs_bt_bahama_name); i++) { vregs_bt_bahama[i] = vreg_get(NULL, vregs_bt_bahama_name[i]); if (IS_ERR(vregs_bt_bahama[i])) { printk(KERN_ERR "%s: vreg get %s failed (%ld)\n", __func__, vregs_bt_bahama_name[i], PTR_ERR(vregs_bt_bahama[i])); return; } } msm_bt_power_device.dev.platform_data = &bluetooth_power; } #else #define bt_power_init(x) do {} while (0) #endif #if defined(CONFIG_BATTERY_FIH_MSM) || defined(CONFIG_BATTERY_MSM) static struct msm_psy_batt_pdata msm_psy_batt_data = { .voltage_min_design = 2800, .voltage_max_design = 4300, .avail_chg_sources = AC_CHG | USB_CHG , .batt_technology = POWER_SUPPLY_TECHNOLOGY_LION, // DIV2-SW2-BSP-FBx-BATT+[ #ifdef CONFIG_BATTERY_FIH_MSM .batt_info_if = { .get_chg_source = msm_batt_get_chg_source, .get_batt_status = msm_batt_get_batt_status, .get_batt_capacity = msm_batt_info_not_support, .get_batt_health = msm_batt_info_not_support, .get_batt_temp = msm_batt_info_not_support, .get_batt_voltage = msm_batt_info_not_support, }, #endif // DIV2-SW2-BSP-FBX-BATT+] }; static struct platform_device msm_batt_device = { .name = "msm-battery", .id = -1, .dev.platform_data = &msm_psy_batt_data, }; #endif // DIV2-SW2-BSP-FBx-BATT+[ #ifdef CONFIG_BATTERY_FIH_MSM enum { HWMODEL_GAUGE_DS2784, HWMODEL_GAUGE_BQ27500, }; #ifdef CONFIG_DS2482 static struct ds2482_platform_data ds2482_pdata = { .pmic_gpio_ds2482_SLPZ = 31, .sys_gpio_ds2482_SLPZ = PM8058_GPIO_PM_TO_SYS(31) - 1, .sys_gpio_gauge_ls_en = 88, }; #endif #ifdef CONFIG_BATTERY_BQ275X0 struct bq275x0_platform_data bq275x0_pdata = { #if defined(CONFIG_FIH_PROJECT_FB0) || defined(CONFIG_FIH_PROJECT_SF4Y6) .pmic_BATLOW = 12, #else .pmic_BATLOW = 16, #endif .pmic_BATGD = 19, }; #endif static struct i2c_board_info fih_battery_i2c_board_info[] = { #ifdef CONFIG_DS2482 { I2C_BOARD_INFO("ds2482", 0x30 >> 1), .platform_data = &ds2482_pdata, }, #endif #ifdef CONFIG_BATTERY_BQ275X0 { I2C_BOARD_INFO("bq275x0-battery", 0xAA >> 1), .platform_data = &bq275x0_pdata, }, #ifdef CONFIG_BQ275X0_ROMMODE { I2C_BOARD_INFO("bq275x0-RomMode", 0x16 >> 1), }, #endif #endif }; static int fih_battery_hw_model(void) { int product_id = fih_get_product_id(); int product_phase = fih_get_product_phase(); if (product_id == Product_FB0 || product_id == Product_FD1) if (product_phase >= Product_EVB && product_phase < Product_PR231) return HWMODEL_GAUGE_DS2784; else return HWMODEL_GAUGE_BQ27500; else return HWMODEL_GAUGE_BQ27500; } /* * Assign caculate_capacity and get_battery_status function by HWID */ static void __init fih_battery_driver_init(void) { switch(fih_battery_hw_model()) { case HWMODEL_GAUGE_DS2784: #ifdef CONFIG_DS2482 i2c_register_board_info(0, &fih_battery_i2c_board_info[0], 1); #ifdef CONFIG_BATTERY_FIH_DS2784 msm_psy_batt_data.batt_info_if.get_batt_capacity = ds2784_batt_get_batt_capacity; msm_psy_batt_data.batt_info_if.get_batt_health = ds2784_batt_set_batt_health; msm_psy_batt_data.batt_info_if.get_batt_temp = ds2784_batt_get_batt_temp; msm_psy_batt_data.batt_info_if.get_batt_voltage = ds2784_batt_get_batt_voltage; #endif #endif break; case HWMODEL_GAUGE_BQ27500: default: #ifdef CONFIG_BATTERY_BQ275X0 #ifdef CONFIG_DS2482 i2c_register_board_info(0, &fih_battery_i2c_board_info[1], 1); #ifdef CONFIG_BQ275X0_ROMMODE i2c_register_board_info(0, &fih_battery_i2c_board_info[2], 1); #endif #else i2c_register_board_info(0, &fih_battery_i2c_board_info[0], 1); #ifdef CONFIG_BQ275X0_ROMMODE i2c_register_board_info(0, &fih_battery_i2c_board_info[1], 1); #endif #endif msm_psy_batt_data.batt_info_if.get_batt_capacity = bq275x0_battery_soc; msm_psy_batt_data.batt_info_if.get_batt_health = bq275x0_battery_health; msm_psy_batt_data.batt_info_if.get_batt_temp = bq275x0_battery_temperature; msm_psy_batt_data.batt_info_if.get_batt_voltage = bq275x0_battery_voltage; #endif } } #endif // DIV2-SW2-BSP-FBx-BATT+] static char *msm_adc_fluid_device_names[] = { "LTC_ADC1", "LTC_ADC2", "LTC_ADC3", }; static char *msm_adc_surf_device_names[] = { "XO_ADC", }; static struct msm_adc_platform_data msm_adc_pdata; static struct platform_device msm_adc_device = { .name = "msm_adc", .id = -1, .dev = { .platform_data = &msm_adc_pdata, }, }; #ifdef CONFIG_MSM_SDIO_AL static struct msm_gpio mdm2ap_status = { GPIO_CFG(77, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "mdm2ap_status" }; static int configure_mdm2ap_status(int on) { if (on) return msm_gpios_request_enable(&mdm2ap_status, 1); else { msm_gpios_disable_free(&mdm2ap_status, 1); return 0; } } static int get_mdm2ap_status(void) { return gpio_get_value(GPIO_PIN(mdm2ap_status.gpio_cfg)); } static struct sdio_al_platform_data sdio_al_pdata = { .config_mdm2ap_status = configure_mdm2ap_status, .get_mdm2ap_status = get_mdm2ap_status, .allow_sdioc_version_major_2 = 1, .peer_sdioc_version_minor = 0x0001, .peer_sdioc_version_major = 0x0003, .peer_sdioc_boot_version_minor = 0x0001, .peer_sdioc_boot_version_major = 0x0002, }; struct platform_device msm_device_sdio_al = { .name = "msm_sdio_al", .id = -1, .dev = { .platform_data = &sdio_al_pdata, }, }; #endif /* CONFIG_MSM_SDIO_AL */ // DIV2-SW2-BSP-FBx-LEDS+ #ifdef CONFIG_LEDS_FIH_FBX_PWM static struct leds_fbx_pwm_platform_data fbx_leds_pwm_pdata = { .r_led_ctl = 30 }; static struct platform_device fbx_leds_pwm_device = { .name = "fbx-leds-pwm", .id = -1, .dev = { .platform_data = &fbx_leds_pwm_pdata, }, }; #endif // DIV2-SW2-BSP-FBx-LEDS- //FIHTDC, Port keypad, MayLi, 2011.09.21 {+ #ifdef CONFIG_KEYBOARD_SF4H8 static struct sf8_kybd_platform_data sf8_kybd_pdata = { .pmic_gpio_vol_up = 0, .pmic_gpio_vol_dn = 1, .pmic_gpio_cover_det= 2, .sys_gpio_vol_up = PM8058_GPIO_PM_TO_SYS(0), .sys_gpio_vol_dn = PM8058_GPIO_PM_TO_SYS(1), .sys_gpio_cover_det = PM8058_GPIO_PM_TO_SYS(2), }; static struct platform_device sf8_kybd_device = { .name = "sf8_kybd", .id = -1, .dev = { .platform_data = &sf8_kybd_pdata, }, }; #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 -} //SW2-5-1-MP-DbgCfgTool-00+[ #ifdef CONFIG_ANDROID_RAM_CONSOLE #define RAM_CONSOLE_PHYS 0x7A00000 #define RAM_CONSOLE_SIZE 0x00020000 static struct resource ram_console_resources[1] = { [0] = { .start = RAM_CONSOLE_PHYS, .end = RAM_CONSOLE_PHYS + RAM_CONSOLE_SIZE - 1, .flags = IORESOURCE_MEM, }, }; static struct platform_device ram_console_device = { .name = "ram_console", .id = 0, .num_resources = ARRAY_SIZE(ram_console_resources), .resource = ram_console_resources, }; #endif #ifdef CONFIG_FIH_LAST_ALOG #ifdef CONFIG_ANDROID_RAM_CONSOLE #define ALOG_RAM_CONSOLE_PHYS_MAIN (RAM_CONSOLE_PHYS + RAM_CONSOLE_SIZE) #else #define ALOG_RAM_CONSOLE_PHYS_MAIN 0x7A20000 #endif #define ALOG_RAM_CONSOLE_SIZE_MAIN 0x00020000 //128KB #define ALOG_RAM_CONSOLE_PHYS_RADIO (ALOG_RAM_CONSOLE_PHYS_MAIN + ALOG_RAM_CONSOLE_SIZE_MAIN) #define ALOG_RAM_CONSOLE_SIZE_RADIO 0x00020000 //128KB #define ALOG_RAM_CONSOLE_PHYS_EVENTS (ALOG_RAM_CONSOLE_PHYS_RADIO + ALOG_RAM_CONSOLE_SIZE_RADIO) #define ALOG_RAM_CONSOLE_SIZE_EVENTS 0x00020000 //128KB #define ALOG_RAM_CONSOLE_PHYS_SYSTEM (ALOG_RAM_CONSOLE_PHYS_EVENTS + ALOG_RAM_CONSOLE_SIZE_EVENTS) #define ALOG_RAM_CONSOLE_SIZE_SYSTEM 0x00020000 //128KB static struct resource alog_ram_console_resources[4] = { [0] = { .name = "alog_main_buffer", .start = ALOG_RAM_CONSOLE_PHYS_MAIN, .end = ALOG_RAM_CONSOLE_PHYS_MAIN + ALOG_RAM_CONSOLE_SIZE_MAIN - 1, .flags = IORESOURCE_MEM, }, [1] = { .name = "alog_radio_buffer", .start = ALOG_RAM_CONSOLE_PHYS_RADIO, .end = ALOG_RAM_CONSOLE_PHYS_RADIO + ALOG_RAM_CONSOLE_SIZE_RADIO - 1, .flags = IORESOURCE_MEM, }, [2] = { .name = "alog_events_buffer", .start = ALOG_RAM_CONSOLE_PHYS_EVENTS, .end = ALOG_RAM_CONSOLE_PHYS_EVENTS + ALOG_RAM_CONSOLE_SIZE_EVENTS - 1, .flags = IORESOURCE_MEM, }, [3] = { .name = "alog_system_buffer", .start = ALOG_RAM_CONSOLE_PHYS_SYSTEM, .end = ALOG_RAM_CONSOLE_PHYS_SYSTEM + ALOG_RAM_CONSOLE_SIZE_SYSTEM - 1, .flags = IORESOURCE_MEM, }, }; static struct platform_device alog_ram_console_device = { .name = "alog_ram_console", .id = 0, .num_resources = ARRAY_SIZE(alog_ram_console_resources), .resource = alog_ram_console_resources, }; #endif //SW2-5-1-MP-DbgCfgTool-00+] static struct platform_device *devices[] __initdata = { #if defined(CONFIG_SERIAL_MSM) || defined(CONFIG_MSM_SERIAL_DEBUGGER) &msm_device_uart2, #endif &msm_device_smd, &msm_device_dmov, /* Div2-SW2-BSP-FBX-OW { */ #ifdef CONFIG_SMC91X &smc91x_device, #endif #ifdef CONFIG_SMSC911X &smsc911x_device, #endif /* } Div2-SW2-BSP-FBX-OW */ &msm_device_nand, #ifdef CONFIG_USB_FUNCTION &msm_device_hsusb_peripheral, &mass_storage_device, #endif #ifdef CONFIG_USB_MSM_OTG_72K &msm_device_otg, #ifdef CONFIG_USB_GADGET &msm_device_gadget_peripheral, #endif #endif #ifdef CONFIG_USB_ANDROID &usb_mass_storage_device, &rndis_device, #ifdef CONFIG_USB_ANDROID_DIAG &usb_diag_device, #endif &android_usb_device, #endif &qsd_device_spi, #ifdef CONFIG_I2C_SSBI &msm_device_ssbi6, &msm_device_ssbi7, #endif &android_pmem_device, &msm_fb_device, &msm_migrate_pages_device, //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 &mddi_toshiba_device, #endif //SW2-6-MM-JH-Unused_Display_Codes-00- //SW2-6-MM-JH-Display_Flag-00+ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT &lcdc_toshiba_panel_device, #endif //SW2-6-MM-JH-Display_Flag-00- #ifdef CONFIG_MSM_ROTATOR &msm_rotator_device, #endif //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 &lcdc_sharp_panel_device, #endif //SW2-6-MM-JH-Unused_Display_Codes-00- /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL &hdmi_adv7525_panel_device, #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ &android_pmem_kernel_ebi1_device, &android_pmem_adsp_device, &android_pmem_audio_device, &msm_device_i2c, &msm_device_i2c_2, &msm_device_uart_dm1, &hs_device, #ifdef CONFIG_MSM7KV2_AUDIO &msm_aictl_device, &msm_mi2s_device, &msm_lpa_device, &msm_aux_pcm_device, #endif &msm_device_adspdec, &qup_device_i2c, #if defined(CONFIG_MARIMBA_CORE) && \ (defined(CONFIG_MSM_BT_POWER) || defined(CONFIG_MSM_BT_POWER_MODULE)) &msm_bt_power_device, #endif // FihtdcCode@20110908 WeiChu add for WiFi porting begin // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_WLAN_POWER &bcm4329_wifi_power_device, #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +] // FIHTDC-SW2-Div6-CW-Project BCM4329 BLUETOOTH driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_BLUETOOTH_POWER &bcm4329_bt_power_device, &bcm4329_fm_power_device, #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 BLUETOOTH driver For SF8 +] // FihtdcCode@20110908 WeiChu add for WiFi porting end &msm_kgsl_3d0, #ifdef CONFIG_MSM_KGSL_2D &msm_kgsl_2d0, #endif #ifdef CONFIG_FIH_MT9P111 &msm_camera_sensor_mt9p111, #endif #ifdef CONFIG_FIH_HM0356 &msm_camera_sensor_hm0356, #endif #ifdef CONFIG_FIH_HM0357 &msm_camera_sensor_hm0357, #endif #ifdef CONFIG_FIH_TCM9001MD &msm_camera_sensor_tcm9001md, #endif #ifdef CONFIG_MT9T013 &msm_camera_sensor_mt9t013, #endif #ifdef CONFIG_MT9D112 &msm_camera_sensor_mt9d112, #endif #ifdef CONFIG_S5K3E2FX &msm_camera_sensor_s5k3e2fx, #endif #ifdef CONFIG_MT9P012 &msm_camera_sensor_mt9p012, #endif #ifdef CONFIG_MT9E013 &msm_camera_sensor_mt9e013, #endif #ifdef CONFIG_VX6953 &msm_camera_sensor_vx6953, #endif #ifdef CONFIG_SN12M0PZ &msm_camera_sensor_sn12m0pz, #endif &msm_device_vidc_720p, #ifdef CONFIG_MSM_GEMINI &msm_gemini_device, #endif #ifdef CONFIG_MSM_VPE &msm_vpe_device, #endif #if defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE) &msm_device_tsif, #endif #ifdef CONFIG_MSM_SDIO_AL &msm_device_sdio_al, #endif #if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \ defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE) &qcrypto_device, #endif #if defined(CONFIG_CRYPTO_DEV_QCEDEV) || \ defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE) &qcedev_device, #endif //SW2-D5-AriesHuang-SF4V5/SF4H8 porting keypad backlight +{ #if defined(CONFIG_FIH_PROJECT_SF4V5) || defined(CONFIG_FIH_PROJECT_SF4Y6) || defined(CONFIG_FIH_PROJECT_SF8) &msm_device_pmic_leds, #endif //SW2-D5-AriesHuang-SF4V5/SF4H8 porting keypad backlight +} &msm_batt_device, &msm_adc_device, &msm_ebi0_thermal, &msm_ebi1_thermal, #ifdef CONFIG_KEYBOARD_GPIO &gpio_buttons_device, // DIV2-SW2-BSP-FBx-BUTTONS #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 {+ #ifdef CONFIG_KEYBOARD_SF4H8 &sf8_kybd_device, #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 -} #ifdef CONFIG_LEDS_FIH_FBX_PWM &fbx_leds_pwm_device, // DIV2-SW2-BSP-FBx-LEDS #endif /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ &headset_sensor_device, /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ //SW2-5-1-MP-DbgCfgTool-00+[ #ifdef CONFIG_ANDROID_RAM_CONSOLE &ram_console_device, #endif #ifdef CONFIG_FIH_LAST_ALOG &alog_ram_console_device, #endif // FihtdcCode@20110908 WeiChu add for WiFi porting begin #if defined(CONFIG_BROADCOM_BCM4329) &msm_bluesleep_device, #endif // FihtdcCode@20110908 WeiChu add for WiFi porting end //SW2-5-1-MP-DbgCftTool-00+] }; static struct msm_gpio msm_i2c_gpios_hw[] = { { GPIO_CFG(70, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "i2c_scl" }, { GPIO_CFG(71, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "i2c_sda" }, }; static struct msm_gpio msm_i2c_gpios_io[] = { { GPIO_CFG(70, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "i2c_scl" }, { GPIO_CFG(71, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "i2c_sda" }, }; static struct msm_gpio qup_i2c_gpios_io[] = { { GPIO_CFG(16, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "qup_scl" }, { GPIO_CFG(17, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "qup_sda" }, }; static struct msm_gpio qup_i2c_gpios_hw[] = { { GPIO_CFG(16, 2, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "qup_scl" }, { GPIO_CFG(17, 2, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "qup_sda" }, }; static void msm_i2c_gpio_config(int adap_id, int config_type) { struct msm_gpio *msm_i2c_table; /* Each adapter gets 2 lines from the table */ if (adap_id > 0) return; if (config_type) msm_i2c_table = &msm_i2c_gpios_hw[adap_id*2]; else msm_i2c_table = &msm_i2c_gpios_io[adap_id*2]; msm_gpios_enable(msm_i2c_table, 2); } /*This needs to be enabled only for OEMS*/ #ifndef CONFIG_QUP_EXCLUSIVE_TO_CAMERA static struct vreg *qup_vreg; #endif static void qup_i2c_gpio_config(int adap_id, int config_type) { int rc = 0; struct msm_gpio *qup_i2c_table; /* Each adapter gets 2 lines from the table */ if (adap_id != 4) return; if (config_type) qup_i2c_table = qup_i2c_gpios_hw; else qup_i2c_table = qup_i2c_gpios_io; rc = msm_gpios_enable(qup_i2c_table, 2); if (rc < 0) printk(KERN_ERR "QUP GPIO enable failed: %d\n", rc); /*This needs to be enabled only for OEMS*/ #ifndef CONFIG_QUP_EXCLUSIVE_TO_CAMERA if (qup_vreg) { int rc = vreg_set_level(qup_vreg, 1800); if (rc) { pr_err("%s: vreg LVS1 set level failed (%d)\n", __func__, rc); } rc = vreg_enable(qup_vreg); if (rc) { pr_err("%s: vreg_enable() = %d \n", __func__, rc); } } #endif } static struct msm_i2c_platform_data msm_i2c_pdata = { .clk_freq = 100000, .pri_clk = 70, .pri_dat = 71, .rmutex = 1, .rsl_id = "D:I2C02000021", .msm_i2c_config_gpio = msm_i2c_gpio_config, }; /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ static void __init msm_device_i2c_power_domain(void) { struct vreg *vreg_ldo12; struct vreg *vreg_ldo8; ///i2c_gpio_power //DIV5-BSP-CH-SF6-SENSOR-PORTING00++[ //Div2D5-OwenHuang-I2C-Enable_Bus_VDDIO-00+{ #if defined(CONFIG_FIH_PROJECT_SF4Y6) || defined(CONFIG_FIH_PROJECT_SF4V5) //Div2D5-OwenHuang-SF5_ALSPS_Vreg_GP7_Setting-01* //Div2D5-OwenHuang-SF5_Reset_L8-00* struct vreg *vreg_gp7; #endif //Div2D5-OwenHuang-I2C-Enable_Bus_VDDIO-00+} //DIV5-BSP-CH-SF6-SENSOR-PORTING00++] int rc; /* 1.8V -- LDO12 */ vreg_ldo12 = vreg_get(NULL, "gp9"); if (IS_ERR(vreg_ldo12)) { pr_err("%s: gp9 vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_ldo12)); return; } rc = vreg_set_level(vreg_ldo12, 3000); if (rc) { pr_err("%s: vreg LDO12 set level failed (%d)\n", __func__, rc); return; } rc = vreg_enable(vreg_ldo12); if (rc) { pr_err("%s: LDO12 vreg enable failed (%d)\n", __func__, rc); return; } /* VDDIO 1.8V -- LDO8*/ ///i2c_gpio_power vreg_ldo8 = vreg_get(NULL, "gp7"); if (IS_ERR(vreg_ldo8)) { rc = PTR_ERR(vreg_ldo8); printk("%s: gp7 vreg get failed (%d)\n", __func__, rc); return; } rc = vreg_set_level(vreg_ldo8, 1800); if (rc) { printk("%s: vreg LDO8 set level failed (%d)\n", __func__, rc); return; } rc = vreg_enable(vreg_ldo8); if (rc) { pr_err("%s: LDO8 vreg enable failed (%d)\n", __func__, rc); return; } //DIV5-BSP-CH-SF6-SENSOR-PORTING00++[ //Div2D5-OwenHuang-I2C-Enable_Bus_VDDIO-00+{ #if defined(CONFIG_FIH_PROJECT_SF4Y6) || defined(CONFIG_FIH_PROJECT_SF4V5) //Div2D5-OwenHuang-SF5_ALSPS_Vreg_GP7_Setting-01* //Div2D5-OwenHuang-SF5_Reset_L8-00* vreg_gp7 = vreg_get(NULL, "gp7"); if (IS_ERR(vreg_gp7)) { pr_err("%s: gp7 vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_gp7)); return; } rc = vreg_set_level(vreg_gp7, 1800); if (rc) { pr_err("%s: vreg gp7 set level failed (%d)\n", __func__, rc); return; } //Div2D5-OwenHuang-SF5_Reset_L8-00-{ /*rc = vreg_enable(vreg_gp7); if (rc) { pr_err("%s: gp7 vreg enable failed (%d)\n", __func__, rc); return; }*/ //Div2D5-OwenHuang-SF5_Reset_L8-00-} vreg_pull_down_switch(vreg_gp7, 1); //Div2D5-OwenHuang-SF5_Reset_L8-00+ //Div2D5-OwenHuang-SF6_AKM8975C-Framework_Porting-04+{ //reset again to ensure light sensor can initialize successfully rc = vreg_disable(vreg_gp7); if (rc) { pr_err("%s: gp7 vreg enable failed (%d)\n", __func__, rc); return; } printk(KERN_INFO "%s, shutdown vreg_gp7\n", __func__); msleep(100); printk(KERN_INFO "%s, Power-on vreg_gp7\n", __func__); rc = vreg_enable(vreg_gp7); if (rc) { pr_err("%s: gp7 vreg enable failed (%d)\n", __func__, rc); return; } //Div2D5-OwenHuang-SF6_AKM8975C-Framework_Porting-04+} vreg_gp7 = NULL; #endif //Div2D5-OwenHuang-I2C-Enable_Bus_VDDIO-00+} //DIV5-BSP-CH-SF6-SENSOR-PORTING00++] } /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ static void __init msm_device_i2c_init(void) { if (msm_gpios_request(msm_i2c_gpios_hw, ARRAY_SIZE(msm_i2c_gpios_hw))) pr_err("failed to request I2C gpios\n"); msm_device_i2c.dev.platform_data = &msm_i2c_pdata; } static struct msm_i2c_platform_data msm_i2c_2_pdata = { .clk_freq = 100000, .rmutex = 1, .rsl_id = "D:I2C02000022", .msm_i2c_config_gpio = msm_i2c_gpio_config, }; static void __init msm_device_i2c_2_init(void) { msm_device_i2c_2.dev.platform_data = &msm_i2c_2_pdata; } static struct msm_i2c_platform_data qup_i2c_pdata = { .clk_freq = 384000, .pclk = "camif_pad_pclk", .msm_i2c_config_gpio = qup_i2c_gpio_config, }; static void __init qup_device_i2c_init(void) { if (msm_gpios_request(qup_i2c_gpios_hw, ARRAY_SIZE(qup_i2c_gpios_hw))) pr_err("failed to request I2C gpios\n"); qup_device_i2c.dev.platform_data = &qup_i2c_pdata; /*This needs to be enabled only for OEMS*/ #ifndef CONFIG_QUP_EXCLUSIVE_TO_CAMERA qup_vreg = vreg_get(NULL, "lvsw1"); if (IS_ERR(qup_vreg)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(qup_vreg)); } #endif } #ifdef CONFIG_I2C_SSBI static struct msm_ssbi_platform_data msm_i2c_ssbi6_pdata = { .rsl_id = "D:PMIC_SSBI", .controller_type = MSM_SBI_CTRL_SSBI2, }; static struct msm_ssbi_platform_data msm_i2c_ssbi7_pdata = { .rsl_id = "D:CODEC_SSBI", .controller_type = MSM_SBI_CTRL_SSBI, }; #endif static struct msm_acpu_clock_platform_data msm7x30_clock_data = { .acpu_switch_time_us = 50, .vdd_switch_time_us = 62, }; static void __init msm7x30_init_irq(void) { msm_init_irq(); } static struct msm_gpio msm_nand_ebi2_cfg_data[] = { {GPIO_CFG(86, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "ebi2_cs1"}, {GPIO_CFG(115, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "ebi2_busy1"}, }; struct vreg *vreg_s3; struct vreg *vreg_mmc; #if (defined(CONFIG_MMC_MSM_SDC1_SUPPORT)\ || defined(CONFIG_MMC_MSM_SDC2_SUPPORT)\ || defined(CONFIG_MMC_MSM_SDC3_SUPPORT)\ || defined(CONFIG_MMC_MSM_SDC4_SUPPORT)) struct sdcc_gpio { struct msm_gpio *cfg_data; uint32_t size; struct msm_gpio *sleep_cfg_data; }; #if defined(CONFIG_MMC_MSM_SDC1_SUPPORT) static struct msm_gpio sdc1_lvlshft_cfg_data[] = { {GPIO_CFG(35, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_16MA), "sdc1_lvlshft"}, }; #endif static struct msm_gpio sdc1_cfg_data[] = { {GPIO_CFG(38, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "sdc1_clk"}, #ifndef CONFIG_FIH_AAT1272 {GPIO_CFG(39, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_cmd"}, #endif {GPIO_CFG(39, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_cmd"}, {GPIO_CFG(40, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_dat_3"}, {GPIO_CFG(41, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_dat_2"}, {GPIO_CFG(42, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_dat_1"}, {GPIO_CFG(43, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_dat_0"}, }; static struct msm_gpio sdc2_cfg_data[] = { {GPIO_CFG(64, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "sdc2_clk"}, {GPIO_CFG(65, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_cmd"}, {GPIO_CFG(66, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_3"}, {GPIO_CFG(67, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_2"}, {GPIO_CFG(68, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_1"}, {GPIO_CFG(69, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_0"}, #ifdef CONFIG_MMC_MSM_SDC2_8_BIT_SUPPORT {GPIO_CFG(115, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_4"}, {GPIO_CFG(114, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_5"}, {GPIO_CFG(113, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_6"}, {GPIO_CFG(112, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_7"}, #endif }; static struct msm_gpio sdc3_cfg_data[] = { {GPIO_CFG(110, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "sdc3_clk"}, {GPIO_CFG(111, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_cmd"}, {GPIO_CFG(116, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_dat_3"}, {GPIO_CFG(117, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_dat_2"}, {GPIO_CFG(118, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_dat_1"}, {GPIO_CFG(119, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_dat_0"}, }; static struct msm_gpio sdc3_sleep_cfg_data[] = { {GPIO_CFG(110, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_clk"}, {GPIO_CFG(111, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_cmd"}, {GPIO_CFG(116, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_dat_3"}, {GPIO_CFG(117, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_dat_2"}, {GPIO_CFG(118, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_dat_1"}, {GPIO_CFG(119, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_dat_0"}, }; static struct msm_gpio sdc4_cfg_data[] = { {GPIO_CFG(58, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "sdc4_clk"}, {GPIO_CFG(59, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_cmd"}, {GPIO_CFG(60, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_dat_3"}, {GPIO_CFG(61, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_dat_2"}, {GPIO_CFG(62, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_dat_1"}, {GPIO_CFG(63, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_dat_0"}, }; static struct sdcc_gpio sdcc_cfg_data[] = { { .cfg_data = sdc1_cfg_data, .size = ARRAY_SIZE(sdc1_cfg_data), .sleep_cfg_data = NULL, }, { .cfg_data = sdc2_cfg_data, .size = ARRAY_SIZE(sdc2_cfg_data), .sleep_cfg_data = NULL, }, { .cfg_data = sdc3_cfg_data, .size = ARRAY_SIZE(sdc3_cfg_data), .sleep_cfg_data = sdc3_sleep_cfg_data, }, { .cfg_data = sdc4_cfg_data, .size = ARRAY_SIZE(sdc4_cfg_data), .sleep_cfg_data = NULL, }, }; struct sdcc_vreg { struct vreg *vreg_data; unsigned level; }; static struct sdcc_vreg sdcc_vreg_data[4]; static unsigned long vreg_sts, gpio_sts; static uint32_t msm_sdcc_setup_gpio(int dev_id, unsigned int enable) { int rc = 0; struct sdcc_gpio *curr; curr = &sdcc_cfg_data[dev_id - 1]; if (!(test_bit(dev_id, &gpio_sts)^enable)) return rc; if (enable) { set_bit(dev_id, &gpio_sts); rc = msm_gpios_request_enable(curr->cfg_data, curr->size); if (rc) printk(KERN_ERR "%s: Failed to turn on GPIOs for slot %d\n", __func__, dev_id); } else { clear_bit(dev_id, &gpio_sts); if (curr->sleep_cfg_data) { msm_gpios_enable(curr->sleep_cfg_data, curr->size); msm_gpios_free(curr->sleep_cfg_data, curr->size); } else { msm_gpios_disable_free(curr->cfg_data, curr->size); } } return rc; } static uint32_t msm_sdcc_setup_vreg(int dev_id, unsigned int enable) { int rc = 0; struct sdcc_vreg *curr; static int enabled_once[] = {0, 0, 0, 0}; curr = &sdcc_vreg_data[dev_id - 1]; if (!(test_bit(dev_id, &vreg_sts)^enable)) return rc; if (!enable || enabled_once[dev_id - 1]) return 0; if (enable) { set_bit(dev_id, &vreg_sts); rc = vreg_set_level(curr->vreg_data, curr->level); if (rc) { printk(KERN_ERR "%s: vreg_set_level() = %d \n", __func__, rc); } rc = vreg_enable(curr->vreg_data); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); } enabled_once[dev_id - 1] = 1; } else { clear_bit(dev_id, &vreg_sts); rc = vreg_disable(curr->vreg_data); if (rc) { printk(KERN_ERR "%s: vreg_disable() = %d \n", __func__, rc); } } return rc; } static uint32_t msm_sdcc_setup_power(struct device *dv, unsigned int vdd) { int rc = 0; struct platform_device *pdev; pdev = container_of(dv, struct platform_device, dev); rc = msm_sdcc_setup_gpio(pdev->id, (vdd ? 1 : 0)); if (rc) goto out; if (pdev->id == 4) /* S3 is always ON and cannot be disabled */ rc = msm_sdcc_setup_vreg(pdev->id, (vdd ? 1 : 0)); out: return rc; } #if defined(CONFIG_MMC_MSM_SDC1_SUPPORT) && \ defined(CONFIG_CSDIO_VENDOR_ID) && \ defined(CONFIG_CSDIO_DEVICE_ID) && \ (CONFIG_CSDIO_VENDOR_ID == 0x70 && CONFIG_CSDIO_DEVICE_ID == 0x1117) #define MBP_ON 1 #define MBP_OFF 0 #define MBP_RESET_N \ GPIO_CFG(44, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA) #define MBP_INT0 \ GPIO_CFG(46, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA) #define MBP_MODE_CTRL_0 \ GPIO_CFG(35, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) #define MBP_MODE_CTRL_1 \ GPIO_CFG(36, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) #define MBP_MODE_CTRL_2 \ GPIO_CFG(34, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) #define TSIF_EN \ GPIO_CFG(35, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_DATA \ GPIO_CFG(36, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_CLK \ GPIO_CFG(34, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) static struct msm_gpio mbp_cfg_data[] = { {GPIO_CFG(44, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "mbp_reset"}, {GPIO_CFG(85, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "mbp_io_voltage"}, }; static int mbp_config_gpios_pre_init(int enable) { int rc = 0; if (enable) { rc = msm_gpios_request_enable(mbp_cfg_data, ARRAY_SIZE(mbp_cfg_data)); if (rc) { printk(KERN_ERR "%s: Failed to turnon GPIOs for mbp chip(%d)\n", __func__, rc); } } else msm_gpios_disable_free(mbp_cfg_data, ARRAY_SIZE(mbp_cfg_data)); return rc; } static int mbp_setup_rf_vregs(int state) { struct vreg *vreg_rf = NULL; struct vreg *vreg_rf_switch = NULL; int rc; vreg_rf = vreg_get(NULL, "s2"); if (IS_ERR(vreg_rf)) { pr_err("%s: s2 vreg get failed (%ld)", __func__, PTR_ERR(vreg_rf)); return -EFAULT; } vreg_rf_switch = vreg_get(NULL, "rf"); if (IS_ERR(vreg_rf_switch)) { pr_err("%s: rf vreg get failed (%ld)", __func__, PTR_ERR(vreg_rf_switch)); return -EFAULT; } if (state) { rc = vreg_set_level(vreg_rf, 1300); if (rc) { pr_err("%s: vreg s2 set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_rf); if (rc) { printk(KERN_ERR "%s: vreg_enable(s2) = %d\n", __func__, rc); } rc = vreg_set_level(vreg_rf_switch, 2600); if (rc) { pr_err("%s: vreg rf switch set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_rf_switch); if (rc) { printk(KERN_ERR "%s: vreg_enable(rf) = %d\n", __func__, rc); } } else { (void) vreg_disable(vreg_rf); (void) vreg_disable(vreg_rf_switch); } return 0; } static int mbp_setup_vregs(int state) { struct vreg *vreg_analog = NULL; struct vreg *vreg_io = NULL; int rc; vreg_analog = vreg_get(NULL, "gp4"); if (IS_ERR(vreg_analog)) { pr_err("%s: gp4 vreg get failed (%ld)", __func__, PTR_ERR(vreg_analog)); return -EFAULT; } vreg_io = vreg_get(NULL, "s3"); if (IS_ERR(vreg_io)) { pr_err("%s: s3 vreg get failed (%ld)", __func__, PTR_ERR(vreg_io)); return -EFAULT; } if (state) { rc = vreg_set_level(vreg_analog, 2600); if (rc) { pr_err("%s: vreg_set_level failed (%d)", __func__, rc); } rc = vreg_enable(vreg_analog); if (rc) { pr_err("%s: analog vreg enable failed (%d)", __func__, rc); } rc = vreg_set_level(vreg_io, 1800); if (rc) { pr_err("%s: vreg_set_level failed (%d)", __func__, rc); } rc = vreg_enable(vreg_io); if (rc) { pr_err("%s: io vreg enable failed (%d)", __func__, rc); } } else { rc = vreg_disable(vreg_analog); if (rc) { pr_err("%s: analog vreg disable failed (%d)", __func__, rc); } rc = vreg_disable(vreg_io); if (rc) { pr_err("%s: io vreg disable failed (%d)", __func__, rc); } } return rc; } static int mbp_set_tcxo_en(int enable) { int rc; const char *id = "UBMC"; struct vreg *vreg_analog = NULL; rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_A1, enable ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); if (rc < 0) { printk(KERN_ERR "%s: unable to %svote for a1 clk\n", __func__, enable ? "" : "de-"); return -EIO; } if (!enable) { vreg_analog = vreg_get(NULL, "gp4"); if (IS_ERR(vreg_analog)) { pr_err("%s: gp4 vreg get failed (%ld)", __func__, PTR_ERR(vreg_analog)); return -EFAULT; } (void) vreg_disable(vreg_analog); } return rc; } static void mbp_set_freeze_io(int state) { if (state) gpio_set_value(85, 0); else gpio_set_value(85, 1); } static int mbp_set_core_voltage_en(int enable) { int rc; struct vreg *vreg_core1p2 = NULL; vreg_core1p2 = vreg_get(NULL, "gp16"); if (IS_ERR(vreg_core1p2)) { pr_err("%s: gp16 vreg get failed (%ld)", __func__, PTR_ERR(vreg_core1p2)); return -EFAULT; } if (enable) { rc = vreg_set_level(vreg_core1p2, 1200); if (rc) { pr_err("%s: vreg_set_level failed (%d)", __func__, rc); } (void) vreg_enable(vreg_core1p2); return 80; } else { gpio_set_value(85, 1); return 0; } return rc; } static void mbp_set_reset(int state) { if (state) gpio_set_value(GPIO_PIN(MBP_RESET_N), 0); else gpio_set_value(GPIO_PIN(MBP_RESET_N), 1); } static int mbp_config_interface_mode(int state) { if (state) { gpio_tlmm_config(MBP_MODE_CTRL_0, GPIO_CFG_ENABLE); gpio_tlmm_config(MBP_MODE_CTRL_1, GPIO_CFG_ENABLE); gpio_tlmm_config(MBP_MODE_CTRL_2, GPIO_CFG_ENABLE); gpio_set_value(GPIO_PIN(MBP_MODE_CTRL_0), 0); gpio_set_value(GPIO_PIN(MBP_MODE_CTRL_1), 1); gpio_set_value(GPIO_PIN(MBP_MODE_CTRL_2), 0); } else { gpio_tlmm_config(MBP_MODE_CTRL_0, GPIO_CFG_DISABLE); gpio_tlmm_config(MBP_MODE_CTRL_1, GPIO_CFG_DISABLE); gpio_tlmm_config(MBP_MODE_CTRL_2, GPIO_CFG_DISABLE); } return 0; } static int mbp_setup_adc_vregs(int state) { struct vreg *vreg_adc = NULL; int rc; vreg_adc = vreg_get(NULL, "s4"); if (IS_ERR(vreg_adc)) { pr_err("%s: s4 vreg get failed (%ld)", __func__, PTR_ERR(vreg_adc)); return -EFAULT; } if (state) { rc = vreg_set_level(vreg_adc, 2200); if (rc) { pr_err("%s: vreg_set_level failed (%d)", __func__, rc); } rc = vreg_enable(vreg_adc); if (rc) { pr_err("%s: enable vreg adc failed (%d)", __func__, rc); } } else { rc = vreg_disable(vreg_adc); if (rc) { pr_err("%s: disable vreg adc failed (%d)", __func__, rc); } } return rc; } static int mbp_power_up(void) { int rc; rc = mbp_config_gpios_pre_init(MBP_ON); if (rc) goto exit; pr_debug("%s: mbp_config_gpios_pre_init() done\n", __func__); rc = mbp_setup_vregs(MBP_ON); if (rc) goto exit; pr_debug("%s: gp4 (2.6) and s3 (1.8) done\n", __func__); rc = mbp_set_tcxo_en(MBP_ON); if (rc) goto exit; pr_debug("%s: tcxo clock done\n", __func__); mbp_set_freeze_io(MBP_OFF); pr_debug("%s: set gpio 85 to 1 done\n", __func__); udelay(100); mbp_set_reset(MBP_ON); udelay(300); rc = mbp_config_interface_mode(MBP_ON); if (rc) goto exit; pr_debug("%s: mbp_config_interface_mode() done\n", __func__); udelay(100 + mbp_set_core_voltage_en(MBP_ON)); pr_debug("%s: power gp16 1.2V done\n", __func__); mbp_set_freeze_io(MBP_ON); pr_debug("%s: set gpio 85 to 0 done\n", __func__); udelay(100); rc = mbp_setup_rf_vregs(MBP_ON); if (rc) goto exit; pr_debug("%s: s2 1.3V and rf 2.6V done\n", __func__); rc = mbp_setup_adc_vregs(MBP_ON); if (rc) goto exit; pr_debug("%s: s4 2.2V done\n", __func__); udelay(200); mbp_set_reset(MBP_OFF); pr_debug("%s: close gpio 44 done\n", __func__); msleep(20); exit: return rc; } static int mbp_power_down(void) { int rc; struct vreg *vreg_adc = NULL; vreg_adc = vreg_get(NULL, "s4"); if (IS_ERR(vreg_adc)) { pr_err("%s: s4 vreg get failed (%ld)", __func__, PTR_ERR(vreg_adc)); return -EFAULT; } mbp_set_reset(MBP_ON); pr_debug("%s: mbp_set_reset(MBP_ON) done\n", __func__); udelay(100); rc = mbp_setup_adc_vregs(MBP_OFF); if (rc) goto exit; pr_debug("%s: vreg_disable(vreg_adc) done\n", __func__); udelay(5); rc = mbp_setup_rf_vregs(MBP_OFF); if (rc) goto exit; pr_debug("%s: mbp_setup_rf_vregs(MBP_OFF) done\n", __func__); udelay(5); mbp_set_freeze_io(MBP_OFF); pr_debug("%s: mbp_set_freeze_io(MBP_OFF) done\n", __func__); udelay(100); rc = mbp_set_core_voltage_en(MBP_OFF); if (rc) goto exit; pr_debug("%s: mbp_set_core_voltage_en(MBP_OFF) done\n", __func__); gpio_set_value(85, 1); rc = mbp_set_tcxo_en(MBP_OFF); if (rc) goto exit; pr_debug("%s: mbp_set_tcxo_en(MBP_OFF) done\n", __func__); rc = mbp_config_gpios_pre_init(MBP_OFF); if (rc) goto exit; exit: return rc; } static void (*mbp_status_notify_cb)(int card_present, void *dev_id); static void *mbp_status_notify_cb_devid; static int mbp_power_status; static int mbp_power_init_done; static uint32_t mbp_setup_power(struct device *dv, unsigned int power_status) { int rc = 0; struct platform_device *pdev; pdev = container_of(dv, struct platform_device, dev); if (power_status == mbp_power_status) goto exit; if (power_status) { pr_debug("turn on power of mbp slot"); rc = mbp_power_up(); mbp_power_status = 1; } else { pr_debug("turn off power of mbp slot"); rc = mbp_power_down(); mbp_power_status = 0; } exit: return rc; }; int mbp_register_status_notify(void (*callback)(int, void *), void *dev_id) { mbp_status_notify_cb = callback; mbp_status_notify_cb_devid = dev_id; return 0; } static unsigned int mbp_status(struct device *dev) { return mbp_power_status; } static uint32_t msm_sdcc_setup_power_mbp(struct device *dv, unsigned int vdd) { struct platform_device *pdev; uint32_t rc = 0; pdev = container_of(dv, struct platform_device, dev); rc = msm_sdcc_setup_power(dv, vdd); if (rc) { pr_err("%s: Failed to setup power (%d)\n", __func__, rc); goto out; } if (!mbp_power_init_done) { mbp_setup_power(dv, 1); mbp_setup_power(dv, 0); mbp_power_init_done = 1; } if (vdd >= 0x8000) { rc = mbp_setup_power(dv, (0x8000 == vdd) ? 0 : 1); if (rc) { pr_err("%s: Failed to config mbp chip power (%d)\n", __func__, rc); goto out; } if (mbp_status_notify_cb) { mbp_status_notify_cb(mbp_power_status, mbp_status_notify_cb_devid); } } out: /* should return 0 only */ return 0; } #endif #endif #ifdef CONFIG_MMC_MSM_SDC4_SUPPORT #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION static unsigned int msm7x30_sdcc_slot_status(struct device *dev) { return (unsigned int)!gpio_get_value(sd_detect_pin); } #endif static void msm_sdcc_sdio_lpm_gpio(struct device *dv, unsigned int active) { pr_debug("%s not implemented\n", __func__); } static int msm_sdcc_get_wpswitch(struct device *dv) { void __iomem *wp_addr = 0; uint32_t ret = 0; struct platform_device *pdev; if (!(machine_is_msm7x30_surf())) return -1; pdev = container_of(dv, struct platform_device, dev); wp_addr = ioremap(FPGA_SDCC_STATUS, 4); if (!wp_addr) { pr_err("%s: Could not remap %x\n", __func__, FPGA_SDCC_STATUS); return -ENOMEM; } ret = (((readl(wp_addr) >> 4) >> (pdev->id-1)) & 0x01); pr_info("%s: WP Status for Slot %d = 0x%x \n", __func__, pdev->id, ret); iounmap(wp_addr); return ret; } #endif #if defined(CONFIG_MMC_MSM_SDC1_SUPPORT) #if defined(CONFIG_CSDIO_VENDOR_ID) && \ defined(CONFIG_CSDIO_DEVICE_ID) && \ (CONFIG_CSDIO_VENDOR_ID == 0x70 && CONFIG_CSDIO_DEVICE_ID == 0x1117) static struct mmc_platform_data msm7x30_sdc1_data = { .ocr_mask = MMC_VDD_165_195 | MMC_VDD_27_28 | MMC_VDD_28_29, .translate_vdd = msm_sdcc_setup_power_mbp, .mmc_bus_width = MMC_CAP_4_BIT_DATA, .status = mbp_status, .register_status_notify = mbp_register_status_notify, #ifdef CONFIG_MMC_MSM_SDC1_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 24576000, .nonremovable = 0, }; #else static struct mmc_platform_data msm7x30_sdc1_data = { .ocr_mask = MMC_VDD_165_195, .translate_vdd = msm_sdcc_setup_power, .mmc_bus_width = MMC_CAP_4_BIT_DATA, #ifdef CONFIG_MMC_MSM_SDC1_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .nonremovable = 0, }; #endif #endif #ifdef CONFIG_MMC_MSM_SDC2_SUPPORT static struct mmc_platform_data msm7x30_sdc2_data = { .ocr_mask = MMC_VDD_165_195 | MMC_VDD_27_28, .translate_vdd = msm_sdcc_setup_power, #ifdef CONFIG_MMC_MSM_SDC2_8_BIT_SUPPORT .mmc_bus_width = MMC_CAP_8_BIT_DATA, #else .mmc_bus_width = MMC_CAP_4_BIT_DATA, #endif #ifdef CONFIG_MMC_MSM_SDC2_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .nonremovable = 1, }; #endif #ifdef CONFIG_MMC_MSM_SDC3_SUPPORT static struct mmc_platform_data msm7x30_sdc3_data = { .ocr_mask = MMC_VDD_27_28 | MMC_VDD_28_29, .translate_vdd = msm_sdcc_setup_power, .mmc_bus_width = MMC_CAP_4_BIT_DATA, #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT .sdiowakeup_irq = MSM_GPIO_TO_INT(118), #endif #ifdef CONFIG_MMC_MSM_SDC3_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .nonremovable = 0, }; #endif #ifdef CONFIG_MMC_MSM_SDC4_SUPPORT static struct mmc_platform_data msm7x30_sdc4_data = { .ocr_mask = MMC_VDD_27_28 | MMC_VDD_28_29, .translate_vdd = msm_sdcc_setup_power, .mmc_bus_width = MMC_CAP_4_BIT_DATA, #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION .status = msm7x30_sdcc_slot_status, .status_irq = PM8058_GPIO_IRQ(PMIC8058_IRQ_BASE, PMIC_GPIO_SD_DET - 1), .irq_flags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, #endif .wpswitch = msm_sdcc_get_wpswitch, #ifdef CONFIG_MMC_MSM_SDC4_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .nonremovable = 0, }; #endif #ifdef CONFIG_MMC_MSM_SDC1_SUPPORT static void msm_sdc1_lvlshft_enable(void) { int rc; /* Enable LDO5, an input to the FET that powers slot 1 */ rc = vreg_set_level(vreg_mmc, 2850); if (rc) printk(KERN_ERR "%s: vreg_set_level() = %d \n", __func__, rc); rc = vreg_enable(vreg_mmc); if (rc) printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); /* Enable GPIO 35, to turn on the FET that powers slot 1 */ rc = msm_gpios_request_enable(sdc1_lvlshft_cfg_data, ARRAY_SIZE(sdc1_lvlshft_cfg_data)); if (rc) printk(KERN_ERR "%s: Failed to enable GPIO 35\n", __func__); rc = gpio_direction_output(GPIO_PIN(sdc1_lvlshft_cfg_data[0].gpio_cfg), 1); if (rc) printk(KERN_ERR "%s: Failed to turn on GPIO 35\n", __func__); } #endif /* FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized { */ #ifdef CONFIG_FIH_FXX #include <linux/ctype.h> //Div6D1-JL-FixWrongID #include "proc_comm.h" #define NV_PRD_ID_I 50001 #define NV_FIH_USB_DEVICE_CUSTOMER_I 50034 int fih_usb_full_func = 0xC000; struct usb_device_custom_nv { uint32_t magic_num; uint16_t vendor_id; uint16_t product_id; char product_name[32]; char manufacturer_name[32]; char reserved[52]; }; static int sync_from_custom_nv(void) { uint32_t smem_proc_comm_oem_cmd1 = PCOM_CUSTOMER_CMD1; uint32_t smem_proc_comm_oem_data1 = SMEM_PROC_COMM_OEM_NV_READ; uint32_t smem_proc_comm_oem_data2 = NV_PRD_ID_I; uint32_t product_id[32]; char serial_number[32]; struct usb_device_custom_nv usb_product;//Div2-5-3-Peripheral-LL-UsbCustomized-00+ struct smem_host_oem_info *usb_type_info = NULL; unsigned int info_size; int len = 0; int i; char *src; char *k_serial; usb_type_info = smem_get_entry(SMEM_ID_VENDOR2, &info_size); if(usb_type_info) { android_usb_pdata.product_id = usb_type_info->host_usb_id; } if(msm_proc_comm_oem(smem_proc_comm_oem_cmd1, &smem_proc_comm_oem_data1, product_id, &smem_proc_comm_oem_data2) == 0) { memcpy(serial_number, product_id, sizeof(serial_number)); len = strlen(serial_number); if(len > 0) { //strlcpy(serial_number, (char*)product_id, sizeof(serial_number)); printk(KERN_INFO"%s: read serial number (%s)\n",__func__, serial_number); src = serial_number; //eliminate space char from string start index while(isspace(*src)) { src++; } k_serial = (char*)kzalloc(16, GFP_KERNEL); strlcpy(k_serial, src, 16+1); src = k_serial; //end of non alpha and number character while(isalnum(*src)) { src++; } *src = '\0'; if(strlen(k_serial)){ android_usb_pdata.serial_number = k_serial; } } } src = android_usb_pdata.serial_number; rndis_pdata.ethaddr[0] = 0x02; for (i = 0; *src; i++) { /* XOR the USB serial across the remaining bytes */ rndis_pdata.ethaddr[i % (ETH_ALEN - 1) + 1] ^= *src++; } //Div2-5-3-Peripheral-LL-UsbCustomized-01*{ smem_proc_comm_oem_data2 = NV_FIH_USB_DEVICE_CUSTOMER_I; if(msm_proc_comm_oem(smem_proc_comm_oem_cmd1, &smem_proc_comm_oem_data1, product_id, &smem_proc_comm_oem_data2) == 0) { memcpy(&usb_product, product_id, sizeof(usb_product)); printk(KERN_INFO"%s: USB MAGIC NUMBER (%d)", __func__, usb_product.magic_num); if(usb_product.magic_num == 0x12345678) {//magic number must be 0x12345678 could be effective printk(KERN_INFO"%s: USB CUSTOMIZED VID(0X%X) PID(0X%X) PRODUCT(%s) MANUFACTURER(%s)\n", __func__, usb_product.vendor_id, usb_product.product_id, usb_product.product_name, usb_product.manufacturer_name); if(usb_product.vendor_id && usb_product.product_id) { android_usb_pdata.vendor_id = usb_product.vendor_id; if(android_usb_pdata.vendor_id == 0x12d1) {//huawei fih_usb_full_func = 0x1021;//open all usb functions android_usb_pdata.num_products = ARRAY_SIZE(usb_products_12d1); android_usb_pdata.products = usb_products_12d1; if(android_usb_pdata.product_id == 0xc002) {//recovery mode android_usb_pdata.product_id = 0x1022; } else if(android_usb_pdata.product_id == 0xc000) {//diag debug mode enable android_usb_pdata.product_id = 0x1021; } else { android_usb_pdata.product_id = usb_product.product_id; } } } if(strlen(usb_product.product_name)) { k_serial = (char*)kzalloc(32, GFP_KERNEL); strlcpy(k_serial, usb_product.product_name, sizeof(usb_product.product_name)); src = k_serial; while(isalnum(*src)||isspace(*src)) { src++; } *src = '\0'; if(strlen(k_serial)) { android_usb_pdata.product_name = k_serial; } } if(strlen(usb_product.manufacturer_name)) { k_serial = (char*)kzalloc(32, GFP_KERNEL); strlcpy(k_serial, usb_product.manufacturer_name, sizeof(usb_product.manufacturer_name)); src = k_serial; while(isalnum(*src)||isspace(*src)) { src++; } *src = '\0'; if(strlen(k_serial)) { android_usb_pdata.manufacturer_name = k_serial; rndis_pdata.vendorDescr = k_serial; mass_storage_pdata.vendor = k_serial; } } } } #ifdef CONFIG_FIH_FTM if(android_usb_pdata.vendor_id == 0x12d1) {//Huawei android_usb_pdata.product_id = 0x1023; } else if(android_usb_pdata.vendor_id == 0x489) {//FIH android_usb_pdata.product_id = 0xc003; } android_usb_pdata.serial_number = 0; //set serial number NULL #endif printk(KERN_INFO"%s: USB VID(0x%X) PID(0x%X) PRODUCT(%s) MANUFACTURER(%s) SN(%s)\n", __func__, android_usb_pdata.vendor_id, android_usb_pdata.product_id, android_usb_pdata.product_name, android_usb_pdata.manufacturer_name, android_usb_pdata.serial_number); //Div2-5-3-Peripheral-LL-UsbCustomized-01*} return 1; } #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized */ static void __init msm7x30_init_mmc(void) { vreg_s3 = vreg_get(NULL, "s3"); if (IS_ERR(vreg_s3)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_s3)); return; } vreg_mmc = vreg_get(NULL, "mmc"); if (IS_ERR(vreg_mmc)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_mmc)); return; } #ifdef CONFIG_MMC_MSM_SDC1_SUPPORT if (machine_is_msm7x30_fluid()) { msm7x30_sdc1_data.ocr_mask = MMC_VDD_27_28 | MMC_VDD_28_29; msm_sdc1_lvlshft_enable(); } sdcc_vreg_data[0].vreg_data = vreg_s3; sdcc_vreg_data[0].level = 1800; msm_add_sdcc(1, &msm7x30_sdc1_data); #endif #ifdef CONFIG_MMC_MSM_SDC2_SUPPORT if (machine_is_msm8x55_svlte_surf()) msm7x30_sdc2_data.msmsdcc_fmax = 24576000; if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { msm7x30_sdc2_data.sdio_lpm_gpio_setup = msm_sdcc_sdio_lpm_gpio; #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT msm7x30_sdc2_data.sdiowakeup_irq = MSM_GPIO_TO_INT(68); #ifdef CONFIG_MSM_SDIO_AL msm7x30_sdc2_data.is_sdio_al_client = 1; #endif #endif } sdcc_vreg_data[1].vreg_data = vreg_s3; sdcc_vreg_data[1].level = 1800; msm_add_sdcc(2, &msm7x30_sdc2_data); #endif #ifdef CONFIG_MMC_MSM_SDC3_SUPPORT sdcc_vreg_data[2].vreg_data = vreg_s3; sdcc_vreg_data[2].level = 1800; msm_sdcc_setup_gpio(3, 1); msm_add_sdcc(3, &msm7x30_sdc3_data); #endif #ifdef CONFIG_MMC_MSM_SDC4_SUPPORT sdcc_vreg_data[3].vreg_data = vreg_mmc; sdcc_vreg_data[3].level = 2850; #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION switch(fih_get_product_id()) { case Product_FB0: { if(fih_get_product_phase() ==Product_PR1) sd_detect_pin = 38; else sd_detect_pin = 142; } break; case Product_FB1: case Product_FB3: case Product_FD1: { sd_detect_pin = 142; } break; case Product_SF6: { if(fih_get_product_phase() ==Product_PR3 || fih_get_product_phase() == Product_PCR) sd_detect_pin = 143; else sd_detect_pin = 142; } break; case Product_SFH: { sd_detect_pin = 142; } break; case Product_SF8: case Product_SH8: case Product_SFC: { sd_detect_pin = 0; } break; default: sd_detect_pin = 142; break; } if(sd_detect_pin) { gpio_tlmm_config(GPIO_CFG(sd_detect_pin, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), GPIO_CFG_ENABLE); msm7x30_sdc4_data.status_irq = MSM_GPIO_TO_INT(sd_detect_pin); } else { msm7x30_sdc4_data.status = NULL; msm7x30_sdc4_data.status_irq = 0; } #endif switch(fih_get_product_id()) { case Product_FB0: case Product_FB1: case Product_FB3: case Product_SF6: case Product_FD1: { sd_enable_pin = 85; } break; case Product_SF5: { sd_enable_pin = 100; } break; case Product_SF8: case Product_SFH: case Product_SH8: case Product_SFC: { sd_enable_pin = 175; } break; default: sd_enable_pin = 85; break; } gpio_tlmm_config(GPIO_CFG(sd_enable_pin, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); printk("[SD] id:%d, phase:%d, sd_enable_pin:%d, sd_detect_pin:%d\n", fih_get_product_id(), fih_get_product_phase(), sd_enable_pin, sd_detect_pin); msm_add_sdcc(4, &msm7x30_sdc4_data); #endif } static void __init msm7x30_init_nand(void) { char *build_id; struct flash_platform_data *plat_data; build_id = socinfo_get_build_id(); if (build_id == NULL) { pr_err("%s: Build ID not available from socinfo\n", __func__); return; } if (build_id[8] == 'C' && !msm_gpios_request_enable(msm_nand_ebi2_cfg_data, ARRAY_SIZE(msm_nand_ebi2_cfg_data))) { plat_data = msm_device_nand.dev.platform_data; plat_data->interleave = 1; printk(KERN_INFO "%s: Interleave mode Build ID found\n", __func__); } } #ifdef CONFIG_SERIAL_MSM_CONSOLE static struct msm_gpio uart2_config_data[] = { { GPIO_CFG(49, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART2_RFR"}, //{ GPIO_CFG(50, 2, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART2_CTS"}, { GPIO_CFG(51, 2, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART2_Rx"}, { GPIO_CFG(52, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART2_Tx"}, }; static void msm7x30_init_uart2(void) { msm_gpios_request_enable(uart2_config_data, ARRAY_SIZE(uart2_config_data)); } #endif /* TSIF begin */ #if defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE) #define TSIF_B_SYNC GPIO_CFG(37, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_B_DATA GPIO_CFG(36, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_B_EN GPIO_CFG(35, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_B_CLK GPIO_CFG(34, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) static const struct msm_gpio tsif_gpios[] = { { .gpio_cfg = TSIF_B_CLK, .label = "tsif_clk", }, { .gpio_cfg = TSIF_B_EN, .label = "tsif_en", }, { .gpio_cfg = TSIF_B_DATA, .label = "tsif_data", }, { .gpio_cfg = TSIF_B_SYNC, .label = "tsif_sync", }, }; static struct msm_tsif_platform_data tsif_platform_data = { .num_gpios = ARRAY_SIZE(tsif_gpios), .gpios = tsif_gpios, .tsif_pclk = "tsif_pclk", .tsif_ref_clk = "tsif_ref_clk", }; #endif /* defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE) */ /* TSIF end */ #ifdef CONFIG_LEDS_PM8058 static void __init pmic8058_leds_init(void) { if (machine_is_msm7x30_surf()) { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].platform_data = &pm8058_surf_leds_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].data_size = sizeof(pm8058_surf_leds_data); } else if (!machine_is_msm7x30_fluid()) { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].platform_data = &pm8058_ffa_leds_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].data_size = sizeof(pm8058_ffa_leds_data); } else if (machine_is_msm7x30_fluid()) { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].platform_data = &pm8058_fluid_leds_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].data_size = sizeof(pm8058_fluid_leds_data); } } #endif static struct msm_spm_platform_data msm_spm_data __initdata = { .reg_base_addr = MSM_SAW_BASE, .reg_init_values[MSM_SPM_REG_SAW_CFG] = 0x05, .reg_init_values[MSM_SPM_REG_SAW_SPM_CTL] = 0x18, .reg_init_values[MSM_SPM_REG_SAW_SPM_SLP_TMR_DLY] = 0x00006666, .reg_init_values[MSM_SPM_REG_SAW_SPM_WAKE_TMR_DLY] = 0xFF000666, .reg_init_values[MSM_SPM_REG_SAW_SLP_CLK_EN] = 0x01, .reg_init_values[MSM_SPM_REG_SAW_SLP_HSFS_PRECLMP_EN] = 0x03, .reg_init_values[MSM_SPM_REG_SAW_SLP_HSFS_POSTCLMP_EN] = 0x00, .reg_init_values[MSM_SPM_REG_SAW_SLP_CLMP_EN] = 0x01, .reg_init_values[MSM_SPM_REG_SAW_SLP_RST_EN] = 0x00, .reg_init_values[MSM_SPM_REG_SAW_SPM_MPM_CFG] = 0x00, .awake_vlevel = 0xF2, .retention_vlevel = 0xE0, .collapse_vlevel = 0x72, .retention_mid_vlevel = 0xE0, .collapse_mid_vlevel = 0xE0, .vctl_timeout_us = 50, }; //Div2-SW2-BSP,JOE HSU,+++ //#ifdef CONFIG_FIH_CONFIG_GROUP extern void fxx_info_init(void); //#endif //Div2-SW2-BSP,JOE HSU,--- #if defined(CONFIG_TOUCHSCREEN_TSC2007) || \ defined(CONFIG_TOUCHSCREEN_TSC2007_MODULE) #define TSC2007_TS_PEN_INT 20 static struct msm_gpio tsc2007_config_data[] = { { GPIO_CFG(TSC2007_TS_PEN_INT, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "tsc2007_irq" }, }; static struct vreg *vreg_tsc_s3; static struct vreg *vreg_tsc_s2; static int tsc2007_init(void) { int rc; vreg_tsc_s3 = vreg_get(NULL, "s3"); if (IS_ERR(vreg_tsc_s3)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_tsc_s3)); return -ENODEV; } rc = vreg_set_level(vreg_tsc_s3, 1800); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_set_level; } rc = vreg_enable(vreg_tsc_s3); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_set_level; } vreg_tsc_s2 = vreg_get(NULL, "s2"); if (IS_ERR(vreg_tsc_s2)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_tsc_s2)); goto fail_vreg_get; } rc = vreg_set_level(vreg_tsc_s2, 1300); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_s2_level; } rc = vreg_enable(vreg_tsc_s2); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_s2_level; } rc = msm_gpios_request_enable(tsc2007_config_data, ARRAY_SIZE(tsc2007_config_data)); if (rc) { pr_err("%s: Unable to request gpios\n", __func__); goto fail_gpio_req; } return 0; fail_gpio_req: vreg_disable(vreg_tsc_s2); fail_vreg_s2_level: vreg_put(vreg_tsc_s2); fail_vreg_get: vreg_disable(vreg_tsc_s3); fail_vreg_set_level: vreg_put(vreg_tsc_s3); return rc; } static int tsc2007_get_pendown_state(void) { int rc; rc = gpio_get_value(TSC2007_TS_PEN_INT); if (rc < 0) { pr_err("%s: MSM GPIO %d read failed\n", __func__, TSC2007_TS_PEN_INT); return rc; } return (rc == 0 ? 1 : 0); } static void tsc2007_exit(void) { vreg_disable(vreg_tsc_s3); vreg_put(vreg_tsc_s3); vreg_disable(vreg_tsc_s2); vreg_put(vreg_tsc_s2); msm_gpios_disable_free(tsc2007_config_data, ARRAY_SIZE(tsc2007_config_data)); } static int tsc2007_power_shutdown(bool enable) { int rc; if (enable == false) { rc = vreg_enable(vreg_tsc_s2); if (rc) { pr_err("%s: vreg_enable failed\n", __func__); return rc; } rc = vreg_enable(vreg_tsc_s3); if (rc) { pr_err("%s: vreg_enable failed\n", __func__); vreg_disable(vreg_tsc_s2); return rc; } /* Voltage settling delay */ msleep(20); } else { rc = vreg_disable(vreg_tsc_s2); if (rc) { pr_err("%s: vreg_disable failed\n", __func__); return rc; } rc = vreg_disable(vreg_tsc_s3); if (rc) { pr_err("%s: vreg_disable failed\n", __func__); vreg_enable(vreg_tsc_s2); return rc; } } return rc; } static struct tsc2007_platform_data tsc2007_ts_data = { .model = 2007, .x_plate_ohms = 300, .irq_flags = IRQF_TRIGGER_LOW, .init_platform_hw = tsc2007_init, .exit_platform_hw = tsc2007_exit, .power_shutdown = tsc2007_power_shutdown, .invert_x = true, .invert_y = true, /* REVISIT: Temporary fix for reversed pressure */ .invert_z1 = true, .invert_z2 = true, .get_pendown_state = tsc2007_get_pendown_state, }; static struct i2c_board_info tsc_i2c_board_info[] = { { I2C_BOARD_INFO("tsc2007", 0x48), .irq = MSM_GPIO_TO_INT(TSC2007_TS_PEN_INT), .platform_data = &tsc2007_ts_data, }, }; #endif static const char *vregs_isa1200_name[] = { "gp7", "gp10", }; static const int vregs_isa1200_val[] = { 1800, 2600, }; static struct vreg *vregs_isa1200[ARRAY_SIZE(vregs_isa1200_name)]; static int isa1200_power(int vreg_on) { int i, rc = 0; for (i = 0; i < ARRAY_SIZE(vregs_isa1200_name); i++) { if (!vregs_isa1200[i]) { pr_err("%s: vreg_get %s failed (%d)\n", __func__, vregs_isa1200_name[i], rc); goto vreg_fail; } rc = vreg_on ? vreg_enable(vregs_isa1200[i]) : vreg_disable(vregs_isa1200[i]); if (rc < 0) { pr_err("%s: vreg %s %s failed (%d)\n", __func__, vregs_isa1200_name[i], vreg_on ? "enable" : "disable", rc); goto vreg_fail; } } return 0; vreg_fail: while (i) vreg_disable(vregs_isa1200[--i]); return rc; } static int isa1200_dev_setup(bool enable) { int i, rc; if (enable == true) { for (i = 0; i < ARRAY_SIZE(vregs_isa1200_name); i++) { vregs_isa1200[i] = vreg_get(NULL, vregs_isa1200_name[i]); if (IS_ERR(vregs_isa1200[i])) { pr_err("%s: vreg get %s failed (%ld)\n", __func__, vregs_isa1200_name[i], PTR_ERR(vregs_isa1200[i])); rc = PTR_ERR(vregs_isa1200[i]); goto vreg_get_fail; } rc = vreg_set_level(vregs_isa1200[i], vregs_isa1200_val[i]); if (rc) { pr_err("%s: vreg_set_level() = %d\n", __func__, rc); goto vreg_get_fail; } } rc = gpio_tlmm_config(GPIO_CFG(HAP_LVL_SHFT_MSM_GPIO, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE); if (rc) { pr_err("%s: Could not configure gpio %d\n", __func__, HAP_LVL_SHFT_MSM_GPIO); goto vreg_get_fail; } rc = gpio_request(HAP_LVL_SHFT_MSM_GPIO, "haptics_shft_lvl_oe"); if (rc) { pr_err("%s: unable to request gpio %d (%d)\n", __func__, HAP_LVL_SHFT_MSM_GPIO, rc); goto vreg_get_fail; } gpio_set_value(HAP_LVL_SHFT_MSM_GPIO, 1); } else { for (i = 0; i < ARRAY_SIZE(vregs_isa1200_name); i++) vreg_put(vregs_isa1200[i]); gpio_free(HAP_LVL_SHFT_MSM_GPIO); } return 0; vreg_get_fail: while (i) vreg_put(vregs_isa1200[--i]); return rc; } static struct isa1200_platform_data isa1200_1_pdata = { .name = "vibrator", .power_on = isa1200_power, .dev_setup = isa1200_dev_setup, .pwm_ch_id = 1, /*channel id*/ /*gpio to enable haptic*/ .hap_en_gpio = PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_HAP_ENABLE), .max_timeout = 15000, .mode_ctrl = PWM_GEN_MODE, .pwm_fd = { .pwm_div = 256, }, .is_erm = false, .smart_en = true, .ext_clk_en = true, .chip_en = 1, }; static struct i2c_board_info msm_isa1200_board_info[] = { { I2C_BOARD_INFO("isa1200_1", 0x90>>1), .platform_data = &isa1200_1_pdata, }, }; static int kp_flip_mpp_config(void) { return pm8058_mpp_config_digital_in(PM_FLIP_MPP, PM8058_MPP_DIG_LEVEL_S3, PM_MPP_DIN_TO_INT); } static struct flip_switch_pdata flip_switch_data = { .name = "kp_flip_switch", .flip_gpio = PM8058_GPIO_PM_TO_SYS(PM8058_GPIOS) + PM_FLIP_MPP, .left_key = KEY_OPEN, .right_key = KEY_CLOSE, .active_low = 0, .wakeup = 1, .flip_mpp_config = kp_flip_mpp_config, }; static struct platform_device flip_switch_device = { .name = "kp_flip_switch", .id = -1, .dev = { .platform_data = &flip_switch_data, } }; static const char *vregs_tma300_name[] = { "gp6", "gp7", }; static const int vregs_tma300_val[] = { 3050, 1800, }; static struct vreg *vregs_tma300[ARRAY_SIZE(vregs_tma300_name)]; static int tma300_power(int vreg_on) { int i, rc = -EINVAL; for (i = 0; i < ARRAY_SIZE(vregs_tma300_name); i++) { /* Never disable gp6 for fluid as lcd has a problem with it */ if (!i && !vreg_on) continue; if (!vregs_tma300[i]) { printk(KERN_ERR "%s: vreg_get %s failed (%d)\n", __func__, vregs_tma300_name[i], rc); return rc; } rc = vreg_on ? vreg_enable(vregs_tma300[i]) : vreg_disable(vregs_tma300[i]); if (rc < 0) { printk(KERN_ERR "%s: vreg %s %s failed (%d)\n", __func__, vregs_tma300_name[i], vreg_on ? "enable" : "disable", rc); return rc; } } return 0; } #define TS_GPIO_IRQ 150 static int tma300_dev_setup(bool enable) { int i, rc; if (enable) { /* get voltage sources */ for (i = 0; i < ARRAY_SIZE(vregs_tma300_name); i++) { vregs_tma300[i] = vreg_get(NULL, vregs_tma300_name[i]); if (IS_ERR(vregs_tma300[i])) { pr_err("%s: vreg get %s failed (%ld)\n", __func__, vregs_tma300_name[i], PTR_ERR(vregs_tma300[i])); rc = PTR_ERR(vregs_tma300[i]); goto vreg_get_fail; } rc = vreg_set_level(vregs_tma300[i], vregs_tma300_val[i]); if (rc) { pr_err("%s: vreg_set_level() = %d\n", __func__, rc); i++; goto vreg_get_fail; } } /* enable interrupt gpio */ rc = gpio_tlmm_config(GPIO_CFG(TS_GPIO_IRQ, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_6MA), GPIO_CFG_ENABLE); if (rc) { pr_err("%s: Could not configure gpio %d\n", __func__, TS_GPIO_IRQ); goto vreg_get_fail; } /* virtual keys */ tma300_vkeys_attr.attr.name = "virtualkeys.msm_tma300_ts"; properties_kobj = kobject_create_and_add("board_properties", NULL); if (!properties_kobj) { pr_err("%s: failed to create a kobject" "for board_properites\n", __func__); rc = -ENOMEM; goto vreg_get_fail; } rc = sysfs_create_group(properties_kobj, &tma300_properties_attr_group); if (rc) { pr_err("%s: failed to create a sysfs entry %s\n", __func__, tma300_vkeys_attr.attr.name); kobject_put(properties_kobj); goto vreg_get_fail; } } else { /* put voltage sources */ for (i = 0; i < ARRAY_SIZE(vregs_tma300_name); i++) vreg_put(vregs_tma300[i]); /* destroy virtual keys */ if (properties_kobj) { sysfs_remove_group(properties_kobj, &tma300_properties_attr_group); kobject_put(properties_kobj); } } return 0; vreg_get_fail: while (i) vreg_put(vregs_tma300[--i]); return rc; } static struct cy8c_ts_platform_data cy8ctma300_pdata = { .power_on = tma300_power, .dev_setup = tma300_dev_setup, .ts_name = "msm_tma300_ts", .dis_min_x = 0, .dis_max_x = 479, .dis_min_y = 0, .dis_max_y = 799, .res_x = 479, .res_y = 1009, .min_tid = 1, .max_tid = 255, .min_touch = 0, .max_touch = 255, .min_width = 0, .max_width = 255, .invert_y = 1, .nfingers = 4, .irq_gpio = TS_GPIO_IRQ, .resout_gpio = -1, }; static struct i2c_board_info cy8ctma300_board_info[] = { { I2C_BOARD_INFO("cy8ctma300", 0x2), .platform_data = &cy8ctma300_pdata, } }; static void __init msm7x30_init(void) { int rc; //SW5-Multimedia-TH-MT9P111forV6-00+{ int pid = Product_FB0; int cnt = 0; int camera_num = 0; //SW5-Multimedia-TH-MT9P111forV6-00+} unsigned smem_size; uint32_t usb_hub_gpio_cfg_value = GPIO_CFG(56, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); uint32_t soc_version = 0; if (socinfo_init() < 0) printk(KERN_ERR "%s: socinfo_init() failed!\n", __func__); soc_version = socinfo_get_version(); //Div2-SW2-BSP,JOE HSU fih_get_oem_info(); fih_get_host_oem_info(); // SW2-5-1-MP-HostOemInfo-00+ msm_clock_init(msm_clocks_7x30, msm_num_clocks_7x30); #ifdef CONFIG_SERIAL_MSM_CONSOLE msm7x30_init_uart2(); #endif msm_spm_init(&msm_spm_data, 1); msm_acpu_clock_init(&msm7x30_clock_data); /* Div2-SW2-BSP-FBX-OW { */ #ifdef CONFIG_SMSC911X if (machine_is_msm7x30_surf() || machine_is_msm7x30_fluid()) msm7x30_cfg_smsc911x(); #endif /* } Div2-SW2-BSP-FBX-OW */ #ifdef CONFIG_USB_FUNCTION msm_hsusb_pdata.swfi_latency = msm_pm_data [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].latency; msm_device_hsusb_peripheral.dev.platform_data = &msm_hsusb_pdata; #endif #ifdef CONFIG_USB_MSM_OTG_72K if (SOCINFO_VERSION_MAJOR(soc_version) >= 2 && SOCINFO_VERSION_MINOR(soc_version) >= 1) { pr_debug("%s: SOC Version:2.(1 or more)\n", __func__); msm_otg_pdata.ldo_set_voltage = 0; } msm_device_otg.dev.platform_data = &msm_otg_pdata; #ifdef CONFIG_USB_GADGET msm_otg_pdata.swfi_latency = msm_pm_data [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].latency; msm_device_gadget_peripheral.dev.platform_data = &msm_gadget_pdata; #endif #endif msm_uart_dm1_pdata.wakeup_irq = gpio_to_irq(136); msm_device_uart_dm1.dev.platform_data = &msm_uart_dm1_pdata; camera_sensor_hwpin_init(); #if defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE) msm_device_tsif.dev.platform_data = &tsif_platform_data; #endif if (machine_is_msm7x30_fluid()) { msm_adc_pdata.dev_names = msm_adc_fluid_device_names; msm_adc_pdata.num_adc = ARRAY_SIZE(msm_adc_fluid_device_names); } else { msm_adc_pdata.dev_names = msm_adc_surf_device_names; msm_adc_pdata.num_adc = ARRAY_SIZE(msm_adc_surf_device_names); } #ifdef CONFIG_USB_ANDROID if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { android_usb_pdata.product_id = 0x9028; android_usb_pdata.num_products = ARRAY_SIZE(fusion_usb_products); android_usb_pdata.products = fusion_usb_products; } #endif platform_add_devices(devices, ARRAY_SIZE(devices)); #ifdef CONFIG_USB_EHCI_MSM msm_add_host(0, &msm_usb_host_pdata); #endif /* FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized { */ #ifdef CONFIG_FIH_FXX sync_from_custom_nv(); //Div2-5-3-Peripheral-LL-UsbPorting-00+ #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized */ msm7x30_init_mmc(); msm7x30_init_nand(); msm_qsd_spi_init(); #ifdef CONFIG_SPI_QSD if (machine_is_msm7x30_fluid()) spi_register_board_info(lcdc_sharp_spi_board_info, ARRAY_SIZE(lcdc_sharp_spi_board_info)); else spi_register_board_info(lcdc_toshiba_spi_board_info, ARRAY_SIZE(lcdc_toshiba_spi_board_info)); #endif msm_fb_add_devices(); msm_pm_set_platform_data(msm_pm_data, ARRAY_SIZE(msm_pm_data)); /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ msm_device_i2c_power_domain(); /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ msm_device_i2c_init(); msm_device_i2c_2_init(); qup_device_i2c_init(); buses_init(); msm7x30_init_marimba(); #ifdef CONFIG_MSM7KV2_AUDIO snddev_poweramp_gpio_init(); aux_pcm_gpio_init(); #endif #ifdef CONFIG_BATTERY_FIH_MSM fih_battery_driver_init(); // DIV2-SW2-BSP-FBx-BATT #endif i2c_register_board_info(0, msm_i2c_board_info, ARRAY_SIZE(msm_i2c_board_info)); if (!machine_is_msm8x55_svlte_ffa()) marimba_pdata.tsadc = &marimba_tsadc_pdata; if (machine_is_msm7x30_fluid()) i2c_register_board_info(0, cy8info, ARRAY_SIZE(cy8info)); #ifdef CONFIG_BOSCH_BMA150 if (machine_is_msm7x30_fluid()) i2c_register_board_info(0, bma150_board_info, ARRAY_SIZE(bma150_board_info)); #endif i2c_register_board_info(2, msm_marimba_board_info, ARRAY_SIZE(msm_marimba_board_info)); //SW5-Multimedia-TH-MT9P111forV6-00+{ pid = fih_get_product_id(); camera_num = ARRAY_SIZE(msm_camera_boardinfo); if (pid == Product_SF6 || IS_SF8_SERIES_PRJ())//Div2-SW6-MM-MC-ImplementCameraFTMforSF8Serials-00* { for (cnt = 0; cnt < camera_num; cnt++) { if(strncasecmp(msm_camera_boardinfo[cnt].type, "mt9p111", 7) == 0) { printk(KERN_INFO "%s: Old camera slave address = %x .\n", __func__, msm_camera_boardinfo[cnt].addr); msm_camera_boardinfo[cnt].addr = (0x7A >> 1); printk(KERN_INFO "%s: New camera slave address = %x .\n", __func__, msm_camera_boardinfo[cnt].addr); } } if (IS_SF8_SERIES_PRJ()) printk(KERN_INFO "%s: This is SF8 series project.....\n", __func__); } //SW5-Multimedia-TH-MT9P111forV6-00+} i2c_register_board_info(2, msm_i2c_gsbi7_timpani_info, ARRAY_SIZE(msm_i2c_gsbi7_timpani_info)); i2c_register_board_info(4 /* QUP ID */, msm_camera_boardinfo, ARRAY_SIZE(msm_camera_boardinfo)); bt_power_init(); // FihtdcCode@20110908 WeiChu add for WiFi porting begin // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_WLAN_POWER bcm4329_wifi_power_init(); #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +] // FIHTDC-SW2-Div6-CW-Project BCM4329 BLUETOOTH driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_BLUETOOTH_POWER bcm4329_bt_power_init(); bcm4329_fm_power_init(); #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 BLUETOOTH driver For SF8 +] // FihtdcCode@20110908 WeiChu add for WiFi porting end #ifdef CONFIG_I2C_SSBI msm_device_ssbi6.dev.platform_data = &msm_i2c_ssbi6_pdata; msm_device_ssbi7.dev.platform_data = &msm_i2c_ssbi7_pdata; #endif if (machine_is_msm7x30_fluid()) i2c_register_board_info(0, msm_isa1200_board_info, ARRAY_SIZE(msm_isa1200_board_info)); #if defined(CONFIG_TOUCHSCREEN_TSC2007) || \ defined(CONFIG_TOUCHSCREEN_TSC2007_MODULE) if (machine_is_msm8x55_svlte_ffa()) i2c_register_board_info(2, tsc_i2c_board_info, ARRAY_SIZE(tsc_i2c_board_info)); #endif if (machine_is_msm7x30_surf()) platform_device_register(&flip_switch_device); #ifdef CONFIG_LEDS_PM8058 pmic8058_leds_init(); #endif if (machine_is_msm7x30_fluid()) { /* Initialize platform data for fluid v2 hardware */ if (SOCINFO_VERSION_MAJOR( socinfo_get_platform_version()) == 2) { cy8ctma300_pdata.res_y = 920; cy8ctma300_pdata.invert_y = 0; } i2c_register_board_info(0, cy8ctma300_board_info, ARRAY_SIZE(cy8ctma300_board_info)); } if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = gpio_tlmm_config(usb_hub_gpio_cfg_value, GPIO_CFG_ENABLE); if (rc) pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, usb_hub_gpio_cfg_value, rc); } boot_reason = *(unsigned int *) (smem_get_entry(SMEM_POWER_ON_STATUS_INFO, &smem_size)); printk(KERN_NOTICE "Boot Reason = 0x%02x\n", boot_reason); //Div2-SW2-BSP,JOE HSU,+++ //#ifdef CONFIG_FIH_CONFIG_GROUP /*call product id functions for init verification*/ fih_get_product_id(); fih_get_product_phase(); fih_get_band_id(); fxx_info_init(); //#endif //Div2-SW2-BSP,JOE HSU,--- } static unsigned pmem_sf_size = MSM_PMEM_SF_SIZE; static int __init pmem_sf_size_setup(char *p) { pmem_sf_size = memparse(p, NULL); return 0; } early_param("pmem_sf_size", pmem_sf_size_setup); static unsigned fb_size = MSM_FB_SIZE; static int __init fb_size_setup(char *p) { fb_size = memparse(p, NULL); return 0; } early_param("fb_size", fb_size_setup); static unsigned pmem_adsp_size = MSM_PMEM_ADSP_SIZE; static int __init pmem_adsp_size_setup(char *p) { pmem_adsp_size = memparse(p, NULL); return 0; } early_param("pmem_adsp_size", pmem_adsp_size_setup); static unsigned fluid_pmem_adsp_size = MSM_FLUID_PMEM_ADSP_SIZE; static int __init fluid_pmem_adsp_size_setup(char *p) { fluid_pmem_adsp_size = memparse(p, NULL); return 0; } early_param("fluid_pmem_adsp_size", fluid_pmem_adsp_size_setup); static unsigned pmem_audio_size = MSM_PMEM_AUDIO_SIZE; static int __init pmem_audio_size_setup(char *p) { pmem_audio_size = memparse(p, NULL); return 0; } early_param("pmem_audio_size", pmem_audio_size_setup); static unsigned pmem_kernel_ebi1_size = PMEM_KERNEL_EBI1_SIZE; static int __init pmem_kernel_ebi1_size_setup(char *p) { pmem_kernel_ebi1_size = memparse(p, NULL); return 0; } early_param("pmem_kernel_ebi1_size", pmem_kernel_ebi1_size_setup); static void __init msm7x30_allocate_memory_regions(void) { void *addr; unsigned long size; /* Request allocation of Hardware accessible PMEM regions at the beginning to make sure they are allocated in EBI-0. This will allow 7x30 with two mem banks enter the second mem bank into Self-Refresh State during Idle Power Collapse. The current HW accessible PMEM regions are 1. Frame Buffer. LCDC HW can access msm_fb_resources during Idle-PC. 2. Audio LPA HW can access android_pmem_audio_pdata during Idle-PC. */ size = fb_size ? : MSM_FB_SIZE; addr = alloc_bootmem(size); msm_fb_resources[0].start = __pa(addr); msm_fb_resources[0].end = msm_fb_resources[0].start + size - 1; pr_info("allocating %lu bytes at %p (%lx physical) for fb\n", size, addr, __pa(addr)); size = pmem_audio_size; if (size) { addr = alloc_bootmem(size); android_pmem_audio_pdata.start = __pa(addr); android_pmem_audio_pdata.size = size; pr_info("allocating %lu bytes at %p (%lx physical) for audio " "pmem arena\n", size, addr, __pa(addr)); } size = pmem_kernel_ebi1_size; if (size) { addr = alloc_bootmem_aligned(size, 0x100000); android_pmem_kernel_ebi1_pdata.start = __pa(addr); android_pmem_kernel_ebi1_pdata.size = size; pr_info("allocating %lu bytes at %p (%lx physical) for kernel" " ebi1 pmem arena\n", size, addr, __pa(addr)); } size = pmem_sf_size; if (size) { addr = alloc_bootmem(size); android_pmem_pdata.start = __pa(addr); android_pmem_pdata.size = size; pr_info("allocating %lu bytes at %p (%lx physical) for sf " "pmem arena\n", size, addr, __pa(addr)); } if machine_is_msm7x30_fluid() size = fluid_pmem_adsp_size; else size = pmem_adsp_size; if (size) { addr = alloc_bootmem(size); android_pmem_adsp_pdata.start = __pa(addr); android_pmem_adsp_pdata.size = size; pr_info("allocating %lu bytes at %p (%lx physical) for adsp " "pmem arena\n", size, addr, __pa(addr)); } } static void __init msm7x30_map_io(void) { msm_shared_ram_phys = 0x00100000; msm_map_msm7x30_io(); msm7x30_allocate_memory_regions(); } MACHINE_START(MSM7X30_SURF, "QCT MSM7X30 SURF") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM7X30_FFA, "QCT MSM7X30 FFA") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM7X30_FLUID, "QCT MSM7X30 FLUID") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM8X55_SURF, "QCT MSM8X55 SURF") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM8X55_FFA, "FB0") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM8X55_SVLTE_SURF, "QCT MSM8X55 SVLTE SURF") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM8X55_SVLTE_FFA, "QCT MSM8X55 SVLTE FFA") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END
gdyuldin/huawei_u8850_kernel_ics
arch/arm/mach-msm/board-msm7x30.c
C
gpl-2.0
281,833
import MySQLdb class DatabaseHandler: def __init__(self): pass def is_delete(self, tableName): reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"] isDeleteFlag = 1 for name in reservedTableNameList: isIdentical = cmp(tableName, name) if isIdentical == 0: isDeleteFlag = 0 break return isDeleteFlag def Clean_Database(self, hostUrl, account, password, databaseName): print 'clean database1' db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName) cursor = db.cursor() cursor.execute("Show Tables from " + databaseName) result = cursor.fetchall() for record in result: tableName = record[0] isDelete = self.is_delete(tableName) if isDelete == 0: print "Reserve " + tableName else : print "TRUNCATE TABLE `" + tableName + "`" cursor.execute("TRUNCATE TABLE `" + tableName + "`") print 'Add admin' cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', 'example@ezScrum.tw', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)") cursor.execute("INSERT INTO `system` VALUES (1, 1)") db.commit() #if __name__ == '__main__': # databaseHandler = DatabaseHandler() # databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
ezScrum/ezScrum
robotTesting/keywords/lib/DatabaseHandler.py
Python
gpl-2.0
1,547
#!/usr/bin/ruby require File.expand_path(ENV['MOSYNCDIR']+'/rules/mosync_exe.rb') work = PipeExeWork.new work.instance_eval do @SOURCES = ["."] @LIBRARIES = ["mautil"] @NAME = "Stylus" end work.invoke
tybor/MoSync
examples/cpp/Moblet/Stylus/workfile.rb
Ruby
gpl-2.0
207
/*********************************************************************************** * * * Voreen - The Volume Rendering Engine * * * * Copyright (C) 2005-2013 University of Muenster, Germany. * * Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> * * For a list of authors please refer to the file "CREDITS.txt". * * * * This file is part of the Voreen software package. Voreen 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. * * * * Voreen 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 in the file * * "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. * * * * For non-commercial academic use see the license exception specified in the file * * "LICENSE-academic.txt". To get information about commercial licensing please * * contact the authors. * * * ***********************************************************************************/ #include "isolatedconnectedimagefilter.h" #include "voreen/core/datastructures/volume/volumeram.h" #include "voreen/core/datastructures/volume/volume.h" #include "voreen/core/datastructures/volume/volumeatomic.h" #include "voreen/core/ports/conditions/portconditionvolumetype.h" #include "modules/itk/utils/itkwrapper.h" #include "voreen/core/datastructures/volume/operators/volumeoperatorconvert.h" #include "itkImage.h" #include "itkIsolatedConnectedImageFilter.h" #include <iostream> namespace voreen { const std::string IsolatedConnectedImageFilterITK::loggerCat_("voreen.IsolatedConnectedImageFilterITK"); IsolatedConnectedImageFilterITK::IsolatedConnectedImageFilterITK() : ITKProcessor(), inport1_(Port::INPORT, "InputImage"), outport1_(Port::OUTPORT, "OutputImage"), seedPointPort1_(Port::INPORT, "seedPointInput1"), seedPointPort2_(Port::INPORT, "seedPointInput2"), enableProcessing_("enabled", "Enable", false), replaceValue_("replaceValue", "ReplaceValue"), isolatedValueTolerance_("isolatedValueTolerance", "IsolatedValueTolerance"), upper_("upper", "Upper"), lower_("lower", "Lower"), findUpperThreshold_("findUpperThreshold", "FindUpperThreshold", false) { addPort(inport1_); PortConditionLogicalOr* orCondition1 = new PortConditionLogicalOr(); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt8()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt8()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt16()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt16()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt32()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt32()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeFloat()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeDouble()); inport1_.addCondition(orCondition1); addPort(outport1_); addPort(seedPointPort1_); addPort(seedPointPort2_); addProperty(enableProcessing_); addProperty(replaceValue_); addProperty(isolatedValueTolerance_); addProperty(upper_); addProperty(lower_); addProperty(findUpperThreshold_); } Processor* IsolatedConnectedImageFilterITK::create() const { return new IsolatedConnectedImageFilterITK(); } template<class T> void IsolatedConnectedImageFilterITK::isolatedConnectedImageFilterITK() { replaceValue_.setVolume(inport1_.getData()); isolatedValueTolerance_.setVolume(inport1_.getData()); upper_.setVolume(inport1_.getData()); lower_.setVolume(inport1_.getData()); if (!enableProcessing_.get()) { outport1_.setData(inport1_.getData(), false); return; } typedef itk::Image<T, 3> InputImageType1; typedef itk::Image<T, 3> OutputImageType1; typename InputImageType1::Pointer p1 = voreenToITK<T>(inport1_.getData()); //Filter define typedef itk::IsolatedConnectedImageFilter<InputImageType1, OutputImageType1> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); if (seedPointPort1_.hasChanged()) { const PointListGeometry<tgt::vec3>* pointList1 = dynamic_cast< const PointListGeometry<tgt::vec3>* >(seedPointPort1_.getData()); if (pointList1) { seedPoints1 = pointList1->getData(); } } filter->ClearSeeds1(); typename InputImageType1::IndexType seed1; for (size_t i = 0; i < seedPoints1.size(); i++) { seed1[0] = seedPoints1[i].x; seed1[1] = seedPoints1[i].y; seed1[2] = seedPoints1[i].z; filter->AddSeed1(seed1); } if (seedPointPort2_.hasChanged()) { const PointListGeometry<tgt::vec3>* pointList2 = dynamic_cast< const PointListGeometry<tgt::vec3>* >(seedPointPort2_.getData()); if (pointList2) { seedPoints2 = pointList2->getData(); } } filter->ClearSeeds2(); typename InputImageType1::IndexType seed2; for (size_t i = 0; i < seedPoints2.size(); i++) { seed2[0] = seedPoints2[i].x; seed2[1] = seedPoints2[i].y; seed2[2] = seedPoints2[i].z; filter->AddSeed2(seed2); } filter->SetReplaceValue(replaceValue_.getValue<T>()); filter->SetIsolatedValueTolerance(isolatedValueTolerance_.getValue<T>()); filter->SetUpper(upper_.getValue<T>()); filter->SetLower(lower_.getValue<T>()); filter->SetFindUpperThreshold(findUpperThreshold_.get()); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } void IsolatedConnectedImageFilterITK::process() { const VolumeBase* inputHandle1 = inport1_.getData(); const VolumeRAM* inputVolume1 = inputHandle1->getRepresentation<VolumeRAM>(); if (dynamic_cast<const VolumeRAM_UInt8*>(inputVolume1)) { isolatedConnectedImageFilterITK<uint8_t>(); } else if (dynamic_cast<const VolumeRAM_Int8*>(inputVolume1)) { isolatedConnectedImageFilterITK<int8_t>(); } else if (dynamic_cast<const VolumeRAM_UInt16*>(inputVolume1)) { isolatedConnectedImageFilterITK<uint16_t>(); } else if (dynamic_cast<const VolumeRAM_Int16*>(inputVolume1)) { isolatedConnectedImageFilterITK<int16_t>(); } else if (dynamic_cast<const VolumeRAM_UInt32*>(inputVolume1)) { isolatedConnectedImageFilterITK<uint32_t>(); } else if (dynamic_cast<const VolumeRAM_Int32*>(inputVolume1)) { isolatedConnectedImageFilterITK<int32_t>(); } else if (dynamic_cast<const VolumeRAM_Float*>(inputVolume1)) { isolatedConnectedImageFilterITK<float>(); } else if (dynamic_cast<const VolumeRAM_Double*>(inputVolume1)) { isolatedConnectedImageFilterITK<double>(); } else { LERROR("Inputformat of Volume 1 is not supported!"); } } } // namespace
bilgili/Voreen
modules/itk_generated/processors/itk_RegionGrowing/isolatedconnectedimagefilter.cpp
C++
gpl-2.0
8,330
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_06) on Wed Dec 28 15:03:50 CET 2005 --> <TITLE> SimpleTextGUI01 </TITLE> <META NAME="keywords" CONTENT="jmatlink.ui.SimpleTextGUI01 class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="SimpleTextGUI01"; } </SCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SimpleTextGUI01.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../jmatlink/ui/SimpleTestGui02.html" title="class in jmatlink.ui"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../jmatlink/ui/SimpleTextGUI02.html" title="class in jmatlink.ui"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SimpleTextGUI01.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> jmatlink.ui</FONT> <BR> Class SimpleTextGUI01</H2> <PRE> java.lang.Object <IMG SRC="../../resources/inherit.gif" ALT="extended by"><B>jmatlink.ui.SimpleTextGUI01</B> </PRE> <HR> <DL> <DT>public class <B>SimpleTextGUI01</B><DT>extends java.lang.Object</DL> <P> <HR> <P> <!-- ======== NESTED CLASS SUMMARY ======== --> <!-- =========== FIELD SUMMARY =========== --> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../jmatlink/ui/SimpleTextGUI01.html#SimpleTextGUI01()">SimpleTextGUI01</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Method Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../jmatlink/ui/SimpleTextGUI01.html#main(java.lang.String[])">main</A></B>(java.lang.String[]&nbsp;args)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class java.lang.Object</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TD> </TR> </TABLE> <A NAME="SimpleTextGUI01()"><!-- --></A><H3> SimpleTextGUI01</H3> <PRE> public <B>SimpleTextGUI01</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Method Detail</B></FONT></TD> </TR> </TABLE> <A NAME="main(java.lang.String[])"><!-- --></A><H3> main</H3> <PRE> public static void <B>main</B>(java.lang.String[]&nbsp;args)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SimpleTextGUI01.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../jmatlink/ui/SimpleTestGui02.html" title="class in jmatlink.ui"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../jmatlink/ui/SimpleTextGUI02.html" title="class in jmatlink.ui"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SimpleTextGUI01.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Olshansk/PLSNPAIRS-Thesis
extern/jMatLink/doc/javadoc/jmatlink/ui/SimpleTextGUI01.html
HTML
gpl-2.0
9,738
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ /*** This file is part of systemd. Copyright 2010 Lennart Poettering systemd 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. systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>. ***/ #include <errno.h> #include <sys/mount.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sched.h> #include <sys/syscall.h> #include <limits.h> #include <linux/fs.h> #include "strv.h" #include "util.h" #include "path-util.h" #include "namespace.h" #include "missing.h" #include "execute.h" typedef enum MountMode { /* This is ordered by priority! */ INACCESSIBLE, READONLY, PRIVATE_TMP, PRIVATE_VAR_TMP, READWRITE } MountMode; typedef struct BindMount { const char *path; MountMode mode; bool done; bool ignore; } BindMount; static int append_mounts(BindMount **p, char **strv, MountMode mode) { char **i; STRV_FOREACH(i, strv) { (*p)->ignore = false; if ((mode == INACCESSIBLE || mode == READONLY) && (*i)[0] == '-') { (*p)->ignore = true; (*i)++; } if (!path_is_absolute(*i)) return -EINVAL; (*p)->path = *i; (*p)->mode = mode; (*p)++; } return 0; } static int mount_path_compare(const void *a, const void *b) { const BindMount *p = a, *q = b; if (path_equal(p->path, q->path)) { /* If the paths are equal, check the mode */ if (p->mode < q->mode) return -1; if (p->mode > q->mode) return 1; return 0; } /* If the paths are not equal, then order prefixes first */ if (path_startswith(p->path, q->path)) return 1; if (path_startswith(q->path, p->path)) return -1; return 0; } static void drop_duplicates(BindMount *m, unsigned *n) { BindMount *f, *t, *previous; assert(m); assert(n); for (f = m, t = m, previous = NULL; f < m+*n; f++) { /* The first one wins */ if (previous && path_equal(f->path, previous->path)) continue; t->path = f->path; t->mode = f->mode; previous = t; t++; } *n = t - m; } static int apply_mount( BindMount *m, const char *tmp_dir, const char *var_tmp_dir) { const char *what; int r; assert(m); switch (m->mode) { case INACCESSIBLE: what = "/run/systemd/inaccessible"; break; case READONLY: case READWRITE: what = m->path; break; case PRIVATE_TMP: what = tmp_dir; break; case PRIVATE_VAR_TMP: what = var_tmp_dir; break; default: assert_not_reached("Unknown mode"); } assert(what); r = mount(what, m->path, NULL, MS_BIND|MS_REC, NULL); if (r >= 0) log_debug("Successfully mounted %s to %s", what, m->path); else if (m->ignore && errno == ENOENT) r = 0; return r; } static int make_read_only(BindMount *m) { int r; assert(m); if (m->mode != INACCESSIBLE && m->mode != READONLY) return 0; r = mount(NULL, m->path, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_REC, NULL); if (r < 0 && !(m->ignore && errno == ENOENT)) return -errno; return 0; } int setup_tmpdirs(const char *unit_id, char **tmp_dir, char **var_tmp_dir) { int r = 0; _cleanup_free_ char *tmp = NULL, *var = NULL; assert(tmp_dir); assert(var_tmp_dir); tmp = strjoin("/tmp/systemd-", unit_id, "-XXXXXXX", NULL); var = strjoin("/var/tmp/systemd-", unit_id, "-XXXXXXX", NULL); r = create_tmp_dir(tmp, tmp_dir); if (r < 0) return r; r = create_tmp_dir(var, var_tmp_dir); if (r == 0) return 0; /* failure */ rmdir(*tmp_dir); rmdir(tmp); free(*tmp_dir); *tmp_dir = NULL; return r; } int setup_namespace(char** read_write_dirs, char** read_only_dirs, char** inaccessible_dirs, char* tmp_dir, char* var_tmp_dir, bool private_tmp, unsigned mount_flags) { unsigned n = strv_length(read_write_dirs) + strv_length(read_only_dirs) + strv_length(inaccessible_dirs) + (private_tmp ? 2 : 0); BindMount *m, *mounts = NULL; int r = 0; if (!mount_flags) mount_flags = MS_SHARED; if (unshare(CLONE_NEWNS) < 0) return -errno; if (n) { m = mounts = (BindMount *) alloca(n * sizeof(BindMount)); if ((r = append_mounts(&m, read_write_dirs, READWRITE)) < 0 || (r = append_mounts(&m, read_only_dirs, READONLY)) < 0 || (r = append_mounts(&m, inaccessible_dirs, INACCESSIBLE)) < 0) return r; if (private_tmp) { m->path = "/tmp"; m->mode = PRIVATE_TMP; m++; m->path = "/var/tmp"; m->mode = PRIVATE_VAR_TMP; m++; } assert(mounts + n == m); qsort(mounts, n, sizeof(BindMount), mount_path_compare); drop_duplicates(mounts, &n); } /* Remount / as SLAVE so that nothing now mounted in the namespace shows up in the parent */ if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) return -errno; for (m = mounts; m < mounts + n; ++m) { r = apply_mount(m, tmp_dir, var_tmp_dir); if (r < 0) goto undo_mounts; } for (m = mounts; m < mounts + n; ++m) { r = make_read_only(m); if (r < 0) goto undo_mounts; } /* Remount / as the desired mode */ if (mount(NULL, "/", NULL, mount_flags | MS_REC, NULL) < 0) { r = -errno; goto undo_mounts; } return 0; undo_mounts: for (m = mounts; m < mounts + n; ++m) { if (m->done) umount2(m->path, MNT_DETACH); } return r; }
freedesktop-unofficial-mirror/systemd__systemd-stable
src/core/namespace.c
C
gpl-2.0
7,610
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Function template operator++</title> <link rel="stylesheet" href="boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="index.html" title="ODTONE 0.6"> <link rel="up" href="odtone_base_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.types.base_hpp" title="Header &lt;/home/carlos/Projectos/odtone/inc/odtone/mih/types/base.hpp&gt;"> <link rel="prev" href="odtone/mih/operator_idp11211072.html" title="Function operator&lt;&lt;"> <link rel="next" href="odtone/bind_rv_.html" title="Struct template bind_rv_"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="'ODTONE - Open Dot Twenty One'" width="100" height="100" src="./images/logo.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="odtone/mih/operator_idp11211072.html"><img src="images/prev.png" alt="Prev"></a><a accesskey="u" href="odtone_base_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.types.base_hpp"><img src="images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="images/home.png" alt="Home"></a><a accesskey="n" href="odtone/bind_rv_.html"><img src="images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="operator++"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Function template operator++</span></h2> <p>operator++</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="odtone_base_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.types.base_hpp" title="Header &lt;/home/carlos/Projectos/odtone/inc/odtone/mih/types/base.hpp&gt;">/home/carlos/Projectos/odtone/inc/odtone/mih/types/base.hpp</a>&gt; </span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> EnumT<span class="special">&gt;</span> <span class="identifier">EnumT</span> <span class="keyword">operator</span><span class="special">++</span><span class="special">(</span><span class="identifier">EnumT</span> <span class="special">&amp;</span> rs<span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp65712112"></a><h2>Description</h2> <p>Define a postfix increment operator for enumeration types. </p> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2009-2013 Universidade Aveiro<br>Copyright &#169; 2009-2013 Instituto de Telecomunica&#231;&#245;es - P&#243;lo Aveiro<p> This software is distributed under a license. The full license agreement can be found in the LICENSE in this distribution. This software may not be copied, modified, sold or distributed other than expressed in the named license agreement. This software is distributed without any warranty. </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="odtone/mih/operator_idp11211072.html"><img src="images/prev.png" alt="Prev"></a><a accesskey="u" href="odtone_base_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.types.base_hpp"><img src="images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="images/home.png" alt="Home"></a><a accesskey="n" href="odtone/bind_rv_.html"><img src="images/next.png" alt="Next"></a> </div> </body> </html>
phra/802_21
myODTONE/doc/html/operator__.html
HTML
gpl-2.0
3,929
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import com.oracle.java.testlibrary.Asserts; import java.lang.management.MemoryType; import sun.hotspot.code.BlobType; /** * @test BeanTypeTest * @library /testlibrary /../../test/lib * @modules java.management * @build BeanTypeTest * @run main ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions * -XX:+WhiteBoxAPI -XX:+SegmentedCodeCache BeanTypeTest * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions * -XX:+WhiteBoxAPI -XX:-SegmentedCodeCache BeanTypeTest * @summary verify types of code cache memory pool bean */ public class BeanTypeTest { public static void main(String args[]) { for (BlobType bt : BlobType.getAvailable()) { Asserts.assertEQ(MemoryType.NON_HEAP, bt.getMemoryPool().getType()); } } }
netroby/hotspot9
test/compiler/codecache/jmx/BeanTypeTest.java
Java
gpl-2.0
1,948
#include "EOSProjectData.h" EOSProjectData::EOSProjectData() { } EOSProjectData::~EOSProjectData() { }
eranif/codelite
EOSWiki/EOSProjectData.cpp
C++
gpl-2.0
106
/** * TODO: legal stuff * * purple * * Purple is the legal property of its developers, whose names are too numerous * to list here. Please refer to the COPYRIGHT file distributed with this * source distribution. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ #include <glib/gstdio.h> #include "prpltwtr.h" typedef struct { PurpleAccount *account; gchar *username; } TwitterAccountUserNameChange; static GHashTable *oauth_result_to_hashtable(const gchar * txt); static void account_mismatch_screenname_change_cancel_cb(TwitterAccountUserNameChange * change, gint action_id); static void account_mismatch_screenname_change_ok_cb(TwitterAccountUserNameChange * change, gint action_id); static void account_username_change_verify(PurpleAccount * account, const gchar * username); static void verify_credentials_success_cb(TwitterRequestor * r, xmlnode * node, gpointer user_data); static void verify_credentials_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data); static void oauth_request_token_success_cb(TwitterRequestor * r, const gchar * response, gpointer user_data); static void oauth_request_token_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data); static const gchar *account_get_oauth_access_token(PurpleAccount * account); static void account_set_oauth_access_token(PurpleAccount * account, const gchar * oauth_token); static const gchar *account_get_oauth_access_token_secret(PurpleAccount * account); static void account_set_oauth_access_token_secret(PurpleAccount * account, const gchar * oauth_token); static void oauth_request_pin_ok(PurpleAccount * account, const gchar * pin); static void oauth_request_pin_cancel(PurpleAccount * account, const gchar * pin); static void oauth_access_token_success_cb(TwitterRequestor * r, const gchar * response, gpointer user_data); static void oauth_access_token_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data); static const gchar *twitter_option_url_oauth_authorize(PurpleAccount * account); static const gchar *twitter_option_url_oauth_access_token(PurpleAccount * account); static const gchar *twitter_option_url_oauth_request_token(PurpleAccount * account); static const gchar *twitter_oauth_create_url(PurpleAccount * account, const gchar * endpoint); void prpltwtr_auth_invalidate_token(PurpleAccount * account) { account_set_oauth_access_token(account, NULL); account_set_oauth_access_token_secret(account, NULL); } void prpltwtr_auth_pre_send_auth_basic(TwitterRequestor * r, gboolean * post, const char **url, TwitterRequestParams ** params, gchar *** header_fields, gpointer * requestor_data) { const char *pass = purple_connection_get_password(purple_account_get_connection(r->account)); char **userparts = g_strsplit(purple_account_get_username(r->account), "@", 2); const char *sn = userparts[0]; char *auth_text = g_strdup_printf("%s:%s", sn, pass); char *auth_text_b64 = purple_base64_encode((guchar *) auth_text, strlen(auth_text)); *header_fields = g_new(gchar *, 2); (*header_fields)[0] = g_strdup_printf("Authorization: Basic %s", auth_text_b64); (*header_fields)[1] = NULL; g_strfreev(userparts); g_free(auth_text); g_free(auth_text_b64); } void prpltwtr_auth_post_send_auth_basic(TwitterRequestor * r, gboolean * post, const char **url, TwitterRequestParams ** params, gchar *** header_fields, gpointer * requestor_data) { g_strfreev(*header_fields); } const gchar *prpltwtr_auth_get_oauth_key(PurpleAccount * account) { if (!strcmp(purple_account_get_protocol_id(account), TWITTER_PROTOCOL_ID)) { return TWITTER_OAUTH_KEY; } else { const gchar *key = purple_account_get_string(account, TWITTER_PREF_CONSUMER_KEY, ""); if (!strcmp(key, "")) { purple_debug_error(purple_account_get_protocol_id(account), "No Consumer key specified!\n"); } return key; } } const gchar *prpltwtr_auth_get_oauth_secret(PurpleAccount * account) { if (!strcmp(purple_account_get_protocol_id(account), TWITTER_PROTOCOL_ID)) { return TWITTER_OAUTH_SECRET; } else { const gchar *secret = purple_account_get_string(account, TWITTER_PREF_CONSUMER_SECRET, ""); if (!strcmp(secret, "")) { purple_debug_error(purple_account_get_protocol_id(account), "No Consumer secret specified!\n"); } return secret; } } void prpltwtr_auth_pre_send_oauth(TwitterRequestor * r, gboolean * post, const char **url, TwitterRequestParams ** params, gchar *** header_fields, gpointer * requestor_data) { PurpleAccount *account = r->account; PurpleConnection *gc = purple_account_get_connection(account); TwitterConnectionData *twitter = gc->proto_data; gchar *signing_key = g_strdup_printf("%s&%s", prpltwtr_auth_get_oauth_secret(account), twitter->oauth_token_secret ? twitter->oauth_token_secret : ""); TwitterRequestParams *oauth_params = twitter_request_params_add_oauth_params(account, *post, *url, *params, twitter->oauth_token, signing_key); if (oauth_params == NULL) { TwitterRequestErrorData *error = g_new0(TwitterRequestErrorData, 1); gchar *error_msg = g_strdup(_("Could not sign request")); error->type = TWITTER_REQUEST_ERROR_NO_OAUTH; error->message = error_msg; g_free(error_msg); g_free(error); g_free(signing_key); //TODO: error if couldn't sign return; } g_free(signing_key); *requestor_data = *params; *params = oauth_params; } void prpltwtr_auth_oauth_login(PurpleAccount * account, TwitterConnectionData * twitter) { const gchar *oauth_token; const gchar *oauth_token_secret; oauth_token = account_get_oauth_access_token(account); oauth_token_secret = account_get_oauth_access_token_secret(account); if (oauth_token && oauth_token_secret) { twitter->oauth_token = g_strdup(oauth_token); twitter->oauth_token_secret = g_strdup(oauth_token_secret); twitter_api_verify_credentials(purple_account_get_requestor(account), verify_credentials_success_cb, verify_credentials_error_cb, NULL); } else { twitter_send_request(purple_account_get_requestor(account), FALSE, twitter_option_url_oauth_request_token(account), NULL, oauth_request_token_success_cb, oauth_request_token_error_cb, NULL); } } void prpltwtr_auth_post_send_oauth(TwitterRequestor * r, gboolean * post, const char **url, TwitterRequestParams ** params, gchar *** header_fields, gpointer * requestor_data) { twitter_request_params_free(*params); *params = (TwitterRequestParams *) * requestor_data; } static void oauth_access_token_success_cb(TwitterRequestor * r, const gchar * response, gpointer user_data) { PurpleAccount *account = r->account; PurpleConnection *gc = purple_account_get_connection(account); TwitterConnectionData *twitter = gc->proto_data; GHashTable *results = oauth_result_to_hashtable(response); const gchar *oauth_token = g_hash_table_lookup(results, "oauth_token"); const gchar *oauth_token_secret = g_hash_table_lookup(results, "oauth_token_secret"); const gchar *response_screen_name = g_hash_table_lookup(results, "screen_name"); if (oauth_token && oauth_token_secret) { if (twitter->oauth_token) g_free(twitter->oauth_token); if (twitter->oauth_token_secret) g_free(twitter->oauth_token_secret); twitter->oauth_token = g_strdup(oauth_token); twitter->oauth_token_secret = g_strdup(oauth_token_secret); account_set_oauth_access_token(account, oauth_token); account_set_oauth_access_token_secret(account, oauth_token_secret); //FIXME: set this to be case insensitive { char **userparts = g_strsplit(purple_account_get_username(r->account), "@", 2); const char *username = userparts[0]; if (response_screen_name && !twitter_usernames_match(account, response_screen_name, username)) { account_username_change_verify(account, response_screen_name); } else { prpltwtr_verify_connection(account); } g_strfreev(userparts); } } else { purple_debug_error(purple_account_get_protocol_id(account), "Unknown error receiving access token: %s\n", response); prpltwtr_disconnect(account, _("Unknown response getting access token")); } } static void oauth_access_token_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data) { gchar *error = g_strdup_printf(_("Error verifying PIN: %s"), error_data->message ? error_data->message : _("unknown error")); prpltwtr_disconnect(r->account, error); g_free(error); } static GHashTable *oauth_result_to_hashtable(const gchar * txt) { gchar **pieces = g_strsplit(txt, "&", 0); GHashTable *results = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free); gchar **p; for (p = pieces; *p; p++) { gchar *equalpos = strchr(*p, '='); if (equalpos) { equalpos[0] = '\0'; g_hash_table_replace(results, g_strdup(*p), g_strdup(equalpos + 1)); } } g_strfreev(pieces); return results; } static void account_mismatch_screenname_change_cancel_cb(TwitterAccountUserNameChange * change, gint action_id) { PurpleAccount *account = change->account; prpltwtr_auth_invalidate_token(account); g_free(change->username); g_free(change); prpltwtr_disconnect(account, _("Username mismatch")); } static void account_mismatch_screenname_change_ok_cb(TwitterAccountUserNameChange * change, gint action_id) { PurpleAccount *account = change->account; purple_account_set_username(account, change->username); g_free(change->username); g_free(change); prpltwtr_verify_connection(account); } static void account_username_change_verify(PurpleAccount * account, const gchar * username) { PurpleConnection *gc = purple_account_get_connection(account); gchar *secondary = g_strdup_printf(_("Do you wish to change the name on this account to %s?"), username); TwitterAccountUserNameChange *change_data = (TwitterAccountUserNameChange *) g_new0(TwitterAccountUserNameChange *, 1); change_data->account = account; change_data->username = g_strdup(username); purple_request_action(gc, _("Mismatched Screen Names"), _("Authorized screen name does not match with account screen name"), secondary, 0, account, NULL, NULL, change_data, 2, _("Cancel"), account_mismatch_screenname_change_cancel_cb, _("Yes"), account_mismatch_screenname_change_ok_cb, NULL); g_free(secondary); } static void verify_credentials_success_cb(TwitterRequestor * r, xmlnode * node, gpointer user_data) { PurpleAccount *account = r->account; TwitterUserTweet *user_tweet = twitter_verify_credentials_parse(node); char **userparts = g_strsplit(purple_account_get_username(r->account), "@", 2); const char *username = userparts[0]; if (!user_tweet || !user_tweet->screen_name) { prpltwtr_disconnect(account, _("Could not verify credentials")); } else if (!twitter_usernames_match(account, user_tweet->screen_name, username)) { account_username_change_verify(account, user_tweet->screen_name); } else { prpltwtr_verify_connection(account); } g_strfreev(userparts); twitter_user_tweet_free(user_tweet); } static void verify_credentials_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data) { gchar *error = g_strdup_printf(_("Error verifying credentials: %s"), error_data->message ? error_data->message : _("unknown error")); switch (error_data->type) { case TWITTER_REQUEST_ERROR_SERVER: case TWITTER_REQUEST_ERROR_CANCELED: prpltwtr_recoverable_disconnect(r->account, error); break; case TWITTER_REQUEST_ERROR_NONE: case TWITTER_REQUEST_ERROR_TWITTER_GENERAL: case TWITTER_REQUEST_ERROR_INVALID_XML: case TWITTER_REQUEST_ERROR_NO_OAUTH: case TWITTER_REQUEST_ERROR_UNAUTHORIZED: default: prpltwtr_disconnect(r->account, error); break; } g_free(error); } static void oauth_request_token_success_cb(TwitterRequestor * r, const gchar * response, gpointer user_data) { PurpleAccount *account = r->account; PurpleConnection *gc = purple_account_get_connection(account); TwitterConnectionData *twitter = gc->proto_data; GHashTable *results = oauth_result_to_hashtable(response); const gchar *oauth_token = g_hash_table_lookup(results, "oauth_token"); const gchar *oauth_token_secret = g_hash_table_lookup(results, "oauth_token_secret"); if (oauth_token && oauth_token_secret) { /* http://api.twitter.com/oauth/authorize */ gchar *msg = g_strdup_printf("http://%s?oauth_token=%s", twitter_option_url_oauth_authorize(account), purple_url_encode(oauth_token)); gchar *prompt = g_strdup_printf("%s %s", _("Please enter PIN for"), purple_account_get_username(account)); twitter->oauth_token = g_strdup(oauth_token); twitter->oauth_token_secret = g_strdup(oauth_token_secret); purple_notify_uri(twitter, msg); purple_request_input(twitter, _("OAuth Authentication"), //title prompt, //primary msg, //secondary NULL, //default FALSE, //multiline, FALSE, //password NULL, //hint _("Submit"), //ok text G_CALLBACK(oauth_request_pin_ok), _("Cancel"), G_CALLBACK(oauth_request_pin_cancel), account, NULL, NULL, account); g_free(msg); g_free(prompt); } else { purple_debug_error(purple_account_get_protocol_id(account), "Unknown error receiving request token: %s\n", response); prpltwtr_disconnect(account, _("Invalid response receiving request token")); } g_hash_table_destroy(results); } static void oauth_request_token_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data) { gchar *error = g_strdup_printf(_("Error receiving request token: %s"), error_data->message ? error_data->message : _("unknown error")); prpltwtr_disconnect(r->account, error); g_free(error); } static const gchar *account_get_oauth_access_token(PurpleAccount * account) { return purple_account_get_string(account, "oauth_token", NULL); } static void account_set_oauth_access_token(PurpleAccount * account, const gchar * oauth_token) { purple_account_set_string(account, "oauth_token", oauth_token); } static const gchar *account_get_oauth_access_token_secret(PurpleAccount * account) { return purple_account_get_string(account, "oauth_token_secret", NULL); } static void account_set_oauth_access_token_secret(PurpleAccount * account, const gchar * oauth_token) { purple_account_set_string(account, "oauth_token_secret", oauth_token); } static void oauth_request_pin_ok(PurpleAccount * account, const gchar * pin) { TwitterRequestParams *params = twitter_request_params_new(); twitter_request_params_add(params, twitter_request_param_new("oauth_verifier", pin)); twitter_send_request(purple_account_get_requestor(account), FALSE, twitter_option_url_oauth_access_token(account), params, oauth_access_token_success_cb, oauth_access_token_error_cb, NULL); twitter_request_params_free(params); } static void oauth_request_pin_cancel(PurpleAccount * account, const gchar * pin) { prpltwtr_disconnect(account, _("Canceled PIN entry")); } static const gchar *twitter_option_url_oauth_authorize(PurpleAccount * account) { return twitter_oauth_create_url(account, "/authorize"); } static const gchar *twitter_option_url_oauth_request_token(PurpleAccount * account) { return twitter_oauth_create_url(account, "/request_token"); } static const gchar *twitter_option_url_oauth_access_token(PurpleAccount * account) { return twitter_oauth_create_url(account, "/access_token"); } static const gchar *twitter_oauth_create_url(PurpleAccount * account, const gchar * endpoint) { static char url[1024]; char host[256]; g_return_val_if_fail(endpoint != NULL && endpoint[0] != '\0', NULL); if (!strcmp(purple_account_get_protocol_id(account), TWITTER_PROTOCOL_ID)) { snprintf(host, 255, "api.twitter.com/oauth"); } else { snprintf(host, 255, "%s/oauth", purple_account_get_string(account, TWITTER_PREF_API_BASE, STATUSNET_PREF_API_BASE_DEFAULT)); } snprintf(url, 1023, "%s%s%s", host, host[strlen(host) - 1] == '/' || endpoint[0] == '/' ? "" : "/", host[strlen(host) - 1] == '/' && endpoint[0] == '/' ? endpoint + 1 : endpoint); return url; }
dmoonfire/prpltwtr-old
src/prpltwtr/prpltwtr_auth.c
C
gpl-2.0
18,305
/* * Definitions for akm8975 compass chip. */ #ifndef AKM8975_H #define AKM8975_H #include <linux/ioctl.h> #define AKM8975_I2C_NAME "akm8975" /*! \name AK8975 operation mode \anchor AK8975_Mode Defines an operation mode of the AK8975.*/ /*! @{*/ #define AK8975_MODE_SNG_MEASURE 0x01 #define AK8975_MODE_SELF_TEST 0x08 #define AK8975_MODE_FUSE_ACCESS 0x0F #define AK8975_MODE_POWERDOWN 0x00 /*! @}*/ #define SENSOR_DATA_SIZE 8 #define RWBUF_SIZE 16 /*! \name AK8975 register address \anchor AK8975_REG Defines a register address of the AK8975.*/ /*! @{*/ #define AK8975_REG_WIA 0x00 #define AK8975_REG_INFO 0x01 #define AK8975_REG_ST1 0x02 #define AK8975_REG_HXL 0x03 #define AK8975_REG_HXH 0x04 #define AK8975_REG_HYL 0x05 #define AK8975_REG_HYH 0x06 #define AK8975_REG_HZL 0x07 #define AK8975_REG_HZH 0x08 #define AK8975_REG_ST2 0x09 #define AK8975_REG_CNTL 0x0A #define AK8975_REG_RSV 0x0B #define AK8975_REG_ASTC 0x0C #define AK8975_REG_TS1 0x0D #define AK8975_REG_TS2 0x0E #define AK8975_REG_I2CDIS 0x0F /*! @}*/ /*! \name AK8975 fuse-rom address \anchor AK8975_FUSE Defines a read-only address of the fuse ROM of the AK8975.*/ /*! @{*/ #define AK8975_FUSE_ASAX 0x10 #define AK8975_FUSE_ASAY 0x11 #define AK8975_FUSE_ASAZ 0x12 /*! @}*/ #define AKMIO 0xA1 /* IOCTLs for AKM library */ #define ECS_IOCTL_WRITE _IOW(AKMIO, 0x01, char*) #define ECS_IOCTL_READ _IOWR(AKMIO, 0x02, char*) #define ECS_IOCTL_RESET _IO(AKMIO, 0x03) #define ECS_IOCTL_SET_MODE _IOW(AKMIO, 0x04, short) #define ECS_IOCTL_GETDATA _IOR(AKMIO, 0x05, char[SENSOR_DATA_SIZE]) #define ECS_IOCTL_SET_YPR _IOW(AKMIO, 0x06, short[12]) #define ECS_IOCTL_GET_OPEN_STATUS _IOR(AKMIO, 0x07, int) #define ECS_IOCTL_GET_CLOSE_STATUS _IOR(AKMIO, 0x08, int) #define ECS_IOCTL_GET_DELAY _IOR(AKMIO, 0x30, short) #define ECS_IOCTL_GET_PROJECT_NAME _IOR(AKMIO, 0x0D, char[64]) #define ECS_IOCTL_GET_MATRIX _IOR(AKMIO, 0x0E, short [4][3][3]) /* IOCTLs for APPs */ #define ECS_IOCTL_APP_SET_MODE _IOW(AKMIO, 0x10, short)/* NOT use */ #define ECS_IOCTL_APP_SET_MFLAG _IOW(AKMIO, 0x11, short) #define ECS_IOCTL_APP_GET_MFLAG _IOW(AKMIO, 0x12, short) #define ECS_IOCTL_APP_SET_AFLAG _IOW(AKMIO, 0x13, short) #define ECS_IOCTL_APP_GET_AFLAG _IOR(AKMIO, 0x14, short) #define ECS_IOCTL_APP_SET_TFLAG _IOR(AKMIO, 0x15, short)/* NOT use */ #define ECS_IOCTL_APP_GET_TFLAG _IOR(AKMIO, 0x16, short)/* NOT use */ #define ECS_IOCTL_APP_RESET_PEDOMETER _IO(AKMIO, 0x17) /* NOT use */ #define ECS_IOCTL_APP_SET_DELAY _IOW(AKMIO, 0x18, short) #define ECS_IOCTL_APP_GET_DELAY ECS_IOCTL_GET_DELAY #define ECS_IOCTL_APP_SET_MVFLAG _IOW(AKMIO, 0x19, short) #define ECS_IOCTL_APP_GET_MVFLAG _IOR(AKMIO, 0x1A, short) /* */ #define ECS_IOCTL_APP_SET_PFLAG _IOR(AKMIO, 0x1B, short) /* Get proximity flag */ #define ECS_IOCTL_APP_GET_PFLAG _IOR(AKMIO, 0x1C, short) /* Set proximity flag */ /* */ #define ECS_IOCTL_GET_ACCEL_PATH _IOR(AKMIO, 0x20, char[30]) #define ECS_IOCTL_ACCEL_INIT _IOR(AKMIO, 0x21, int[7]) #define ECS_IOCTL_GET_ALAYOUT_INIO _IOR(AKMIO, 0x22, signed short[18]) #define ECS_IOCTL_GET_HLAYOUT_INIO _IOR(AKMIO, 0x23, signed short[18]) #define AKMD2_TO_ACCEL_IOCTL_READ_XYZ _IOWR(AKMIO, 0x31, int) #define AKMD2_TO_ACCEL_IOCTL_ACCEL_INIT _IOWR(AKMIO, 0x32, int) /* original source struct akm8975_platform_data { char layouts[3][3]; char project_name[64]; int gpio_DRDY; }; */ #endif
rcunningham12/L38C-Dynamic-Kernel
include/linux/akm8975.h
C
gpl-2.0
3,667
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Swift Kanban Webinar Series</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <meta name="robots" content="noindex,nofollow"/> </head> <body> <table align="center" style="float:none;width:500px; background-color:#FFFFFF; border: none; border-width: 0px; font-family: Arial;"> <tbody> <!--<tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px; text-align:center;"> <span style='font-size:9px;'>If you are not able to view the email properly click <a href='http://www.Swift-Kanban.com/emailer/masa_kanban_beyond_IT_ and_software/invitation_email.html'>Here</a></span> </td> <td style="width:5px;"></td> </tr> --> <tr style="vertical-align: middle;"> <td style="width:5px;"></td> <td style="width:120px; text-align: left;"> <a href="http://www.swift-kanban.com"> <img src="http://app.streamsend.com/public_images/266321/images/kanban.JPG" border="0" alt="Swift kanban Logo"/> </a> </td> <td style="width:370px; text-align: right;font-family: Arial; font-size: 13px; font-weight: bold; vertical-align: bottom;"> Dr. Masa Maeda Webinar </td> <td style="width:5px;"></td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px; text-align: left;font-size: 8px;"> <hr style="border: none;background-color:#d3d3d3;height: 3px;"/> </td> <td style="width:5px;"></td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px; text-align: left;font-family: Arial;font-weight: bold;line-height: 24px;"> <span style="font-size: 13px; color: #000000;">Webinar: Jun 06, 2012; 10 AM - 11 AM Pacific</span><br/> </td> <td style="width:5px;"></td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:500px; text-align: center;"> <center><a href="http://www.swift-kanban.com/masa_webinar"> <img src="http://www.swift-kanban.com/emailer/masa_kanban_beyond_IT_ and_software/webinar-header.jpg" style="width: 500px;height:101px;"/> </a></center> </td> <td style="width:5px;"></td> </tr> <tr style="height: 0px; font-size: 5px;"> <td colspan="3" style="height: 0px">&nbsp;</td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px; text-align: justify;font-family: Arial; font-size: 13px; line-height: 20px;"> <b style="line-height: 30px;">Kanban - Beyond IT and Software!</b><br/> One of the important contributors to the success of several organizations is alignment of IT strategy with Business for achieving Corporate Goals. If <strong><em>Reduced Waste</em></strong> and <strong><em>Smooth Flow</em></strong> (or streamlined processes) throughout the enterprise are part of your corporate strategy, then you should look at Kanban. While Kanban is making waves in IT operations and Software development, it is also proving invaluable for a number of forward-thinking business functions such as HR, sales, marketing, insurance claims and more! <br/> <br/> Come hear Dr. Masa K Maeda, renowned thought leader, consultant and coach for Lean Value Innovation, discuss the tremendous benefits of Kanban not only in IT but also for other divisions or BUs of your organization like Sales. <u>Invite your business colleagues</u> to collaboratively use Kanban for improving throughput, quality and other business benefits throughout the enterprise. <br/> <br/> <b style="font-size: 15px;">Click <a href="http://www.swift-kanban.com/masa_webinar"> here</a> to Register for the webinar</b><br/> Date: Jun 06, 2012; 10 AM - 11 AM Pacific <br/> <br/> Thank you and we hope that you will join us! <br/> <br/> Swift-Kanban Team <br/> <a href="http://www.swift-kanban.com">http://www.swift-kanban.com</a> </td> <td style="width:5px;"></td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px;height:5px;"> </td> <td style="width:5px;"></td> </tr> <!-- Social Media starts here--> <tr style="background-color: #99FFFF;"> <td colspan="3" style="width:540px;height:20px;"> <table> <tr> <td style="text-align: left;"> <table style="float: left;"> <tr> <td align="right" valign="middle" style='color: #000000; font-family: "Arial"; font-size:14px;'> Follow us: </td> <td align="center" valign="middle" style='color: #000000; font-family: "Arial";font-size:14px;'> <a style="text-decoration: none; border: medium none;" target="_blank" href="http://www.facebook.com/digite"><img src="http://cache.addthis.com/icons/v1/thumbs/facebook.gif" width="16px" border="0" alt=" f" title="Facebook"/></a> </td> <td align="center" valign="middle" style='color: #000000; font-family: "Arial";font-size:14px;'> <a style="text-decoration: none;" target="_blank" href="http://twitter.com/swiftkanban"><img src="http://cache.addthis.com/icons/v1/thumbs/twitter.gif" width="16px" hspace="0" border="0" alt=" t" title="Twitter"></a> </td> <td align="center" valign="middle" style='color: #000000; font-family: "Arial";font-size:14px;'> <a target="_blank" href="http://www.swift-kanban.com/community/blog"><img src="http://cache.addthiscdn.com/icons/v1/thumbs/blogger.gif" width="16px" border="0" alt=" B" title="Blog"></a> </td> <td align="center" valign="middle" style='color:#000000; font-family: "Arial";font-size:14px;'></a> </td> </tr> </table> </td> </tr> </table> </td> </tr> <!-- Social Media ends here --> <tr> <td colspan="3" style="width:540px; text-align: justify;font-family: Arial; font-size: 11px;"> Digite, Inc. is a leading provider of Lean/ Agile ALM and PPM products and solutions, based out of Mountain View, CA. Digite products and solutions have helped thousands of users around the world manage and deliver large and complex projects and applications executed by distributed teams, both in-house and outsourced. To learn more, please visit <a href="http://www.swift-kanban.com" target="_blank" style="text-decoration: none;">www.swift-kanban.com</a> or <a href="http://www.digite.com" target="_blank" style="text-decoration: none;">www.digite.com<br/> <br/> </a><em>Copyright &copy; 2012 Digite, Inc. All rights reserved.</em> <br/> You are receiving this email as you signed up with Digite or one of our media partners. If you have any questions, please contact us at <a href="mailto:marketing@digite.com" style="text-decoration: none;">marketing@digite.com </a> <br/> <br/> Our mailing address is: Digite, Inc., 82 Pioneer Way, Suite 102, Mountain View, CA 94041 <br/><br/> <!-- To manage your communication preferences/subscription with us <a href="{{{unsubscribe}}}">click here</a> --> </td> </tr> </tbody> </table> </body> </html>
xenten/swift-kanban
emailer/masa_kanban_beyond_IT_and_software/invitation_email.html
HTML
gpl-2.0
9,227
/* * Copyright 2002-2011 the original author or authors. * * 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. */ package org.springframework.cache.interceptor; import java.io.Serializable; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; /** * AOP Alliance MethodInterceptor for declarative cache * management using the common Spring caching infrastructure * ({@link org.springframework.cache.Cache}). * * <p>Derives from the {@link CacheAspectSupport} class which * contains the integration with Spring's underlying caching API. * CacheInterceptor simply calls the relevant superclass methods * in the correct order. * * <p>CacheInterceptors are thread-safe. * * @author Costin Leau * @author Juergen Hoeller * @since 3.1 */ @SuppressWarnings("serial") public class CacheInterceptor extends CacheAspectSupport implements MethodInterceptor, Serializable { private static class ThrowableWrapper extends RuntimeException { private final Throwable original; ThrowableWrapper(Throwable original) { this.original = original; } } public Object invoke(final MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); Invoker aopAllianceInvoker = new Invoker() { public Object invoke() { try { return invocation.proceed(); } catch (Throwable ex) { throw new ThrowableWrapper(ex); } } }; try { return execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments()); } catch (ThrowableWrapper th) { throw th.original; } } }
deathspeeder/class-guard
spring-framework-3.2.x/spring-context/src/main/java/org/springframework/cache/interceptor/CacheInterceptor.java
Java
gpl-2.0
2,142
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.protocols.jmx.connectors; import javax.management.MBeanServerConnection; /* * This interface defines the ability to handle a live connection and the ability to * close it. * * @author <A HREF="mailto:mike@opennms.org">Mike Jamison </A> * @author <A HREF="http://www.opennms.org/">OpenNMS </A> */ /** * <p>ConnectionWrapper interface.</p> * * @author ranger * @version $Id: $ */ public interface ConnectionWrapper { /** * <p>getMBeanServer</p> * * @return a {@link javax.management.MBeanServerConnection} object. */ public MBeanServerConnection getMBeanServer(); /** * <p>close</p> */ public void close(); }
tharindum/opennms_dashboard
opennms-services/src/main/java/org/opennms/protocols/jmx/connectors/ConnectionWrapper.java
Java
gpl-2.0
1,879
/* $Id: UIMachineDefs.h $ */ /** @file * VBox Qt GUI - Defines for Virtual Machine classes. */ /* * Copyright (C) 2010-2012 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifndef __UIMachineDefs_h__ #define __UIMachineDefs_h__ /* Global includes */ #include <iprt/cdefs.h> /* Machine elements enum: */ enum UIVisualElement { UIVisualElement_WindowTitle = RT_BIT(0), UIVisualElement_MouseIntegrationStuff = RT_BIT(1), UIVisualElement_IndicatorPoolStuff = RT_BIT(2), UIVisualElement_HDStuff = RT_BIT(3), UIVisualElement_CDStuff = RT_BIT(4), UIVisualElement_FDStuff = RT_BIT(5), UIVisualElement_NetworkStuff = RT_BIT(6), UIVisualElement_USBStuff = RT_BIT(7), UIVisualElement_SharedFolderStuff = RT_BIT(8), UIVisualElement_Display = RT_BIT(9), UIVisualElement_VideoCapture = RT_BIT(10), UIVisualElement_FeaturesStuff = RT_BIT(11), #ifndef Q_WS_MAC UIVisualElement_MiniToolBar = RT_BIT(12), #endif /* !Q_WS_MAC */ UIVisualElement_AllStuff = 0xFFFF }; /* Mouse states enum: */ enum UIMouseStateType { UIMouseStateType_MouseCaptured = RT_BIT(0), UIMouseStateType_MouseAbsolute = RT_BIT(1), UIMouseStateType_MouseAbsoluteDisabled = RT_BIT(2), UIMouseStateType_MouseNeedsHostCursor = RT_BIT(3) }; /* Machine View states enum: */ enum UIViewStateType { UIViewStateType_KeyboardCaptured = RT_BIT(0), UIViewStateType_HostKeyPressed = RT_BIT(1) }; #endif // __UIMachineDefs_h__
sobomax/virtualbox_64bit_edd
src/VBox/Frontends/VirtualBox/src/runtime/UIMachineDefs.h
C
gpl-2.0
2,072
/* * net/dccp/ipv4.c * * An implementation of the DCCP protocol * Arnaldo Carvalho de Melo <acme@conectiva.com.br> * * 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. */ #include <linux/dccp.h> #include <linux/icmp.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/random.h> #include <net/icmp.h> #include <net/inet_common.h> #include <net/inet_hashtables.h> #include <net/inet_sock.h> #include <net/protocol.h> #include <net/sock.h> #include <net/timewait_sock.h> #include <net/tcp_states.h> #include <net/xfrm.h> #include "ackvec.h" #include "ccid.h" #include "dccp.h" #include "feat.h" /* * This is the global socket data structure used for responding to * the Out-of-the-blue (OOTB) packets. A control sock will be created * for this socket at the initialization time. */ static struct socket *dccp_v4_ctl_socket; static int dccp_v4_get_port(struct sock *sk, const unsigned short snum) { return inet_csk_get_port(&dccp_hashinfo, sk, snum, inet_csk_bind_conflict); } int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct inet_sock *inet = inet_sk(sk); struct dccp_sock *dp = dccp_sk(sk); const struct sockaddr_in *usin = (struct sockaddr_in *)uaddr; struct rtable *rt; __be32 daddr, nexthop; int tmp; int err; dp->dccps_role = DCCP_ROLE_CLIENT; if (addr_len < sizeof(struct sockaddr_in)) return -EINVAL; if (usin->sin_family != AF_INET) return -EAFNOSUPPORT; nexthop = daddr = usin->sin_addr.s_addr; if (inet->opt != NULL && inet->opt->srr) { if (daddr == 0) return -EINVAL; nexthop = inet->opt->faddr; } tmp = ip_route_connect(&rt, nexthop, inet->saddr, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if, IPPROTO_DCCP, inet->sport, usin->sin_port, sk); if (tmp < 0) return tmp; if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) { ip_rt_put(rt); return -ENETUNREACH; } if (inet->opt == NULL || !inet->opt->srr) daddr = rt->rt_dst; if (inet->saddr == 0) inet->saddr = rt->rt_src; inet->rcv_saddr = inet->saddr; inet->dport = usin->sin_port; inet->daddr = daddr; inet_csk(sk)->icsk_ext_hdr_len = 0; if (inet->opt != NULL) inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen; /* * Socket identity is still unknown (sport may be zero). * However we set state to DCCP_REQUESTING and not releasing socket * lock select source port, enter ourselves into the hash tables and * complete initialization after this. */ dccp_set_state(sk, DCCP_REQUESTING); err = inet_hash_connect(&dccp_death_row, sk); if (err != 0) goto failure; err = ip_route_newports(&rt, IPPROTO_DCCP, inet->sport, inet->dport, sk); if (err != 0) goto failure; /* OK, now commit destination to socket. */ sk_setup_caps(sk, &rt->u.dst); dp->dccps_iss = secure_dccp_sequence_number(inet->saddr, inet->daddr, inet->sport, inet->dport); inet->id = dp->dccps_iss ^ jiffies; err = dccp_connect(sk); rt = NULL; if (err != 0) goto failure; out: return err; failure: /* * This unhashes the socket and releases the local port, if necessary. */ dccp_set_state(sk, DCCP_CLOSED); ip_rt_put(rt); sk->sk_route_caps = 0; inet->dport = 0; goto out; } EXPORT_SYMBOL_GPL(dccp_v4_connect); /* * This routine does path mtu discovery as defined in RFC1191. */ static inline void dccp_do_pmtu_discovery(struct sock *sk, const struct iphdr *iph, u32 mtu) { struct dst_entry *dst; const struct inet_sock *inet = inet_sk(sk); const struct dccp_sock *dp = dccp_sk(sk); /* We are not interested in DCCP_LISTEN and request_socks (RESPONSEs * send out by Linux are always < 576bytes so they should go through * unfragmented). */ if (sk->sk_state == DCCP_LISTEN) return; /* We don't check in the destentry if pmtu discovery is forbidden * on this route. We just assume that no packet_to_big packets * are send back when pmtu discovery is not active. * There is a small race when the user changes this flag in the * route, but I think that's acceptable. */ if ((dst = __sk_dst_check(sk, 0)) == NULL) return; dst->ops->update_pmtu(dst, mtu); /* Something is about to be wrong... Remember soft error * for the case, if this connection will not able to recover. */ if (mtu < dst_mtu(dst) && ip_dont_fragment(sk, dst)) sk->sk_err_soft = EMSGSIZE; mtu = dst_mtu(dst); if (inet->pmtudisc != IP_PMTUDISC_DONT && inet_csk(sk)->icsk_pmtu_cookie > mtu) { dccp_sync_mss(sk, mtu); /* * From RFC 4340, sec. 14.1: * * DCCP-Sync packets are the best choice for upward * probing, since DCCP-Sync probes do not risk application * data loss. */ dccp_send_sync(sk, dp->dccps_gsr, DCCP_PKT_SYNC); } /* else let the usual retransmit timer handle it */ } /* * This routine is called by the ICMP module when it gets some sort of error * condition. If err < 0 then the socket should be closed and the error * returned to the user. If err > 0 it's just the icmp type << 8 | icmp code. * After adjustment header points to the first 8 bytes of the tcp header. We * need to find the appropriate port. * * The locking strategy used here is very "optimistic". When someone else * accesses the socket the ICMP is just dropped and for some paths there is no * check at all. A more general error queue to queue errors for later handling * is probably better. */ static void dccp_v4_err(struct sk_buff *skb, u32 info) { const struct iphdr *iph = (struct iphdr *)skb->data; const struct dccp_hdr *dh = (struct dccp_hdr *)(skb->data + (iph->ihl << 2)); struct dccp_sock *dp; struct inet_sock *inet; const int type = skb->h.icmph->type; const int code = skb->h.icmph->code; struct sock *sk; __u64 seq; int err; if (skb->len < (iph->ihl << 2) + 8) { ICMP_INC_STATS_BH(ICMP_MIB_INERRORS); return; } sk = inet_lookup(&dccp_hashinfo, iph->daddr, dh->dccph_dport, iph->saddr, dh->dccph_sport, inet_iif(skb)); if (sk == NULL) { ICMP_INC_STATS_BH(ICMP_MIB_INERRORS); return; } if (sk->sk_state == DCCP_TIME_WAIT) { inet_twsk_put(inet_twsk(sk)); return; } bh_lock_sock(sk); /* If too many ICMPs get dropped on busy * servers this needs to be solved differently. */ if (sock_owned_by_user(sk)) NET_INC_STATS_BH(LINUX_MIB_LOCKDROPPEDICMPS); if (sk->sk_state == DCCP_CLOSED) goto out; dp = dccp_sk(sk); seq = dccp_hdr_seq(skb); if (sk->sk_state != DCCP_LISTEN && !between48(seq, dp->dccps_swl, dp->dccps_swh)) { NET_INC_STATS_BH(LINUX_MIB_OUTOFWINDOWICMPS); goto out; } switch (type) { case ICMP_SOURCE_QUENCH: /* Just silently ignore these. */ goto out; case ICMP_PARAMETERPROB: err = EPROTO; break; case ICMP_DEST_UNREACH: if (code > NR_ICMP_UNREACH) goto out; if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */ if (!sock_owned_by_user(sk)) dccp_do_pmtu_discovery(sk, iph, info); goto out; } err = icmp_err_convert[code].errno; break; case ICMP_TIME_EXCEEDED: err = EHOSTUNREACH; break; default: goto out; } switch (sk->sk_state) { struct request_sock *req , **prev; case DCCP_LISTEN: if (sock_owned_by_user(sk)) goto out; req = inet_csk_search_req(sk, &prev, dh->dccph_dport, iph->daddr, iph->saddr); if (!req) goto out; /* * ICMPs are not backlogged, hence we cannot get an established * socket here. */ BUG_TRAP(!req->sk); if (seq != dccp_rsk(req)->dreq_iss) { NET_INC_STATS_BH(LINUX_MIB_OUTOFWINDOWICMPS); goto out; } /* * Still in RESPOND, just remove it silently. * There is no good way to pass the error to the newly * created socket, and POSIX does not want network * errors returned from accept(). */ inet_csk_reqsk_queue_drop(sk, req, prev); goto out; case DCCP_REQUESTING: case DCCP_RESPOND: if (!sock_owned_by_user(sk)) { DCCP_INC_STATS_BH(DCCP_MIB_ATTEMPTFAILS); sk->sk_err = err; sk->sk_error_report(sk); dccp_done(sk); } else sk->sk_err_soft = err; goto out; } /* If we've already connected we will keep trying * until we time out, or the user gives up. * * rfc1122 4.2.3.9 allows to consider as hard errors * only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too, * but it is obsoleted by pmtu discovery). * * Note, that in modern internet, where routing is unreliable * and in each dark corner broken firewalls sit, sending random * errors ordered by their masters even this two messages finally lose * their original sense (even Linux sends invalid PORT_UNREACHs) * * Now we are in compliance with RFCs. * --ANK (980905) */ inet = inet_sk(sk); if (!sock_owned_by_user(sk) && inet->recverr) { sk->sk_err = err; sk->sk_error_report(sk); } else /* Only an error on timeout */ sk->sk_err_soft = err; out: bh_unlock_sock(sk); sock_put(sk); } static inline __sum16 dccp_v4_csum_finish(struct sk_buff *skb, __be32 src, __be32 dst) { return csum_tcpudp_magic(src, dst, skb->len, IPPROTO_DCCP, skb->csum); } void dccp_v4_send_check(struct sock *sk, int unused, struct sk_buff *skb) { const struct inet_sock *inet = inet_sk(sk); struct dccp_hdr *dh = dccp_hdr(skb); dccp_csum_outgoing(skb); dh->dccph_checksum = dccp_v4_csum_finish(skb, inet->saddr, inet->daddr); } EXPORT_SYMBOL_GPL(dccp_v4_send_check); static inline u64 dccp_v4_init_sequence(const struct sk_buff *skb) { return secure_dccp_sequence_number(skb->nh.iph->daddr, skb->nh.iph->saddr, dccp_hdr(skb)->dccph_dport, dccp_hdr(skb)->dccph_sport); } /* * The three way handshake has completed - we got a valid ACK or DATAACK - * now create the new socket. * * This is the equivalent of TCP's tcp_v4_syn_recv_sock */ struct sock *dccp_v4_request_recv_sock(struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst) { struct inet_request_sock *ireq; struct inet_sock *newinet; struct dccp_sock *newdp; struct sock *newsk; if (sk_acceptq_is_full(sk)) goto exit_overflow; if (dst == NULL && (dst = inet_csk_route_req(sk, req)) == NULL) goto exit; newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto exit; sk_setup_caps(newsk, dst); newdp = dccp_sk(newsk); newinet = inet_sk(newsk); ireq = inet_rsk(req); newinet->daddr = ireq->rmt_addr; newinet->rcv_saddr = ireq->loc_addr; newinet->saddr = ireq->loc_addr; newinet->opt = ireq->opt; ireq->opt = NULL; newinet->mc_index = inet_iif(skb); newinet->mc_ttl = skb->nh.iph->ttl; newinet->id = jiffies; dccp_sync_mss(newsk, dst_mtu(dst)); __inet_hash(&dccp_hashinfo, newsk, 0); __inet_inherit_port(&dccp_hashinfo, sk, newsk); return newsk; exit_overflow: NET_INC_STATS_BH(LINUX_MIB_LISTENOVERFLOWS); exit: NET_INC_STATS_BH(LINUX_MIB_LISTENDROPS); dst_release(dst); return NULL; } EXPORT_SYMBOL_GPL(dccp_v4_request_recv_sock); static struct sock *dccp_v4_hnd_req(struct sock *sk, struct sk_buff *skb) { const struct dccp_hdr *dh = dccp_hdr(skb); const struct iphdr *iph = skb->nh.iph; struct sock *nsk; struct request_sock **prev; /* Find possible connection requests. */ struct request_sock *req = inet_csk_search_req(sk, &prev, dh->dccph_sport, iph->saddr, iph->daddr); if (req != NULL) return dccp_check_req(sk, skb, req, prev); nsk = inet_lookup_established(&dccp_hashinfo, iph->saddr, dh->dccph_sport, iph->daddr, dh->dccph_dport, inet_iif(skb)); if (nsk != NULL) { if (nsk->sk_state != DCCP_TIME_WAIT) { bh_lock_sock(nsk); return nsk; } inet_twsk_put(inet_twsk(nsk)); return NULL; } return sk; } static struct dst_entry* dccp_v4_route_skb(struct sock *sk, struct sk_buff *skb) { struct rtable *rt; struct flowi fl = { .oif = ((struct rtable *)skb->dst)->rt_iif, .nl_u = { .ip4_u = { .daddr = skb->nh.iph->saddr, .saddr = skb->nh.iph->daddr, .tos = RT_CONN_FLAGS(sk) } }, .proto = sk->sk_protocol, .uli_u = { .ports = { .sport = dccp_hdr(skb)->dccph_dport, .dport = dccp_hdr(skb)->dccph_sport } } }; security_skb_classify_flow(skb, &fl); if (ip_route_output_flow(&rt, &fl, sk, 0)) { IP_INC_STATS_BH(IPSTATS_MIB_OUTNOROUTES); return NULL; } return &rt->u.dst; } static int dccp_v4_send_response(struct sock *sk, struct request_sock *req, struct dst_entry *dst) { int err = -1; struct sk_buff *skb; /* First, grab a route. */ if (dst == NULL && (dst = inet_csk_route_req(sk, req)) == NULL) goto out; skb = dccp_make_response(sk, dst, req); if (skb != NULL) { const struct inet_request_sock *ireq = inet_rsk(req); struct dccp_hdr *dh = dccp_hdr(skb); dh->dccph_checksum = dccp_v4_csum_finish(skb, ireq->loc_addr, ireq->rmt_addr); memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt)); err = ip_build_and_send_pkt(skb, sk, ireq->loc_addr, ireq->rmt_addr, ireq->opt); err = net_xmit_eval(err); } out: dst_release(dst); return err; } static void dccp_v4_ctl_send_reset(struct sock *sk, struct sk_buff *rxskb) { int err; struct dccp_hdr *rxdh = dccp_hdr(rxskb), *dh; const int dccp_hdr_reset_len = sizeof(struct dccp_hdr) + sizeof(struct dccp_hdr_ext) + sizeof(struct dccp_hdr_reset); struct sk_buff *skb; struct dst_entry *dst; u64 seqno = 0; /* Never send a reset in response to a reset. */ if (rxdh->dccph_type == DCCP_PKT_RESET) return; if (((struct rtable *)rxskb->dst)->rt_type != RTN_LOCAL) return; dst = dccp_v4_route_skb(dccp_v4_ctl_socket->sk, rxskb); if (dst == NULL) return; skb = alloc_skb(dccp_v4_ctl_socket->sk->sk_prot->max_header, GFP_ATOMIC); if (skb == NULL) goto out; /* Reserve space for headers. */ skb_reserve(skb, dccp_v4_ctl_socket->sk->sk_prot->max_header); skb->dst = dst_clone(dst); dh = dccp_zeroed_hdr(skb, dccp_hdr_reset_len); /* Build DCCP header and checksum it. */ dh->dccph_type = DCCP_PKT_RESET; dh->dccph_sport = rxdh->dccph_dport; dh->dccph_dport = rxdh->dccph_sport; dh->dccph_doff = dccp_hdr_reset_len / 4; dh->dccph_x = 1; dccp_hdr_reset(skb)->dccph_reset_code = DCCP_SKB_CB(rxskb)->dccpd_reset_code; /* See "8.3.1. Abnormal Termination" in RFC 4340 */ if (DCCP_SKB_CB(rxskb)->dccpd_ack_seq != DCCP_PKT_WITHOUT_ACK_SEQ) dccp_set_seqno(&seqno, DCCP_SKB_CB(rxskb)->dccpd_ack_seq + 1); dccp_hdr_set_seq(dh, seqno); dccp_hdr_set_ack(dccp_hdr_ack_bits(skb), DCCP_SKB_CB(rxskb)->dccpd_seq); dccp_csum_outgoing(skb); dh->dccph_checksum = dccp_v4_csum_finish(skb, rxskb->nh.iph->saddr, rxskb->nh.iph->daddr); bh_lock_sock(dccp_v4_ctl_socket->sk); err = ip_build_and_send_pkt(skb, dccp_v4_ctl_socket->sk, rxskb->nh.iph->daddr, rxskb->nh.iph->saddr, NULL); bh_unlock_sock(dccp_v4_ctl_socket->sk); if (net_xmit_eval(err) == 0) { DCCP_INC_STATS_BH(DCCP_MIB_OUTSEGS); DCCP_INC_STATS_BH(DCCP_MIB_OUTRSTS); } out: dst_release(dst); } static void dccp_v4_reqsk_destructor(struct request_sock *req) { kfree(inet_rsk(req)->opt); } static struct request_sock_ops dccp_request_sock_ops __read_mostly = { .family = PF_INET, .obj_size = sizeof(struct dccp_request_sock), .rtx_syn_ack = dccp_v4_send_response, .send_ack = dccp_reqsk_send_ack, .destructor = dccp_v4_reqsk_destructor, .send_reset = dccp_v4_ctl_send_reset, }; int dccp_v4_conn_request(struct sock *sk, struct sk_buff *skb) { struct inet_request_sock *ireq; struct request_sock *req; struct dccp_request_sock *dreq; const __be32 service = dccp_hdr_request(skb)->dccph_req_service; struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb); __u8 reset_code = DCCP_RESET_CODE_TOO_BUSY; /* Never answer to DCCP_PKT_REQUESTs send to broadcast or multicast */ if (((struct rtable *)skb->dst)->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) { reset_code = DCCP_RESET_CODE_NO_CONNECTION; goto drop; } if (dccp_bad_service_code(sk, service)) { reset_code = DCCP_RESET_CODE_BAD_SERVICE_CODE; goto drop; } /* * TW buckets are converted to open requests without * limitations, they conserve resources and peer is * evidently real one. */ if (inet_csk_reqsk_queue_is_full(sk)) goto drop; /* * Accept backlog is full. If we have already queued enough * of warm entries in syn queue, drop request. It is better than * clogging syn queue with openreqs with exponentially increasing * timeout. */ if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1) goto drop; req = reqsk_alloc(&dccp_request_sock_ops); if (req == NULL) goto drop; if (dccp_parse_options(sk, skb)) goto drop_and_free; dccp_reqsk_init(req, skb); if (security_inet_conn_request(sk, skb, req)) goto drop_and_free; ireq = inet_rsk(req); ireq->loc_addr = skb->nh.iph->daddr; ireq->rmt_addr = skb->nh.iph->saddr; ireq->opt = NULL; /* * Step 3: Process LISTEN state * * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init Cookie * * In fact we defer setting S.GSR, S.SWL, S.SWH to * dccp_create_openreq_child. */ dreq = dccp_rsk(req); dreq->dreq_isr = dcb->dccpd_seq; dreq->dreq_iss = dccp_v4_init_sequence(skb); dreq->dreq_service = service; if (dccp_v4_send_response(sk, req, NULL)) goto drop_and_free; inet_csk_reqsk_queue_hash_add(sk, req, DCCP_TIMEOUT_INIT); return 0; drop_and_free: reqsk_free(req); drop: DCCP_INC_STATS_BH(DCCP_MIB_ATTEMPTFAILS); dcb->dccpd_reset_code = reset_code; return -1; } EXPORT_SYMBOL_GPL(dccp_v4_conn_request); int dccp_v4_do_rcv(struct sock *sk, struct sk_buff *skb) { struct dccp_hdr *dh = dccp_hdr(skb); if (sk->sk_state == DCCP_OPEN) { /* Fast path */ if (dccp_rcv_established(sk, skb, dh, skb->len)) goto reset; return 0; } /* * Step 3: Process LISTEN state * If P.type == Request or P contains a valid Init Cookie option, * (* Must scan the packet's options to check for Init * Cookies. Only Init Cookies are processed here, * however; other options are processed in Step 8. This * scan need only be performed if the endpoint uses Init * Cookies *) * (* Generate a new socket and switch to that socket *) * Set S := new socket for this port pair * S.state = RESPOND * Choose S.ISS (initial seqno) or set from Init Cookies * Initialize S.GAR := S.ISS * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init Cookies * Continue with S.state == RESPOND * (* A Response packet will be generated in Step 11 *) * Otherwise, * Generate Reset(No Connection) unless P.type == Reset * Drop packet and return * * NOTE: the check for the packet types is done in * dccp_rcv_state_process */ if (sk->sk_state == DCCP_LISTEN) { struct sock *nsk = dccp_v4_hnd_req(sk, skb); if (nsk == NULL) goto discard; if (nsk != sk) { if (dccp_child_process(sk, nsk, skb)) goto reset; return 0; } } if (dccp_rcv_state_process(sk, skb, dh, skb->len)) goto reset; return 0; reset: dccp_v4_ctl_send_reset(sk, skb); discard: kfree_skb(skb); return 0; } EXPORT_SYMBOL_GPL(dccp_v4_do_rcv); /** * dccp_invalid_packet - check for malformed packets * Implements RFC 4340, 8.5: Step 1: Check header basics * Packets that fail these checks are ignored and do not receive Resets. */ int dccp_invalid_packet(struct sk_buff *skb) { const struct dccp_hdr *dh; unsigned int cscov; if (skb->pkt_type != PACKET_HOST) return 1; /* If the packet is shorter than 12 bytes, drop packet and return */ if (!pskb_may_pull(skb, sizeof(struct dccp_hdr))) { DCCP_WARN("pskb_may_pull failed\n"); return 1; } dh = dccp_hdr(skb); /* If P.type is not understood, drop packet and return */ if (dh->dccph_type >= DCCP_PKT_INVALID) { DCCP_WARN("invalid packet type\n"); return 1; } /* * If P.Data Offset is too small for packet type, drop packet and return */ if (dh->dccph_doff < dccp_hdr_len(skb) / sizeof(u32)) { DCCP_WARN("P.Data Offset(%u) too small\n", dh->dccph_doff); return 1; } /* * If P.Data Offset is too too large for packet, drop packet and return */ if (!pskb_may_pull(skb, dh->dccph_doff * sizeof(u32))) { DCCP_WARN("P.Data Offset(%u) too large\n", dh->dccph_doff); return 1; } /* * If P.type is not Data, Ack, or DataAck and P.X == 0 (the packet * has short sequence numbers), drop packet and return */ if (dh->dccph_type >= DCCP_PKT_DATA && dh->dccph_type <= DCCP_PKT_DATAACK && dh->dccph_x == 0) { DCCP_WARN("P.type (%s) not Data || [Data]Ack, while P.X == 0\n", dccp_packet_name(dh->dccph_type)); return 1; } /* * If P.CsCov is too large for the packet size, drop packet and return. * This must come _before_ checksumming (not as RFC 4340 suggests). */ cscov = dccp_csum_coverage(skb); if (cscov > skb->len) { DCCP_WARN("P.CsCov %u exceeds packet length %d\n", dh->dccph_cscov, skb->len); return 1; } /* If header checksum is incorrect, drop packet and return. * (This step is completed in the AF-dependent functions.) */ skb->csum = skb_checksum(skb, 0, cscov, 0); return 0; } EXPORT_SYMBOL_GPL(dccp_invalid_packet); /* this is called when real data arrives */ static int dccp_v4_rcv(struct sk_buff *skb) { const struct dccp_hdr *dh; struct sock *sk; int min_cov; /* Step 1: Check header basics */ if (dccp_invalid_packet(skb)) goto discard_it; /* Step 1: If header checksum is incorrect, drop packet and return */ if (dccp_v4_csum_finish(skb, skb->nh.iph->saddr, skb->nh.iph->daddr)) { DCCP_WARN("dropped packet with invalid checksum\n"); goto discard_it; } dh = dccp_hdr(skb); DCCP_SKB_CB(skb)->dccpd_seq = dccp_hdr_seq(skb); DCCP_SKB_CB(skb)->dccpd_type = dh->dccph_type; dccp_pr_debug("%8.8s " "src=%u.%u.%u.%u@%-5d " "dst=%u.%u.%u.%u@%-5d seq=%llu", dccp_packet_name(dh->dccph_type), NIPQUAD(skb->nh.iph->saddr), ntohs(dh->dccph_sport), NIPQUAD(skb->nh.iph->daddr), ntohs(dh->dccph_dport), (unsigned long long) DCCP_SKB_CB(skb)->dccpd_seq); if (dccp_packet_without_ack(skb)) { DCCP_SKB_CB(skb)->dccpd_ack_seq = DCCP_PKT_WITHOUT_ACK_SEQ; dccp_pr_debug_cat("\n"); } else { DCCP_SKB_CB(skb)->dccpd_ack_seq = dccp_hdr_ack_seq(skb); dccp_pr_debug_cat(", ack=%llu\n", (unsigned long long) DCCP_SKB_CB(skb)->dccpd_ack_seq); } /* Step 2: * Look up flow ID in table and get corresponding socket */ sk = __inet_lookup(&dccp_hashinfo, skb->nh.iph->saddr, dh->dccph_sport, skb->nh.iph->daddr, dh->dccph_dport, inet_iif(skb)); /* * Step 2: * If no socket ... */ if (sk == NULL) { dccp_pr_debug("failed to look up flow ID in table and " "get corresponding socket\n"); goto no_dccp_socket; } /* * Step 2: * ... or S.state == TIMEWAIT, * Generate Reset(No Connection) unless P.type == Reset * Drop packet and return */ if (sk->sk_state == DCCP_TIME_WAIT) { dccp_pr_debug("sk->sk_state == DCCP_TIME_WAIT: do_time_wait\n"); inet_twsk_put(inet_twsk(sk)); goto no_dccp_socket; } /* * RFC 4340, sec. 9.2.1: Minimum Checksum Coverage * o if MinCsCov = 0, only packets with CsCov = 0 are accepted * o if MinCsCov > 0, also accept packets with CsCov >= MinCsCov */ min_cov = dccp_sk(sk)->dccps_pcrlen; if (dh->dccph_cscov && (min_cov == 0 || dh->dccph_cscov < min_cov)) { dccp_pr_debug("Packet CsCov %d does not satisfy MinCsCov %d\n", dh->dccph_cscov, min_cov); /* FIXME: "Such packets SHOULD be reported using Data Dropped * options (Section 11.7) with Drop Code 0, Protocol * Constraints." */ goto discard_and_relse; } if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_and_relse; nf_reset(skb); return sk_receive_skb(sk, skb, 1); no_dccp_socket: if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) goto discard_it; /* * Step 2: * If no socket ... * Generate Reset(No Connection) unless P.type == Reset * Drop packet and return */ if (dh->dccph_type != DCCP_PKT_RESET) { DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; dccp_v4_ctl_send_reset(sk, skb); } discard_it: kfree_skb(skb); return 0; discard_and_relse: sock_put(sk); goto discard_it; } static struct inet_connection_sock_af_ops dccp_ipv4_af_ops = { .queue_xmit = ip_queue_xmit, .send_check = dccp_v4_send_check, .rebuild_header = inet_sk_rebuild_header, .conn_request = dccp_v4_conn_request, .syn_recv_sock = dccp_v4_request_recv_sock, .net_header_len = sizeof(struct iphdr), .setsockopt = ip_setsockopt, .getsockopt = ip_getsockopt, .addr2sockaddr = inet_csk_addr2sockaddr, .sockaddr_len = sizeof(struct sockaddr_in), #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ip_setsockopt, .compat_getsockopt = compat_ip_getsockopt, #endif }; static int dccp_v4_init_sock(struct sock *sk) { static __u8 dccp_v4_ctl_sock_initialized; int err = dccp_init_sock(sk, dccp_v4_ctl_sock_initialized); if (err == 0) { if (unlikely(!dccp_v4_ctl_sock_initialized)) dccp_v4_ctl_sock_initialized = 1; inet_csk(sk)->icsk_af_ops = &dccp_ipv4_af_ops; } return err; } static struct timewait_sock_ops dccp_timewait_sock_ops = { .twsk_obj_size = sizeof(struct inet_timewait_sock), }; static struct proto dccp_v4_prot = { .name = "DCCP", .owner = THIS_MODULE, .close = dccp_close, .connect = dccp_v4_connect, .disconnect = dccp_disconnect, .ioctl = dccp_ioctl, .init = dccp_v4_init_sock, .setsockopt = dccp_setsockopt, .getsockopt = dccp_getsockopt, .sendmsg = dccp_sendmsg, .recvmsg = dccp_recvmsg, .backlog_rcv = dccp_v4_do_rcv, .hash = dccp_hash, .unhash = dccp_unhash, .accept = inet_csk_accept, .get_port = dccp_v4_get_port, .shutdown = dccp_shutdown, .destroy = dccp_destroy_sock, .orphan_count = &dccp_orphan_count, .max_header = MAX_DCCP_HEADER, .obj_size = sizeof(struct dccp_sock), .rsk_prot = &dccp_request_sock_ops, .twsk_prot = &dccp_timewait_sock_ops, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_dccp_setsockopt, .compat_getsockopt = compat_dccp_getsockopt, #endif }; static struct net_protocol dccp_v4_protocol = { .handler = dccp_v4_rcv, .err_handler = dccp_v4_err, .no_policy = 1, }; static const struct proto_ops inet_dccp_ops = { .family = PF_INET, .owner = THIS_MODULE, .release = inet_release, .bind = inet_bind, .connect = inet_stream_connect, .socketpair = sock_no_socketpair, .accept = inet_accept, .getname = inet_getname, /* FIXME: work on tcp_poll to rename it to inet_csk_poll */ .poll = dccp_poll, .ioctl = inet_ioctl, /* FIXME: work on inet_listen to rename it to sock_common_listen */ .listen = inet_dccp_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; static struct inet_protosw dccp_v4_protosw = { .type = SOCK_DCCP, .protocol = IPPROTO_DCCP, .prot = &dccp_v4_prot, .ops = &inet_dccp_ops, .capability = -1, .no_check = 0, .flags = INET_PROTOSW_ICSK, }; static int __init dccp_v4_init(void) { int err = proto_register(&dccp_v4_prot, 1); if (err != 0) goto out; err = inet_add_protocol(&dccp_v4_protocol, IPPROTO_DCCP); if (err != 0) goto out_proto_unregister; inet_register_protosw(&dccp_v4_protosw); err = inet_csk_ctl_sock_create(&dccp_v4_ctl_socket, PF_INET, SOCK_DCCP, IPPROTO_DCCP); if (err) goto out_unregister_protosw; out: return err; out_unregister_protosw: inet_unregister_protosw(&dccp_v4_protosw); inet_del_protocol(&dccp_v4_protocol, IPPROTO_DCCP); out_proto_unregister: proto_unregister(&dccp_v4_prot); goto out; } static void __exit dccp_v4_exit(void) { inet_unregister_protosw(&dccp_v4_protosw); inet_del_protocol(&dccp_v4_protocol, IPPROTO_DCCP); proto_unregister(&dccp_v4_prot); } module_init(dccp_v4_init); module_exit(dccp_v4_exit); /* * __stringify doesn't likes enums, so use SOCK_DCCP (6) and IPPROTO_DCCP (33) * values directly, Also cover the case where the protocol is not specified, * i.e. net-pf-PF_INET-proto-0-type-SOCK_DCCP */ MODULE_ALIAS("net-pf-" __stringify(PF_INET) "-proto-33-type-6"); MODULE_ALIAS("net-pf-" __stringify(PF_INET) "-proto-0-type-6"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Arnaldo Carvalho de Melo <acme@mandriva.com>"); MODULE_DESCRIPTION("DCCP - Datagram Congestion Controlled Protocol");
xiandaicxsj/copyKvm
net/dccp/ipv4.c
C
gpl-2.0
28,989
#ifndef __TYPES_V7__ #define __TYPES_V7__ #if defined(_WIN32) && defined(_MSC_VER) # define ALIGN_PREFIX(bytes) __declspec(align(bytes)) # define ALIGN_POSTFIX(bytes) # define FUNC_DEF_INLINE __inline # define FUNC_DEF_EXTERN_INLINE extern __inline #elif defined(__GNUC__) # define ALIGN_PREFIX(bytes) # define ALIGN_POSTFIX(bytes) __attribute__ ((aligned(bytes))) # if defined (_DEBUG) # define FUNC_DEF_EXTERN_INLINE extern __inline # define FUNC_DEF_INLINE static __inline # else # define FUNC_DEF_EXTERN_INLINE extern __inline # define FUNC_DEF_INLINE static __inline # endif #else # define ALIGN_PREFIX(bytes) # define ALIGN_POSTFIX(bytes) # error UNKNOWN COMPILER AND OS #endif #define ALIGN16_PREFIX ALIGN_PREFIX(16) #define ALIGN16_POSTFIX ALIGN_POSTFIX(16) #define FUNC_CALL_TYPE __fastcall #define FUNC_DEF_EXTERN extern typedef signed long long int64; typedef signed int int32; typedef signed short int16; typedef signed char int8; typedef unsigned long long uint64; typedef unsigned int uint32; typedef unsigned short uint16; typedef unsigned char uint8; typedef float float4[4]; typedef int32 int32_4[4]; typedef float float44[4][4]; typedef float ALIGN16_PREFIX vec4[4] ALIGN16_POSTFIX; typedef int32 ALIGN16_PREFIX ivec4[4] ALIGN16_POSTFIX; typedef float ALIGN16_PREFIX mtx[4][4] ALIGN16_POSTFIX; typedef float ALIGN16_PREFIX quat[4] ALIGN16_POSTFIX; typedef union _intf { float f; int32 i; } intf; #endif//__TYPES__
riffmasterv7/Projects
UberTest/src/types_v7.h
C
gpl-2.0
1,456
/* * Asterisk -- An open source telephony toolkit. * * Copyright (C) 1999 - 2008, Digium, Inc. * * Mark Spencer <markster@digium.com> * * See http://www.asterisk.org for more information about * the Asterisk project. Please do not directly contact * any of the maintainers of this project for assistance; * the project provides a web site, mailing lists and IRC * channels for your use. * * This program is free software, distributed under the terms of * the GNU General Public License Version 2. See the LICENSE file * at the top of the source tree. */ /*! \file * * \brief Core PBX routines. * * \author Mark Spencer <markster@digium.com> */ /*** MODULEINFO <support_level>core</support_level> ***/ #include "asterisk.h" ASTERISK_FILE_VERSION(__FILE__, "$Revision: 388532 $") #include "asterisk/_private.h" #include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */ #include <ctype.h> #include <time.h> #include <sys/time.h> #if defined(HAVE_SYSINFO) #include <sys/sysinfo.h> #endif #if defined(SOLARIS) #include <sys/loadavg.h> #endif #include "asterisk/lock.h" #include "asterisk/cli.h" #include "asterisk/pbx.h" #include "asterisk/channel.h" #include "asterisk/file.h" #include "asterisk/callerid.h" #include "asterisk/cdr.h" #include "asterisk/cel.h" #include "asterisk/config.h" #include "asterisk/term.h" #include "asterisk/time.h" #include "asterisk/manager.h" #include "asterisk/ast_expr.h" #include "asterisk/linkedlists.h" #define SAY_STUBS /* generate declarations and stubs for say methods */ #include "asterisk/say.h" #include "asterisk/utils.h" #include "asterisk/causes.h" #include "asterisk/musiconhold.h" #include "asterisk/app.h" #include "asterisk/devicestate.h" #include "asterisk/event.h" #include "asterisk/hashtab.h" #include "asterisk/module.h" #include "asterisk/indications.h" #include "asterisk/taskprocessor.h" #include "asterisk/xmldoc.h" #include "asterisk/astobj2.h" /*! * \note I M P O R T A N T : * * The speed of extension handling will likely be among the most important * aspects of this PBX. The switching scheme as it exists right now isn't * terribly bad (it's O(N+M), where N is the # of extensions and M is the avg # * of priorities, but a constant search time here would be great ;-) * * A new algorithm to do searching based on a 'compiled' pattern tree is introduced * here, and shows a fairly flat (constant) search time, even for over * 10000 patterns. * * Also, using a hash table for context/priority name lookup can help prevent * the find_extension routines from absorbing exponential cpu cycles as the number * of contexts/priorities grow. I've previously tested find_extension with red-black trees, * which have O(log2(n)) speed. Right now, I'm using hash tables, which do * searches (ideally) in O(1) time. While these techniques do not yield much * speed in small dialplans, they are worth the trouble in large dialplans. * */ /*** DOCUMENTATION <application name="Answer" language="en_US"> <synopsis> Answer a channel if ringing. </synopsis> <syntax> <parameter name="delay"> <para>Asterisk will wait this number of milliseconds before returning to the dialplan after answering the call.</para> </parameter> <parameter name="nocdr"> <para>Asterisk will send an answer signal to the calling phone, but will not set the disposition or answer time in the CDR for this call.</para> </parameter> </syntax> <description> <para>If the call has not been answered, this application will answer it. Otherwise, it has no effect on the call.</para> </description> <see-also> <ref type="application">Hangup</ref> </see-also> </application> <application name="BackGround" language="en_US"> <synopsis> Play an audio file while waiting for digits of an extension to go to. </synopsis> <syntax> <parameter name="filenames" required="true" argsep="&amp;"> <argument name="filename1" required="true" /> <argument name="filename2" multiple="true" /> </parameter> <parameter name="options"> <optionlist> <option name="s"> <para>Causes the playback of the message to be skipped if the channel is not in the <literal>up</literal> state (i.e. it hasn't been answered yet). If this happens, the application will return immediately.</para> </option> <option name="n"> <para>Don't answer the channel before playing the files.</para> </option> <option name="m"> <para>Only break if a digit hit matches a one digit extension in the destination context.</para> </option> </optionlist> </parameter> <parameter name="langoverride"> <para>Explicitly specifies which language to attempt to use for the requested sound files.</para> </parameter> <parameter name="context"> <para>This is the dialplan context that this application will use when exiting to a dialed extension.</para> </parameter> </syntax> <description> <para>This application will play the given list of files <emphasis>(do not put extension)</emphasis> while waiting for an extension to be dialed by the calling channel. To continue waiting for digits after this application has finished playing files, the <literal>WaitExten</literal> application should be used.</para> <para>If one of the requested sound files does not exist, call processing will be terminated.</para> <para>This application sets the following channel variable upon completion:</para> <variablelist> <variable name="BACKGROUNDSTATUS"> <para>The status of the background attempt as a text string.</para> <value name="SUCCESS" /> <value name="FAILED" /> </variable> </variablelist> </description> <see-also> <ref type="application">ControlPlayback</ref> <ref type="application">WaitExten</ref> <ref type="application">BackgroundDetect</ref> <ref type="function">TIMEOUT</ref> </see-also> </application> <application name="Busy" language="en_US"> <synopsis> Indicate the Busy condition. </synopsis> <syntax> <parameter name="timeout"> <para>If specified, the calling channel will be hung up after the specified number of seconds. Otherwise, this application will wait until the calling channel hangs up.</para> </parameter> </syntax> <description> <para>This application will indicate the busy condition to the calling channel.</para> </description> <see-also> <ref type="application">Congestion</ref> <ref type="application">Progress</ref> <ref type="application">Playtones</ref> <ref type="application">Hangup</ref> </see-also> </application> <application name="Congestion" language="en_US"> <synopsis> Indicate the Congestion condition. </synopsis> <syntax> <parameter name="timeout"> <para>If specified, the calling channel will be hung up after the specified number of seconds. Otherwise, this application will wait until the calling channel hangs up.</para> </parameter> </syntax> <description> <para>This application will indicate the congestion condition to the calling channel.</para> </description> <see-also> <ref type="application">Busy</ref> <ref type="application">Progress</ref> <ref type="application">Playtones</ref> <ref type="application">Hangup</ref> </see-also> </application> <application name="ExecIfTime" language="en_US"> <synopsis> Conditional application execution based on the current time. </synopsis> <syntax argsep="?"> <parameter name="day_condition" required="true"> <argument name="times" required="true" /> <argument name="weekdays" required="true" /> <argument name="mdays" required="true" /> <argument name="months" required="true" /> <argument name="timezone" required="false" /> </parameter> <parameter name="appname" required="true" hasparams="optional"> <argument name="appargs" required="true" /> </parameter> </syntax> <description> <para>This application will execute the specified dialplan application, with optional arguments, if the current time matches the given time specification.</para> </description> <see-also> <ref type="application">Exec</ref> <ref type="application">ExecIf</ref> <ref type="application">TryExec</ref> <ref type="application">GotoIfTime</ref> </see-also> </application> <application name="Goto" language="en_US"> <synopsis> Jump to a particular priority, extension, or context. </synopsis> <syntax> <parameter name="context" /> <parameter name="extensions" /> <parameter name="priority" required="true" /> </syntax> <description> <para>This application will set the current context, extension, and priority in the channel structure. After it completes, the pbx engine will continue dialplan execution at the specified location. If no specific <replaceable>extension</replaceable>, or <replaceable>extension</replaceable> and <replaceable>context</replaceable>, are specified, then this application will just set the specified <replaceable>priority</replaceable> of the current extension.</para> <para>At least a <replaceable>priority</replaceable> is required as an argument, or the goto will return a <literal>-1</literal>, and the channel and call will be terminated.</para> <para>If the location that is put into the channel information is bogus, and asterisk cannot find that location in the dialplan, then the execution engine will try to find and execute the code in the <literal>i</literal> (invalid) extension in the current context. If that does not exist, it will try to execute the <literal>h</literal> extension. If neither the <literal>h</literal> nor <literal>i</literal> extensions have been defined, the channel is hung up, and the execution of instructions on the channel is terminated. What this means is that, for example, you specify a context that does not exist, then it will not be possible to find the <literal>h</literal> or <literal>i</literal> extensions, and the call will terminate!</para> </description> <see-also> <ref type="application">GotoIf</ref> <ref type="application">GotoIfTime</ref> <ref type="application">Gosub</ref> <ref type="application">Macro</ref> </see-also> </application> <application name="GotoIf" language="en_US"> <synopsis> Conditional goto. </synopsis> <syntax argsep="?"> <parameter name="condition" required="true" /> <parameter name="destination" required="true" argsep=":"> <argument name="labeliftrue"> <para>Continue at <replaceable>labeliftrue</replaceable> if the condition is true. Takes the form similar to Goto() of [[context,]extension,]priority.</para> </argument> <argument name="labeliffalse"> <para>Continue at <replaceable>labeliffalse</replaceable> if the condition is false. Takes the form similar to Goto() of [[context,]extension,]priority.</para> </argument> </parameter> </syntax> <description> <para>This application will set the current context, extension, and priority in the channel structure based on the evaluation of the given condition. After this application completes, the pbx engine will continue dialplan execution at the specified location in the dialplan. The labels are specified with the same syntax as used within the Goto application. If the label chosen by the condition is omitted, no jump is performed, and the execution passes to the next instruction. If the target location is bogus, and does not exist, the execution engine will try to find and execute the code in the <literal>i</literal> (invalid) extension in the current context. If that does not exist, it will try to execute the <literal>h</literal> extension. If neither the <literal>h</literal> nor <literal>i</literal> extensions have been defined, the channel is hung up, and the execution of instructions on the channel is terminated. Remember that this command can set the current context, and if the context specified does not exist, then it will not be able to find any 'h' or 'i' extensions there, and the channel and call will both be terminated!.</para> </description> <see-also> <ref type="application">Goto</ref> <ref type="application">GotoIfTime</ref> <ref type="application">GosubIf</ref> <ref type="application">MacroIf</ref> </see-also> </application> <application name="GotoIfTime" language="en_US"> <synopsis> Conditional Goto based on the current time. </synopsis> <syntax argsep="?"> <parameter name="condition" required="true"> <argument name="times" required="true" /> <argument name="weekdays" required="true" /> <argument name="mdays" required="true" /> <argument name="months" required="true" /> <argument name="timezone" required="false" /> </parameter> <parameter name="destination" required="true" argsep=":"> <argument name="labeliftrue"> <para>Continue at <replaceable>labeliftrue</replaceable> if the condition is true. Takes the form similar to Goto() of [[context,]extension,]priority.</para> </argument> <argument name="labeliffalse"> <para>Continue at <replaceable>labeliffalse</replaceable> if the condition is false. Takes the form similar to Goto() of [[context,]extension,]priority.</para> </argument> </parameter> </syntax> <description> <para>This application will set the context, extension, and priority in the channel structure based on the evaluation of the given time specification. After this application completes, the pbx engine will continue dialplan execution at the specified location in the dialplan. If the current time is within the given time specification, the channel will continue at <replaceable>labeliftrue</replaceable>. Otherwise the channel will continue at <replaceable>labeliffalse</replaceable>. If the label chosen by the condition is omitted, no jump is performed, and execution passes to the next instruction. If the target jump location is bogus, the same actions would be taken as for <literal>Goto</literal>. Further information on the time specification can be found in examples illustrating how to do time-based context includes in the dialplan.</para> </description> <see-also> <ref type="application">GotoIf</ref> <ref type="application">Goto</ref> <ref type="function">IFTIME</ref> <ref type="function">TESTTIME</ref> </see-also> </application> <application name="ImportVar" language="en_US"> <synopsis> Import a variable from a channel into a new variable. </synopsis> <syntax argsep="="> <parameter name="newvar" required="true" /> <parameter name="vardata" required="true"> <argument name="channelname" required="true" /> <argument name="variable" required="true" /> </parameter> </syntax> <description> <para>This application imports a <replaceable>variable</replaceable> from the specified <replaceable>channel</replaceable> (as opposed to the current one) and stores it as a variable (<replaceable>newvar</replaceable>) in the current channel (the channel that is calling this application). Variables created by this application have the same inheritance properties as those created with the <literal>Set</literal> application.</para> </description> <see-also> <ref type="application">Set</ref> </see-also> </application> <application name="Hangup" language="en_US"> <synopsis> Hang up the calling channel. </synopsis> <syntax> <parameter name="causecode"> <para>If a <replaceable>causecode</replaceable> is given the channel's hangup cause will be set to the given value.</para> </parameter> </syntax> <description> <para>This application will hang up the calling channel.</para> </description> <see-also> <ref type="application">Answer</ref> <ref type="application">Busy</ref> <ref type="application">Congestion</ref> </see-also> </application> <application name="Incomplete" language="en_US"> <synopsis> Returns AST_PBX_INCOMPLETE value. </synopsis> <syntax> <parameter name="n"> <para>If specified, then Incomplete will not attempt to answer the channel first.</para> <note><para>Most channel types need to be in Answer state in order to receive DTMF.</para></note> </parameter> </syntax> <description> <para>Signals the PBX routines that the previous matched extension is incomplete and that further input should be allowed before matching can be considered to be complete. Can be used within a pattern match when certain criteria warrants a longer match.</para> </description> </application> <application name="NoOp" language="en_US"> <synopsis> Do Nothing (No Operation). </synopsis> <syntax> <parameter name="text"> <para>Any text provided can be viewed at the Asterisk CLI.</para> </parameter> </syntax> <description> <para>This application does nothing. However, it is useful for debugging purposes.</para> <para>This method can be used to see the evaluations of variables or functions without having any effect.</para> </description> <see-also> <ref type="application">Verbose</ref> <ref type="application">Log</ref> </see-also> </application> <application name="Proceeding" language="en_US"> <synopsis> Indicate proceeding. </synopsis> <syntax /> <description> <para>This application will request that a proceeding message be provided to the calling channel.</para> </description> </application> <application name="Progress" language="en_US"> <synopsis> Indicate progress. </synopsis> <syntax /> <description> <para>This application will request that in-band progress information be provided to the calling channel.</para> </description> <see-also> <ref type="application">Busy</ref> <ref type="application">Congestion</ref> <ref type="application">Ringing</ref> <ref type="application">Playtones</ref> </see-also> </application> <application name="RaiseException" language="en_US"> <synopsis> Handle an exceptional condition. </synopsis> <syntax> <parameter name="reason" required="true" /> </syntax> <description> <para>This application will jump to the <literal>e</literal> extension in the current context, setting the dialplan function EXCEPTION(). If the <literal>e</literal> extension does not exist, the call will hangup.</para> </description> <see-also> <ref type="function">Exception</ref> </see-also> </application> <application name="ResetCDR" language="en_US"> <synopsis> Resets the Call Data Record. </synopsis> <syntax> <parameter name="options"> <optionlist> <option name="w"> <para>Store the current CDR record before resetting it.</para> </option> <option name="a"> <para>Store any stacked records.</para> </option> <option name="v"> <para>Save CDR variables.</para> </option> <option name="e"> <para>Enable CDR only (negate effects of NoCDR).</para> </option> </optionlist> </parameter> </syntax> <description> <para>This application causes the Call Data Record to be reset.</para> </description> <see-also> <ref type="application">ForkCDR</ref> <ref type="application">NoCDR</ref> </see-also> </application> <application name="Ringing" language="en_US"> <synopsis> Indicate ringing tone. </synopsis> <syntax /> <description> <para>This application will request that the channel indicate a ringing tone to the user.</para> </description> <see-also> <ref type="application">Busy</ref> <ref type="application">Congestion</ref> <ref type="application">Progress</ref> <ref type="application">Playtones</ref> </see-also> </application> <application name="SayAlpha" language="en_US"> <synopsis> Say Alpha. </synopsis> <syntax> <parameter name="string" required="true" /> </syntax> <description> <para>This application will play the sounds that correspond to the letters of the given <replaceable>string</replaceable>.</para> </description> <see-also> <ref type="application">SayDigits</ref> <ref type="application">SayNumber</ref> <ref type="application">SayPhonetic</ref> <ref type="function">CHANNEL</ref> </see-also> </application> <application name="SayDigits" language="en_US"> <synopsis> Say Digits. </synopsis> <syntax> <parameter name="digits" required="true" /> </syntax> <description> <para>This application will play the sounds that correspond to the digits of the given number. This will use the language that is currently set for the channel.</para> </description> <see-also> <ref type="application">SayAlpha</ref> <ref type="application">SayNumber</ref> <ref type="application">SayPhonetic</ref> <ref type="function">CHANNEL</ref> </see-also> </application> <application name="SayNumber" language="en_US"> <synopsis> Say Number. </synopsis> <syntax> <parameter name="digits" required="true" /> <parameter name="gender" /> </syntax> <description> <para>This application will play the sounds that correspond to the given <replaceable>digits</replaceable>. Optionally, a <replaceable>gender</replaceable> may be specified. This will use the language that is currently set for the channel. See the CHANNEL() function for more information on setting the language for the channel.</para> </description> <see-also> <ref type="application">SayAlpha</ref> <ref type="application">SayDigits</ref> <ref type="application">SayPhonetic</ref> <ref type="function">CHANNEL</ref> </see-also> </application> <application name="SayPhonetic" language="en_US"> <synopsis> Say Phonetic. </synopsis> <syntax> <parameter name="string" required="true" /> </syntax> <description> <para>This application will play the sounds from the phonetic alphabet that correspond to the letters in the given <replaceable>string</replaceable>.</para> </description> <see-also> <ref type="application">SayAlpha</ref> <ref type="application">SayDigits</ref> <ref type="application">SayNumber</ref> </see-also> </application> <application name="Set" language="en_US"> <synopsis> Set channel variable or function value. </synopsis> <syntax argsep="="> <parameter name="name" required="true" /> <parameter name="value" required="true" /> </syntax> <description> <para>This function can be used to set the value of channel variables or dialplan functions. When setting variables, if the variable name is prefixed with <literal>_</literal>, the variable will be inherited into channels created from the current channel. If the variable name is prefixed with <literal>__</literal>, the variable will be inherited into channels created from the current channel and all children channels.</para> <note><para>If (and only if), in <filename>/etc/asterisk/asterisk.conf</filename>, you have a <literal>[compat]</literal> category, and you have <literal>app_set = 1.4</literal> under that, then the behavior of this app changes, and strips surrounding quotes from the right hand side as it did previously in 1.4. The advantages of not stripping out quoting, and not caring about the separator characters (comma and vertical bar) were sufficient to make these changes in 1.6. Confusion about how many backslashes would be needed to properly protect separators and quotes in various database access strings has been greatly reduced by these changes.</para></note> </description> <see-also> <ref type="application">MSet</ref> <ref type="function">GLOBAL</ref> <ref type="function">SET</ref> <ref type="function">ENV</ref> </see-also> </application> <application name="MSet" language="en_US"> <synopsis> Set channel variable(s) or function value(s). </synopsis> <syntax> <parameter name="set1" required="true" argsep="="> <argument name="name1" required="true" /> <argument name="value1" required="true" /> </parameter> <parameter name="set2" multiple="true" argsep="="> <argument name="name2" required="true" /> <argument name="value2" required="true" /> </parameter> </syntax> <description> <para>This function can be used to set the value of channel variables or dialplan functions. When setting variables, if the variable name is prefixed with <literal>_</literal>, the variable will be inherited into channels created from the current channel If the variable name is prefixed with <literal>__</literal>, the variable will be inherited into channels created from the current channel and all children channels. MSet behaves in a similar fashion to the way Set worked in 1.2/1.4 and is thus prone to doing things that you may not expect. For example, it strips surrounding double-quotes from the right-hand side (value). If you need to put a separator character (comma or vert-bar), you will need to escape them by inserting a backslash before them. Avoid its use if possible.</para> </description> <see-also> <ref type="application">Set</ref> </see-also> </application> <application name="SetAMAFlags" language="en_US"> <synopsis> Set the AMA Flags. </synopsis> <syntax> <parameter name="flag" /> </syntax> <description> <para>This application will set the channel's AMA Flags for billing purposes.</para> </description> <see-also> <ref type="function">CDR</ref> </see-also> </application> <application name="Wait" language="en_US"> <synopsis> Waits for some time. </synopsis> <syntax> <parameter name="seconds" required="true"> <para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the application to wait for 1.5 seconds.</para> </parameter> </syntax> <description> <para>This application waits for a specified number of <replaceable>seconds</replaceable>.</para> </description> </application> <application name="WaitExten" language="en_US"> <synopsis> Waits for an extension to be entered. </synopsis> <syntax> <parameter name="seconds"> <para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the application to wait for 1.5 seconds.</para> </parameter> <parameter name="options"> <optionlist> <option name="m"> <para>Provide music on hold to the caller while waiting for an extension.</para> <argument name="x"> <para>Specify the class for music on hold. <emphasis>CHANNEL(musicclass) will be used instead if set</emphasis></para> </argument> </option> </optionlist> </parameter> </syntax> <description> <para>This application waits for the user to enter a new extension for a specified number of <replaceable>seconds</replaceable>.</para> <xi:include xpointer="xpointer(/docs/application[@name='Macro']/description/warning[2])" /> </description> <see-also> <ref type="application">Background</ref> <ref type="function">TIMEOUT</ref> </see-also> </application> <function name="EXCEPTION" language="en_US"> <synopsis> Retrieve the details of the current dialplan exception. </synopsis> <syntax> <parameter name="field" required="true"> <para>The following fields are available for retrieval:</para> <enumlist> <enum name="reason"> <para>INVALID, ERROR, RESPONSETIMEOUT, ABSOLUTETIMEOUT, or custom value set by the RaiseException() application</para> </enum> <enum name="context"> <para>The context executing when the exception occurred.</para> </enum> <enum name="exten"> <para>The extension executing when the exception occurred.</para> </enum> <enum name="priority"> <para>The numeric priority executing when the exception occurred.</para> </enum> </enumlist> </parameter> </syntax> <description> <para>Retrieve the details (specified <replaceable>field</replaceable>) of the current dialplan exception.</para> </description> <see-also> <ref type="application">RaiseException</ref> </see-also> </function> <function name="TESTTIME" language="en_US"> <synopsis> Sets a time to be used with the channel to test logical conditions. </synopsis> <syntax> <parameter name="date" required="true" argsep=" "> <para>Date in ISO 8601 format</para> </parameter> <parameter name="time" required="true" argsep=" "> <para>Time in HH:MM:SS format (24-hour time)</para> </parameter> <parameter name="zone" required="false"> <para>Timezone name</para> </parameter> </syntax> <description> <para>To test dialplan timing conditions at times other than the current time, use this function to set an alternate date and time. For example, you may wish to evaluate whether a location will correctly identify to callers that the area is closed on Christmas Day, when Christmas would otherwise fall on a day when the office is normally open.</para> </description> <see-also> <ref type="application">GotoIfTime</ref> </see-also> </function> <manager name="ShowDialPlan" language="en_US"> <synopsis> Show dialplan contexts and extensions </synopsis> <syntax> <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" /> <parameter name="Extension"> <para>Show a specific extension.</para> </parameter> <parameter name="Context"> <para>Show a specific context.</para> </parameter> </syntax> <description> <para>Show dialplan contexts and extensions. Be aware that showing the full dialplan may take a lot of capacity.</para> </description> </manager> ***/ #ifdef LOW_MEMORY #define EXT_DATA_SIZE 256 #else #define EXT_DATA_SIZE 8192 #endif #define SWITCH_DATA_LENGTH 256 #define VAR_BUF_SIZE 4096 #define VAR_NORMAL 1 #define VAR_SOFTTRAN 2 #define VAR_HARDTRAN 3 #define BACKGROUND_SKIP (1 << 0) #define BACKGROUND_NOANSWER (1 << 1) #define BACKGROUND_MATCHEXTEN (1 << 2) #define BACKGROUND_PLAYBACK (1 << 3) AST_APP_OPTIONS(background_opts, { AST_APP_OPTION('s', BACKGROUND_SKIP), AST_APP_OPTION('n', BACKGROUND_NOANSWER), AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN), AST_APP_OPTION('p', BACKGROUND_PLAYBACK), }); #define WAITEXTEN_MOH (1 << 0) #define WAITEXTEN_DIALTONE (1 << 1) AST_APP_OPTIONS(waitexten_opts, { AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 0), AST_APP_OPTION_ARG('d', WAITEXTEN_DIALTONE, 0), }); struct ast_context; struct ast_app; static struct ast_taskprocessor *device_state_tps; AST_THREADSTORAGE(switch_data); AST_THREADSTORAGE(extensionstate_buf); /*! \brief ast_exten: An extension The dialplan is saved as a linked list with each context having it's own linked list of extensions - one item per priority. */ struct ast_exten { char *exten; /*!< Extension name */ int matchcid; /*!< Match caller id ? */ const char *cidmatch; /*!< Caller id to match for this extension */ int priority; /*!< Priority */ const char *label; /*!< Label */ struct ast_context *parent; /*!< The context this extension belongs to */ const char *app; /*!< Application to execute */ struct ast_app *cached_app; /*!< Cached location of application */ void *data; /*!< Data to use (arguments) */ void (*datad)(void *); /*!< Data destructor */ struct ast_exten *peer; /*!< Next higher priority with our extension */ struct ast_hashtab *peer_table; /*!< Priorities list in hashtab form -- only on the head of the peer list */ struct ast_hashtab *peer_label_table; /*!< labeled priorities in the peers -- only on the head of the peer list */ const char *registrar; /*!< Registrar */ struct ast_exten *next; /*!< Extension with a greater ID */ char stuff[0]; }; /*! \brief ast_include: include= support in extensions.conf */ struct ast_include { const char *name; const char *rname; /*!< Context to include */ const char *registrar; /*!< Registrar */ int hastime; /*!< If time construct exists */ struct ast_timing timing; /*!< time construct */ struct ast_include *next; /*!< Link them together */ char stuff[0]; }; /*! \brief ast_sw: Switch statement in extensions.conf */ struct ast_sw { char *name; const char *registrar; /*!< Registrar */ char *data; /*!< Data load */ int eval; AST_LIST_ENTRY(ast_sw) list; char stuff[0]; }; /*! \brief ast_ignorepat: Ignore patterns in dial plan */ struct ast_ignorepat { const char *registrar; struct ast_ignorepat *next; const char pattern[0]; }; /*! \brief match_char: forms a syntax tree for quick matching of extension patterns */ struct match_char { int is_pattern; /* the pattern started with '_' */ int deleted; /* if this is set, then... don't return it */ int specificity; /* simply the strlen of x, or 10 for X, 9 for Z, and 8 for N; and '.' and '!' will add 11 ? */ struct match_char *alt_char; struct match_char *next_char; struct ast_exten *exten; /* attached to last char of a pattern for exten */ char x[1]; /* the pattern itself-- matches a single char */ }; struct scoreboard /* make sure all fields are 0 before calling new_find_extension */ { int total_specificity; int total_length; char last_char; /* set to ! or . if they are the end of the pattern */ int canmatch; /* if the string to match was just too short */ struct match_char *node; struct ast_exten *canmatch_exten; struct ast_exten *exten; }; /*! \brief ast_context: An extension context */ struct ast_context { ast_rwlock_t lock; /*!< A lock to prevent multiple threads from clobbering the context */ struct ast_exten *root; /*!< The root of the list of extensions */ struct ast_hashtab *root_table; /*!< For exact matches on the extensions in the pattern tree, and for traversals of the pattern_tree */ struct match_char *pattern_tree; /*!< A tree to speed up extension pattern matching */ struct ast_context *next; /*!< Link them together */ struct ast_include *includes; /*!< Include other contexts */ struct ast_ignorepat *ignorepats; /*!< Patterns for which to continue playing dialtone */ char *registrar; /*!< Registrar -- make sure you malloc this, as the registrar may have to survive module unloads */ int refcount; /*!< each module that would have created this context should inc/dec this as appropriate */ AST_LIST_HEAD_NOLOCK(, ast_sw) alts; /*!< Alternative switches */ ast_mutex_t macrolock; /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */ char name[0]; /*!< Name of the context */ }; /*! \brief ast_app: A registered application */ struct ast_app { int (*execute)(struct ast_channel *chan, const char *data); AST_DECLARE_STRING_FIELDS( AST_STRING_FIELD(synopsis); /*!< Synopsis text for 'show applications' */ AST_STRING_FIELD(description); /*!< Description (help text) for 'show application &lt;name&gt;' */ AST_STRING_FIELD(syntax); /*!< Syntax text for 'core show applications' */ AST_STRING_FIELD(arguments); /*!< Arguments description */ AST_STRING_FIELD(seealso); /*!< See also */ ); #ifdef AST_XML_DOCS enum ast_doc_src docsrc; /*!< Where the documentation come from. */ #endif AST_RWLIST_ENTRY(ast_app) list; /*!< Next app in list */ struct ast_module *module; /*!< Module this app belongs to */ char name[0]; /*!< Name of the application */ }; /*! \brief ast_state_cb: An extension state notify register item */ struct ast_state_cb { /*! Watcher ID returned when registered. */ int id; /*! Arbitrary data passed for callbacks. */ void *data; /*! Callback when state changes. */ ast_state_cb_type change_cb; /*! Callback when destroyed so any resources given by the registerer can be freed. */ ast_state_cb_destroy_type destroy_cb; /*! \note Only used by ast_merge_contexts_and_delete */ AST_LIST_ENTRY(ast_state_cb) entry; }; /*! * \brief Structure for dial plan hints * * \note Hints are pointers from an extension in the dialplan to * one or more devices (tech/name) * * See \ref AstExtState */ struct ast_hint { /*! * \brief Hint extension * * \note * Will never be NULL while the hint is in the hints container. */ struct ast_exten *exten; struct ao2_container *callbacks; /*!< Callback container for this extension */ int laststate; /*!< Last known state */ char context_name[AST_MAX_CONTEXT];/*!< Context of destroyed hint extension. */ char exten_name[AST_MAX_EXTENSION];/*!< Extension of destroyed hint extension. */ }; /* --- Hash tables of various objects --------*/ #ifdef LOW_MEMORY #define HASH_EXTENHINT_SIZE 17 #else #define HASH_EXTENHINT_SIZE 563 #endif static const struct cfextension_states { int extension_state; const char * const text; } extension_states[] = { { AST_EXTENSION_NOT_INUSE, "Idle" }, { AST_EXTENSION_INUSE, "InUse" }, { AST_EXTENSION_BUSY, "Busy" }, { AST_EXTENSION_UNAVAILABLE, "Unavailable" }, { AST_EXTENSION_RINGING, "Ringing" }, { AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" }, { AST_EXTENSION_ONHOLD, "Hold" }, { AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD, "InUse&Hold" } }; struct statechange { AST_LIST_ENTRY(statechange) entry; char dev[0]; }; struct pbx_exception { AST_DECLARE_STRING_FIELDS( AST_STRING_FIELD(context); /*!< Context associated with this exception */ AST_STRING_FIELD(exten); /*!< Exten associated with this exception */ AST_STRING_FIELD(reason); /*!< The exception reason */ ); int priority; /*!< Priority associated with this exception */ }; static int pbx_builtin_answer(struct ast_channel *, const char *); static int pbx_builtin_goto(struct ast_channel *, const char *); static int pbx_builtin_hangup(struct ast_channel *, const char *); static int pbx_builtin_background(struct ast_channel *, const char *); static int pbx_builtin_wait(struct ast_channel *, const char *); static int pbx_builtin_waitexten(struct ast_channel *, const char *); static int pbx_builtin_incomplete(struct ast_channel *, const char *); static int pbx_builtin_resetcdr(struct ast_channel *, const char *); static int pbx_builtin_setamaflags(struct ast_channel *, const char *); static int pbx_builtin_ringing(struct ast_channel *, const char *); static int pbx_builtin_proceeding(struct ast_channel *, const char *); static int pbx_builtin_progress(struct ast_channel *, const char *); static int pbx_builtin_congestion(struct ast_channel *, const char *); static int pbx_builtin_busy(struct ast_channel *, const char *); static int pbx_builtin_noop(struct ast_channel *, const char *); static int pbx_builtin_gotoif(struct ast_channel *, const char *); static int pbx_builtin_gotoiftime(struct ast_channel *, const char *); static int pbx_builtin_execiftime(struct ast_channel *, const char *); static int pbx_builtin_saynumber(struct ast_channel *, const char *); static int pbx_builtin_saydigits(struct ast_channel *, const char *); static int pbx_builtin_saycharacters(struct ast_channel *, const char *); static int pbx_builtin_sayphonetic(struct ast_channel *, const char *); static int matchcid(const char *cidpattern, const char *callerid); #ifdef NEED_DEBUG static void log_match_char_tree(struct match_char *node, char *prefix); /* for use anywhere */ #endif static int pbx_builtin_importvar(struct ast_channel *, const char *); static void set_ext_pri(struct ast_channel *c, const char *exten, int pri); static void new_find_extension(const char *str, struct scoreboard *score, struct match_char *tree, int length, int spec, const char *callerid, const char *label, enum ext_match_t action); static struct match_char *already_in_tree(struct match_char *current, char *pat, int is_pattern); static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly); static void create_match_char_tree(struct ast_context *con); static struct ast_exten *get_canmatch_exten(struct match_char *node); static void destroy_pattern_tree(struct match_char *pattern_tree); static int hashtab_compare_extens(const void *ha_a, const void *ah_b); static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b); static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b); static unsigned int hashtab_hash_extens(const void *obj); static unsigned int hashtab_hash_priority(const void *obj); static unsigned int hashtab_hash_labels(const void *obj); static void __ast_internal_context_destroy( struct ast_context *con); static int ast_add_extension_nolock(const char *context, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void (*datad)(void *), const char *registrar); static int ast_add_extension2_lockopt(struct ast_context *con, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void (*datad)(void *), const char *registrar, int lock_context); static struct ast_context *find_context_locked(const char *context); static struct ast_context *find_context(const char *context); /*! * \internal * \brief Character array comparison function for qsort. * * \param a Left side object. * \param b Right side object. * * \retval <0 if a < b * \retval =0 if a = b * \retval >0 if a > b */ static int compare_char(const void *a, const void *b) { const unsigned char *ac = a; const unsigned char *bc = b; return *ac - *bc; } /* labels, contexts are case sensitive priority numbers are ints */ int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b) { const struct ast_context *ac = ah_a; const struct ast_context *bc = ah_b; if (!ac || !bc) /* safety valve, but it might prevent a crash you'd rather have happen */ return 1; /* assume context names are registered in a string table! */ return strcmp(ac->name, bc->name); } static int hashtab_compare_extens(const void *ah_a, const void *ah_b) { const struct ast_exten *ac = ah_a; const struct ast_exten *bc = ah_b; int x = strcmp(ac->exten, bc->exten); if (x) { /* if exten names are diff, then return */ return x; } /* but if they are the same, do the cidmatch values match? */ if (ac->matchcid && bc->matchcid) { return strcmp(ac->cidmatch,bc->cidmatch); } else if (!ac->matchcid && !bc->matchcid) { return 0; /* if there's no matchcid on either side, then this is a match */ } else { return 1; /* if there's matchcid on one but not the other, they are different */ } } static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b) { const struct ast_exten *ac = ah_a; const struct ast_exten *bc = ah_b; return ac->priority != bc->priority; } static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b) { const struct ast_exten *ac = ah_a; const struct ast_exten *bc = ah_b; return strcmp(S_OR(ac->label, ""), S_OR(bc->label, "")); } unsigned int ast_hashtab_hash_contexts(const void *obj) { const struct ast_context *ac = obj; return ast_hashtab_hash_string(ac->name); } static unsigned int hashtab_hash_extens(const void *obj) { const struct ast_exten *ac = obj; unsigned int x = ast_hashtab_hash_string(ac->exten); unsigned int y = 0; if (ac->matchcid) y = ast_hashtab_hash_string(ac->cidmatch); return x+y; } static unsigned int hashtab_hash_priority(const void *obj) { const struct ast_exten *ac = obj; return ast_hashtab_hash_int(ac->priority); } static unsigned int hashtab_hash_labels(const void *obj) { const struct ast_exten *ac = obj; return ast_hashtab_hash_string(S_OR(ac->label, "")); } AST_RWLOCK_DEFINE_STATIC(globalslock); static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE; static int autofallthrough = 1; static int extenpatternmatchnew = 0; static char *overrideswitch = NULL; /*! \brief Subscription for device state change events */ static struct ast_event_sub *device_state_sub; AST_MUTEX_DEFINE_STATIC(maxcalllock); static int countcalls; static int totalcalls; static AST_RWLIST_HEAD_STATIC(acf_root, ast_custom_function); /*! \brief Declaration of builtin applications */ static struct pbx_builtin { char name[AST_MAX_APP]; int (*execute)(struct ast_channel *chan, const char *data); } builtins[] = { /* These applications are built into the PBX core and do not need separate modules */ { "Answer", pbx_builtin_answer }, { "BackGround", pbx_builtin_background }, { "Busy", pbx_builtin_busy }, { "Congestion", pbx_builtin_congestion }, { "ExecIfTime", pbx_builtin_execiftime }, { "Goto", pbx_builtin_goto }, { "GotoIf", pbx_builtin_gotoif }, { "GotoIfTime", pbx_builtin_gotoiftime }, { "ImportVar", pbx_builtin_importvar }, { "Hangup", pbx_builtin_hangup }, { "Incomplete", pbx_builtin_incomplete }, { "NoOp", pbx_builtin_noop }, { "Proceeding", pbx_builtin_proceeding }, { "Progress", pbx_builtin_progress }, { "RaiseException", pbx_builtin_raise_exception }, { "ResetCDR", pbx_builtin_resetcdr }, { "Ringing", pbx_builtin_ringing }, { "SayAlpha", pbx_builtin_saycharacters }, { "SayDigits", pbx_builtin_saydigits }, { "SayNumber", pbx_builtin_saynumber }, { "SayPhonetic", pbx_builtin_sayphonetic }, { "Set", pbx_builtin_setvar }, { "MSet", pbx_builtin_setvar_multiple }, { "SetAMAFlags", pbx_builtin_setamaflags }, { "Wait", pbx_builtin_wait }, { "WaitExten", pbx_builtin_waitexten } }; static struct ast_context *contexts; static struct ast_hashtab *contexts_table = NULL; /*! * \brief Lock for the ast_context list * \note * This lock MUST be recursive, or a deadlock on reload may result. See * https://issues.asterisk.org/view.php?id=17643 */ AST_MUTEX_DEFINE_STATIC(conlock); /*! * \brief Lock to hold off restructuring of hints by ast_merge_contexts_and_delete. */ AST_MUTEX_DEFINE_STATIC(context_merge_lock); static AST_RWLIST_HEAD_STATIC(apps, ast_app); static AST_RWLIST_HEAD_STATIC(switches, ast_switch); static int stateid = 1; /*! * \note When holding this container's lock, do _not_ do * anything that will cause conlock to be taken, unless you * _already_ hold it. The ast_merge_contexts_and_delete function * will take the locks in conlock/hints order, so any other * paths that require both locks must also take them in that * order. */ static struct ao2_container *hints; static struct ao2_container *statecbs; #ifdef CONTEXT_DEBUG /* these routines are provided for doing run-time checks on the extension structures, in case you are having problems, this routine might help you localize where the problem is occurring. It's kinda like a debug memory allocator's arena checker... It'll eat up your cpu cycles! but you'll see, if you call it in the right places, right where your problems began... */ /* you can break on the check_contexts_trouble() routine in your debugger to stop at the moment there's a problem */ void check_contexts_trouble(void); void check_contexts_trouble(void) { int x = 1; x = 2; } int check_contexts(char *, int); int check_contexts(char *file, int line ) { struct ast_hashtab_iter *t1; struct ast_context *c1, *c2; int found = 0; struct ast_exten *e1, *e2, *e3; struct ast_exten ex; /* try to find inconsistencies */ /* is every context in the context table in the context list and vice-versa ? */ if (!contexts_table) { ast_log(LOG_NOTICE,"Called from: %s:%d: No contexts_table!\n", file, line); usleep(500000); } t1 = ast_hashtab_start_traversal(contexts_table); while( (c1 = ast_hashtab_next(t1))) { for(c2=contexts;c2;c2=c2->next) { if (!strcmp(c1->name, c2->name)) { found = 1; break; } } if (!found) { ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the linked list\n", file, line, c1->name); check_contexts_trouble(); } } ast_hashtab_end_traversal(t1); for(c2=contexts;c2;c2=c2->next) { c1 = find_context_locked(c2->name); if (!c1) { ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the hashtab\n", file, line, c2->name); check_contexts_trouble(); } else ast_unlock_contexts(); } /* loop thru all contexts, and verify the exten structure compares to the hashtab structure */ for(c2=contexts;c2;c2=c2->next) { c1 = find_context_locked(c2->name); if (c1) { ast_unlock_contexts(); /* is every entry in the root list also in the root_table? */ for(e1 = c1->root; e1; e1=e1->next) { char dummy_name[1024]; ex.exten = dummy_name; ex.matchcid = e1->matchcid; ex.cidmatch = e1->cidmatch; ast_copy_string(dummy_name, e1->exten, sizeof(dummy_name)); e2 = ast_hashtab_lookup(c1->root_table, &ex); if (!e2) { if (e1->matchcid) { ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s (CID match: %s) but it is not in its root_table\n", file, line, c2->name, dummy_name, e1->cidmatch ); } else { ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, dummy_name ); } check_contexts_trouble(); } } /* is every entry in the root_table also in the root list? */ if (!c2->root_table) { if (c2->root) { ast_log(LOG_NOTICE,"Called from: %s:%d: No c2->root_table for context %s!\n", file, line, c2->name); usleep(500000); } } else { t1 = ast_hashtab_start_traversal(c2->root_table); while( (e2 = ast_hashtab_next(t1)) ) { for(e1=c2->root;e1;e1=e1->next) { if (!strcmp(e1->exten, e2->exten)) { found = 1; break; } } if (!found) { ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, e2->exten); check_contexts_trouble(); } } ast_hashtab_end_traversal(t1); } } /* is every priority reflected in the peer_table at the head of the list? */ /* is every entry in the root list also in the root_table? */ /* are the per-extension peer_tables in the right place? */ for(e1 = c2->root; e1; e1 = e1->next) { for(e2=e1;e2;e2=e2->peer) { ex.priority = e2->priority; if (e2 != e1 && e2->peer_table) { ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority ); check_contexts_trouble(); } if (e2 != e1 && e2->peer_label_table) { ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_label_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority ); check_contexts_trouble(); } if (e2 == e1 && !e2->peer_table){ ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_table!\n", file, line, c2->name, e1->exten, e2->priority ); check_contexts_trouble(); } if (e2 == e1 && !e2->peer_label_table) { ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_label_table!\n", file, line, c2->name, e1->exten, e2->priority ); check_contexts_trouble(); } e3 = ast_hashtab_lookup(e1->peer_table, &ex); if (!e3) { ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer_table\n", file, line, c2->name, e1->exten, e2->priority ); check_contexts_trouble(); } } if (!e1->peer_table){ ast_log(LOG_NOTICE,"Called from: %s:%d: No e1->peer_table!\n", file, line); usleep(500000); } /* is every entry in the peer_table also in the peer list? */ t1 = ast_hashtab_start_traversal(e1->peer_table); while( (e2 = ast_hashtab_next(t1)) ) { for(e3=e1;e3;e3=e3->peer) { if (e3->priority == e2->priority) { found = 1; break; } } if (!found) { ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer list\n", file, line, c2->name, e1->exten, e2->priority ); check_contexts_trouble(); } } ast_hashtab_end_traversal(t1); } } return 0; } #endif /* \note This function is special. It saves the stack so that no matter how many times it is called, it returns to the same place */ int pbx_exec(struct ast_channel *c, /*!< Channel */ struct ast_app *app, /*!< Application */ const char *data) /*!< Data for execution */ { int res; struct ast_module_user *u = NULL; const char *saved_c_appl; const char *saved_c_data; if (c->cdr && !ast_check_hangup(c)) ast_cdr_setapp(c->cdr, app->name, data); /* save channel values */ saved_c_appl= c->appl; saved_c_data= c->data; c->appl = app->name; c->data = data; ast_cel_report_event(c, AST_CEL_APP_START, NULL, NULL, NULL); if (app->module) u = __ast_module_user_add(app->module, c); if (strcasecmp(app->name, "system") && !ast_strlen_zero(data) && strchr(data, '|') && !strchr(data, ',') && !ast_opt_dont_warn) { ast_log(LOG_WARNING, "The application delimiter is now the comma, not " "the pipe. Did you forget to convert your dialplan? (%s(%s))\n", app->name, (char *) data); } res = app->execute(c, S_OR(data, "")); if (app->module && u) __ast_module_user_remove(app->module, u); ast_cel_report_event(c, AST_CEL_APP_END, NULL, NULL, NULL); /* restore channel values */ c->appl = saved_c_appl; c->data = saved_c_data; return res; } /*! Go no deeper than this through includes (not counting loops) */ #define AST_PBX_MAX_STACK 128 /*! \brief Find application handle in linked list */ struct ast_app *pbx_findapp(const char *app) { struct ast_app *tmp; AST_RWLIST_RDLOCK(&apps); AST_RWLIST_TRAVERSE(&apps, tmp, list) { if (!strcasecmp(tmp->name, app)) break; } AST_RWLIST_UNLOCK(&apps); return tmp; } static struct ast_switch *pbx_findswitch(const char *sw) { struct ast_switch *asw; AST_RWLIST_RDLOCK(&switches); AST_RWLIST_TRAVERSE(&switches, asw, list) { if (!strcasecmp(asw->name, sw)) break; } AST_RWLIST_UNLOCK(&switches); return asw; } static inline int include_valid(struct ast_include *i) { if (!i->hastime) return 1; return ast_check_timing(&(i->timing)); } static void pbx_destroy(struct ast_pbx *p) { ast_free(p); } /* form a tree that fully describes all the patterns in a context's extensions * in this tree, a "node" represents an individual character or character set * meant to match the corresponding character in a dial string. The tree * consists of a series of match_char structs linked in a chain * via the alt_char pointers. More than one pattern can share the same parts of the * tree as other extensions with the same pattern to that point. * My first attempt to duplicate the finding of the 'best' pattern was flawed in that * I misunderstood the general algorithm. I thought that the 'best' pattern * was the one with lowest total score. This was not true. Thus, if you have * patterns "1XXXXX" and "X11111", you would be tempted to say that "X11111" is * the "best" match because it has fewer X's, and is therefore more specific, * but this is not how the old algorithm works. It sorts matching patterns * in a similar collating sequence as sorting alphabetic strings, from left to * right. Thus, "1XXXXX" comes before "X11111", and would be the "better" match, * because "1" is more specific than "X". * So, to accomodate this philosophy, I sort the tree branches along the alt_char * line so they are lowest to highest in specificity numbers. This way, as soon * as we encounter our first complete match, we automatically have the "best" * match and can stop the traversal immediately. Same for CANMATCH/MATCHMORE. * If anyone would like to resurrect the "wrong" pattern trie searching algorithm, * they are welcome to revert pbx to before 1 Apr 2008. * As an example, consider these 4 extensions: * (a) NXXNXXXXXX * (b) 307754XXXX * (c) fax * (d) NXXXXXXXXX * * In the above, between (a) and (d), (a) is a more specific pattern than (d), and would win over * most numbers. For all numbers beginning with 307754, (b) should always win. * * These pattern should form a (sorted) tree that looks like this: * { "3" } --next--> { "0" } --next--> { "7" } --next--> { "7" } --next--> { "5" } ... blah ... --> { "X" exten_match: (b) } * | * |alt * | * { "f" } --next--> { "a" } --next--> { "x" exten_match: (c) } * { "N" } --next--> { "X" } --next--> { "X" } --next--> { "N" } --next--> { "X" } ... blah ... --> { "X" exten_match: (a) } * | | * | |alt * |alt | * | { "X" } --next--> { "X" } ... blah ... --> { "X" exten_match: (d) } * | * NULL * * In the above, I could easily turn "N" into "23456789", but I think that a quick "if( *z >= '2' && *z <= '9' )" might take * fewer CPU cycles than a call to strchr("23456789",*z), where *z is the char to match... * * traversal is pretty simple: one routine merely traverses the alt list, and for each matching char in the pattern, it calls itself * on the corresponding next pointer, incrementing also the pointer of the string to be matched, and passing the total specificity and length. * We pass a pointer to a scoreboard down through, also. * The scoreboard isn't as necessary to the revised algorithm, but I kept it as a handy way to return the matched extension. * The first complete match ends the traversal, which should make this version of the pattern matcher faster * the previous. The same goes for "CANMATCH" or "MATCHMORE"; the first such match ends the traversal. In both * these cases, the reason we can stop immediately, is because the first pattern match found will be the "best" * according to the sort criteria. * Hope the limit on stack depth won't be a problem... this routine should * be pretty lean as far a stack usage goes. Any non-match terminates the recursion down a branch. * * In the above example, with the number "3077549999" as the pattern, the traversor could match extensions a, b and d. All are * of length 10; they have total specificities of 24580, 10246, and 25090, respectively, not that this matters * at all. (b) wins purely because the first character "3" is much more specific (lower specificity) than "N". I have * left the specificity totals in the code as an artifact; at some point, I will strip it out. * * Just how much time this algorithm might save over a plain linear traversal over all possible patterns is unknown, * because it's a function of how many extensions are stored in a context. With thousands of extensions, the speedup * can be very noticeable. The new matching algorithm can run several hundreds of times faster, if not a thousand or * more times faster in extreme cases. * * MatchCID patterns are also supported, and stored in the tree just as the extension pattern is. Thus, you * can have patterns in your CID field as well. * * */ static void update_scoreboard(struct scoreboard *board, int length, int spec, struct ast_exten *exten, char last, const char *callerid, int deleted, struct match_char *node) { /* if this extension is marked as deleted, then skip this -- if it never shows on the scoreboard, it will never be found, nor will halt the traversal. */ if (deleted) return; board->total_specificity = spec; board->total_length = length; board->exten = exten; board->last_char = last; board->node = node; #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"Scoreboarding (LONGER) %s, len=%d, score=%d\n", exten->exten, length, spec); #endif } #ifdef NEED_DEBUG static void log_match_char_tree(struct match_char *node, char *prefix) { char extenstr[40]; struct ast_str *my_prefix = ast_str_alloca(1024); extenstr[0] = '\0'; if (node && node->exten) snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten); if (strlen(node->x) > 1) { ast_debug(1, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N', node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"", node->exten ? node->exten->exten : "", extenstr); } else { ast_debug(1, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N', node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"", node->exten ? node->exten->exten : "", extenstr); } ast_str_set(&my_prefix, 0, "%s+ ", prefix); if (node->next_char) log_match_char_tree(node->next_char, ast_str_buffer(my_prefix)); if (node->alt_char) log_match_char_tree(node->alt_char, prefix); } #endif static void cli_match_char_tree(struct match_char *node, char *prefix, int fd) { char extenstr[40]; struct ast_str *my_prefix = ast_str_alloca(1024); extenstr[0] = '\0'; if (node->exten) { snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten); } if (strlen(node->x) > 1) { ast_cli(fd, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N', node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "", node->exten ? node->exten->exten : "", extenstr); } else { ast_cli(fd, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N', node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "", node->exten ? node->exten->exten : "", extenstr); } ast_str_set(&my_prefix, 0, "%s+ ", prefix); if (node->next_char) cli_match_char_tree(node->next_char, ast_str_buffer(my_prefix), fd); if (node->alt_char) cli_match_char_tree(node->alt_char, prefix, fd); } static struct ast_exten *get_canmatch_exten(struct match_char *node) { /* find the exten at the end of the rope */ struct match_char *node2 = node; for (node2 = node; node2; node2 = node2->next_char) { if (node2->exten) { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"CanMatch_exten returns exten %s(%p)\n", node2->exten->exten, node2->exten); #endif return node2->exten; } } #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"CanMatch_exten returns NULL, match_char=%s\n", node->x); #endif return 0; } static struct ast_exten *trie_find_next_match(struct match_char *node) { struct match_char *m3; struct match_char *m4; struct ast_exten *e3; if (node && node->x[0] == '.' && !node->x[1]) { /* dot and ! will ALWAYS be next match in a matchmore */ return node->exten; } if (node && node->x[0] == '!' && !node->x[1]) { return node->exten; } if (!node || !node->next_char) { return NULL; } m3 = node->next_char; if (m3->exten) { return m3->exten; } for (m4 = m3->alt_char; m4; m4 = m4->alt_char) { if (m4->exten) { return m4->exten; } } for (m4 = m3; m4; m4 = m4->alt_char) { e3 = trie_find_next_match(m3); if (e3) { return e3; } } return NULL; } #ifdef DEBUG_THIS static char *action2str(enum ext_match_t action) { switch (action) { case E_MATCH: return "MATCH"; case E_CANMATCH: return "CANMATCH"; case E_MATCHMORE: return "MATCHMORE"; case E_FINDLABEL: return "FINDLABEL"; case E_SPAWN: return "SPAWN"; default: return "?ACTION?"; } } #endif static void new_find_extension(const char *str, struct scoreboard *score, struct match_char *tree, int length, int spec, const char *callerid, const char *label, enum ext_match_t action) { struct match_char *p; /* note minimal stack storage requirements */ struct ast_exten pattern = { .label = label }; #ifdef DEBUG_THIS if (tree) ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree %s action=%s\n", str, tree->x, action2str(action)); else ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree NULL action=%s\n", str, action2str(action)); #endif for (p = tree; p; p = p->alt_char) { if (p->is_pattern) { if (p->x[0] == 'N') { if (p->x[1] == 0 && *str >= '2' && *str <= '9' ) { #define NEW_MATCHER_CHK_MATCH \ if (p->exten && !(*(str + 1))) { /* if a shorter pattern matches along the way, might as well report it */ \ if (action == E_MATCH || action == E_SPAWN || action == E_FINDLABEL) { /* if in CANMATCH/MATCHMORE, don't let matches get in the way */ \ update_scoreboard(score, length + 1, spec + p->specificity, p->exten, 0, callerid, p->deleted, p); \ if (!p->deleted) { \ if (action == E_FINDLABEL) { \ if (ast_hashtab_lookup(score->exten->peer_label_table, &pattern)) { \ ast_debug(4, "Found label in preferred extension\n"); \ return; \ } \ } else { \ ast_debug(4, "returning an exact match-- first found-- %s\n", p->exten->exten); \ return; /* the first match, by definition, will be the best, because of the sorted tree */ \ } \ } \ } \ } #define NEW_MATCHER_RECURSE \ if (p->next_char && (*(str + 1) || (p->next_char->x[0] == '/' && p->next_char->x[1] == 0) \ || p->next_char->x[0] == '!')) { \ if (*(str + 1) || p->next_char->x[0] == '!') { \ new_find_extension(str + 1, score, p->next_char, length + 1, spec + p->specificity, callerid, label, action); \ if (score->exten) { \ ast_debug(4 ,"returning an exact match-- %s\n", score->exten->exten); \ return; /* the first match is all we need */ \ } \ } else { \ new_find_extension("/", score, p->next_char, length + 1, spec + p->specificity, callerid, label, action); \ if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) { \ ast_debug(4,"returning a (can/more) match--- %s\n", score->exten ? score->exten->exten : \ "NULL"); \ return; /* the first match is all we need */ \ } \ } \ } else if ((p->next_char || action == E_CANMATCH) && !*(str + 1)) { \ score->canmatch = 1; \ score->canmatch_exten = get_canmatch_exten(p); \ if (action == E_CANMATCH || action == E_MATCHMORE) { \ ast_debug(4, "returning a canmatch/matchmore--- str=%s\n", str); \ return; \ } \ } NEW_MATCHER_CHK_MATCH; NEW_MATCHER_RECURSE; } } else if (p->x[0] == 'Z') { if (p->x[1] == 0 && *str >= '1' && *str <= '9' ) { NEW_MATCHER_CHK_MATCH; NEW_MATCHER_RECURSE; } } else if (p->x[0] == 'X') { if (p->x[1] == 0 && *str >= '0' && *str <= '9' ) { NEW_MATCHER_CHK_MATCH; NEW_MATCHER_RECURSE; } } else if (p->x[0] == '.' && p->x[1] == 0) { /* how many chars will the . match against? */ int i = 0; const char *str2 = str; while (*str2 && *str2 != '/') { str2++; i++; } if (p->exten && *str2 != '/') { update_scoreboard(score, length + i, spec + (i * p->specificity), p->exten, '.', callerid, p->deleted, p); if (score->exten) { ast_debug(4,"return because scoreboard has a match with '/'--- %s\n", score->exten->exten); return; /* the first match is all we need */ } } if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) { new_find_extension("/", score, p->next_char, length + i, spec+(p->specificity*i), callerid, label, action); if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) { ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set--- %s\n", score->exten ? score->exten->exten : "NULL"); return; /* the first match is all we need */ } } } else if (p->x[0] == '!' && p->x[1] == 0) { /* how many chars will the . match against? */ int i = 1; const char *str2 = str; while (*str2 && *str2 != '/') { str2++; i++; } if (p->exten && *str2 != '/') { update_scoreboard(score, length + 1, spec + (p->specificity * i), p->exten, '!', callerid, p->deleted, p); if (score->exten) { ast_debug(4, "return because scoreboard has a '!' match--- %s\n", score->exten->exten); return; /* the first match is all we need */ } } if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) { new_find_extension("/", score, p->next_char, length + i, spec + (p->specificity * i), callerid, label, action); if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) { ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/' and '!'--- %s\n", score->exten ? score->exten->exten : "NULL"); return; /* the first match is all we need */ } } } else if (p->x[0] == '/' && p->x[1] == 0) { /* the pattern in the tree includes the cid match! */ if (p->next_char && callerid && *callerid) { new_find_extension(callerid, score, p->next_char, length + 1, spec, callerid, label, action); if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) { ast_debug(4, "return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/'--- %s\n", score->exten ? score->exten->exten : "NULL"); return; /* the first match is all we need */ } } } else if (strchr(p->x, *str)) { ast_debug(4, "Nothing strange about this match\n"); NEW_MATCHER_CHK_MATCH; NEW_MATCHER_RECURSE; } } else if (strchr(p->x, *str)) { ast_debug(4, "Nothing strange about this match\n"); NEW_MATCHER_CHK_MATCH; NEW_MATCHER_RECURSE; } } ast_debug(4, "return at end of func\n"); } /* the algorithm for forming the extension pattern tree is also a bit simple; you * traverse all the extensions in a context, and for each char of the extension, * you see if it exists in the tree; if it doesn't, you add it at the appropriate * spot. What more can I say? At the end of each exten, you cap it off by adding the * address of the extension involved. Duplicate patterns will be complained about. * * Ideally, this would be done for each context after it is created and fully * filled. It could be done as a finishing step after extensions.conf or .ael is * loaded, or it could be done when the first search is encountered. It should only * have to be done once, until the next unload or reload. * * I guess forming this pattern tree would be analogous to compiling a regex. Except * that a regex only handles 1 pattern, really. This trie holds any number * of patterns. Well, really, it **could** be considered a single pattern, * where the "|" (or) operator is allowed, I guess, in a way, sort of... */ static struct match_char *already_in_tree(struct match_char *current, char *pat, int is_pattern) { struct match_char *t; if (!current) { return 0; } for (t = current; t; t = t->alt_char) { if (is_pattern == t->is_pattern && !strcmp(pat, t->x)) {/* uh, we may want to sort exploded [] contents to make matching easy */ return t; } } return 0; } /* The first arg is the location of the tree ptr, or the address of the next_char ptr in the node, so we can mess with it, if we need to insert at the beginning of the list */ static void insert_in_next_chars_alt_char_list(struct match_char **parent_ptr, struct match_char *node) { struct match_char *curr, *lcurr; /* insert node into the tree at "current", so the alt_char list from current is sorted in increasing value as you go to the leaves */ if (!(*parent_ptr)) { *parent_ptr = node; return; } if ((*parent_ptr)->specificity > node->specificity) { /* insert at head */ node->alt_char = (*parent_ptr); *parent_ptr = node; return; } lcurr = *parent_ptr; for (curr = (*parent_ptr)->alt_char; curr; curr = curr->alt_char) { if (curr->specificity > node->specificity) { node->alt_char = curr; lcurr->alt_char = node; break; } lcurr = curr; } if (!curr) { lcurr->alt_char = node; } } struct pattern_node { /*! Pattern node specificity */ int specif; /*! Pattern node match characters. */ char buf[256]; }; static struct match_char *add_pattern_node(struct ast_context *con, struct match_char *current, const struct pattern_node *pattern, int is_pattern, int already, struct match_char **nextcharptr) { struct match_char *m; if (!(m = ast_calloc(1, sizeof(*m) + strlen(pattern->buf)))) { return NULL; } /* strcpy is safe here since we know its size and have allocated * just enough space for when we allocated m */ strcpy(m->x, pattern->buf); /* the specificity scores are the same as used in the old pattern matcher. */ m->is_pattern = is_pattern; if (pattern->specif == 1 && is_pattern && pattern->buf[0] == 'N') { m->specificity = 0x0832; } else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == 'Z') { m->specificity = 0x0931; } else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == 'X') { m->specificity = 0x0a30; } else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == '.') { m->specificity = 0x18000; } else if (pattern->specif == 1 && is_pattern && pattern->buf[0] == '!') { m->specificity = 0x28000; } else { m->specificity = pattern->specif; } if (!con->pattern_tree) { insert_in_next_chars_alt_char_list(&con->pattern_tree, m); } else { if (already) { /* switch to the new regime (traversing vs appending)*/ insert_in_next_chars_alt_char_list(nextcharptr, m); } else { insert_in_next_chars_alt_char_list(&current->next_char, m); } } return m; } /*! * \internal * \brief Extract the next exten pattern node. * * \param node Pattern node to fill. * \param src Next source character to read. * \param pattern TRUE if the exten is a pattern. * \param extenbuf Original exten buffer to use in diagnostic messages. * * \retval Ptr to next extenbuf pos to read. */ static const char *get_pattern_node(struct pattern_node *node, const char *src, int pattern, const char *extenbuf) { #define INC_DST_OVERFLOW_CHECK \ do { \ if (dst - node->buf < sizeof(node->buf) - 1) { \ ++dst; \ } else { \ overflow = 1; \ } \ } while (0) node->specif = 0; node->buf[0] = '\0'; while (*src) { if (*src == '[' && pattern) { char *dst = node->buf; const char *src_next; int length; int overflow = 0; /* get past the '[' */ ++src; for (;;) { if (*src == '\\') { /* Escaped character. */ ++src; if (*src == '[' || *src == '\\' || *src == '-' || *src == ']') { *dst = *src++; INC_DST_OVERFLOW_CHECK; } } else if (*src == '-') { unsigned char first; unsigned char last; src_next = src; first = *(src_next - 1); last = *++src_next; if (last == '\\') { /* Escaped character. */ last = *++src_next; } /* Possible char range. */ if (node->buf[0] && last) { /* Expand the char range. */ while (++first <= last) { *dst = first; INC_DST_OVERFLOW_CHECK; } src = src_next + 1; } else { /* * There was no left or right char for the range. * It is just a '-'. */ *dst = *src++; INC_DST_OVERFLOW_CHECK; } } else if (*src == '\0') { ast_log(LOG_WARNING, "A matching ']' was not found for '[' in exten pattern '%s'\n", extenbuf); break; } else if (*src == ']') { ++src; break; } else { *dst = *src++; INC_DST_OVERFLOW_CHECK; } } /* null terminate the exploded range */ *dst = '\0'; if (overflow) { ast_log(LOG_ERROR, "Expanded character set too large to deal with in exten pattern '%s'. Ignoring character set.\n", extenbuf); node->buf[0] = '\0'; continue; } /* Sort the characters in character set. */ length = strlen(node->buf); if (!length) { ast_log(LOG_WARNING, "Empty character set in exten pattern '%s'. Ignoring.\n", extenbuf); node->buf[0] = '\0'; continue; } qsort(node->buf, length, 1, compare_char); /* Remove duplicate characters from character set. */ dst = node->buf; src_next = node->buf; while (*src_next++) { if (*dst != *src_next) { *++dst = *src_next; } } length = strlen(node->buf); length <<= 8; node->specif = length | (unsigned char) node->buf[0]; break; } else if (*src == '-') { /* Skip dashes in all extensions. */ ++src; } else { if (*src == '\\') { /* * XXX The escape character here does not remove any special * meaning to characters except the '[', '\\', and '-' * characters since they are special only in this function. */ node->buf[0] = *++src; if (!node->buf[0]) { break; } } else { node->buf[0] = *src; if (pattern) { /* make sure n,x,z patterns are canonicalized to N,X,Z */ if (node->buf[0] == 'n') { node->buf[0] = 'N'; } else if (node->buf[0] == 'x') { node->buf[0] = 'X'; } else if (node->buf[0] == 'z') { node->buf[0] = 'Z'; } } } node->buf[1] = '\0'; node->specif = 1; ++src; break; } } return src; #undef INC_DST_OVERFLOW_CHECK } static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly) { struct match_char *m1 = NULL; struct match_char *m2 = NULL; struct match_char **m0; const char *pos; int already; int pattern = 0; int idx_cur; int idx_next; char extenbuf[512]; struct pattern_node pat_node[2]; if (e1->matchcid) { if (sizeof(extenbuf) < strlen(e1->exten) + strlen(e1->cidmatch) + 2) { ast_log(LOG_ERROR, "The pattern %s/%s is too big to deal with: it will be ignored! Disaster!\n", e1->exten, e1->cidmatch); return NULL; } sprintf(extenbuf, "%s/%s", e1->exten, e1->cidmatch);/* Safe. We just checked. */ } else { ast_copy_string(extenbuf, e1->exten, sizeof(extenbuf)); } #ifdef NEED_DEBUG ast_log(LOG_DEBUG, "Adding exten %s to tree\n", extenbuf); #endif m1 = con->pattern_tree; /* each pattern starts over at the root of the pattern tree */ m0 = &con->pattern_tree; already = 1; pos = extenbuf; if (*pos == '_') { pattern = 1; ++pos; } idx_cur = 0; pos = get_pattern_node(&pat_node[idx_cur], pos, pattern, extenbuf); for (; pat_node[idx_cur].buf[0]; idx_cur = idx_next) { idx_next = (idx_cur + 1) % ARRAY_LEN(pat_node); pos = get_pattern_node(&pat_node[idx_next], pos, pattern, extenbuf); /* See about adding node to tree. */ m2 = NULL; if (already && (m2 = already_in_tree(m1, pat_node[idx_cur].buf, pattern)) && m2->next_char) { if (!pat_node[idx_next].buf[0]) { /* * This is the end of the pattern, but not the end of the tree. * Mark this node with the exten... a shorter pattern might win * if the longer one doesn't match. */ if (findonly) { return m2; } if (m2->exten) { ast_log(LOG_WARNING, "Found duplicate exten. Had %s found %s\n", m2->deleted ? "(deleted/invalid)" : m2->exten->exten, e1->exten); } m2->exten = e1; m2->deleted = 0; } m1 = m2->next_char; /* m1 points to the node to compare against */ m0 = &m2->next_char; /* m0 points to the ptr that points to m1 */ } else { /* not already OR not m2 OR nor m2->next_char */ if (m2) { if (findonly) { return m2; } m1 = m2; /* while m0 stays the same */ } else { if (findonly) { return m1; } m1 = add_pattern_node(con, m1, &pat_node[idx_cur], pattern, already, m0); if (!m1) { /* m1 is the node just added */ return NULL; } m0 = &m1->next_char; } if (!pat_node[idx_next].buf[0]) { if (m2 && m2->exten) { ast_log(LOG_WARNING, "Found duplicate exten. Had %s found %s\n", m2->deleted ? "(deleted/invalid)" : m2->exten->exten, e1->exten); } m1->deleted = 0; m1->exten = e1; } /* The 'already' variable is a mini-optimization designed to make it so that we * don't have to call already_in_tree when we know it will return false. */ already = 0; } } return m1; } static void create_match_char_tree(struct ast_context *con) { struct ast_hashtab_iter *t1; struct ast_exten *e1; #ifdef NEED_DEBUG int biggest_bucket, resizes, numobjs, numbucks; ast_log(LOG_DEBUG,"Creating Extension Trie for context %s(%p)\n", con->name, con); ast_hashtab_get_stats(con->root_table, &biggest_bucket, &resizes, &numobjs, &numbucks); ast_log(LOG_DEBUG,"This tree has %d objects in %d bucket lists, longest list=%d objects, and has resized %d times\n", numobjs, numbucks, biggest_bucket, resizes); #endif t1 = ast_hashtab_start_traversal(con->root_table); while ((e1 = ast_hashtab_next(t1))) { if (e1->exten) { add_exten_to_pattern_tree(con, e1, 0); } else { ast_log(LOG_ERROR, "Attempt to create extension with no extension name.\n"); } } ast_hashtab_end_traversal(t1); } static void destroy_pattern_tree(struct match_char *pattern_tree) /* pattern tree is a simple binary tree, sort of, so the proper way to destroy it is... recursively! */ { /* destroy all the alternates */ if (pattern_tree->alt_char) { destroy_pattern_tree(pattern_tree->alt_char); pattern_tree->alt_char = 0; } /* destroy all the nexts */ if (pattern_tree->next_char) { destroy_pattern_tree(pattern_tree->next_char); pattern_tree->next_char = 0; } pattern_tree->exten = 0; /* never hurts to make sure there's no pointers laying around */ ast_free(pattern_tree); } /*! * \internal * \brief Get the length of the exten string. * * \param str Exten to get length. * * \retval strlen of exten. */ static int ext_cmp_exten_strlen(const char *str) { int len; len = 0; for (;;) { /* Ignore '-' chars as eye candy fluff. */ while (*str == '-') { ++str; } if (!*str) { break; } ++str; ++len; } return len; } /*! * \internal * \brief Partial comparison of non-pattern extens. * * \param left Exten to compare. * \param right Exten to compare. Also matches if this string ends first. * * \retval <0 if left < right * \retval =0 if left == right * \retval >0 if left > right */ static int ext_cmp_exten_partial(const char *left, const char *right) { int cmp; for (;;) { /* Ignore '-' chars as eye candy fluff. */ while (*left == '-') { ++left; } while (*right == '-') { ++right; } if (!*right) { /* * Right ended first for partial match or both ended at the same * time for a match. */ cmp = 0; break; } cmp = *left - *right; if (cmp) { break; } ++left; ++right; } return cmp; } /*! * \internal * \brief Comparison of non-pattern extens. * * \param left Exten to compare. * \param right Exten to compare. * * \retval <0 if left < right * \retval =0 if left == right * \retval >0 if left > right */ static int ext_cmp_exten(const char *left, const char *right) { int cmp; for (;;) { /* Ignore '-' chars as eye candy fluff. */ while (*left == '-') { ++left; } while (*right == '-') { ++right; } cmp = *left - *right; if (cmp) { break; } if (!*left) { /* * Get here only if both strings ended at the same time. cmp * would be non-zero if only one string ended. */ break; } ++left; ++right; } return cmp; } /* * Special characters used in patterns: * '_' underscore is the leading character of a pattern. * In other position it is treated as a regular char. * '-' The '-' is a separator and ignored. Why? So patterns like NXX-XXX-XXXX work. * . one or more of any character. Only allowed at the end of * a pattern. * ! zero or more of anything. Also impacts the result of CANMATCH * and MATCHMORE. Only allowed at the end of a pattern. * In the core routine, ! causes a match with a return code of 2. * In turn, depending on the search mode: (XXX check if it is implemented) * - E_MATCH retuns 1 (does match) * - E_MATCHMORE returns 0 (no match) * - E_CANMATCH returns 1 (does match) * * / should not appear as it is considered the separator of the CID info. * XXX at the moment we may stop on this char. * * X Z N match ranges 0-9, 1-9, 2-9 respectively. * [ denotes the start of a set of character. Everything inside * is considered literally. We can have ranges a-d and individual * characters. A '[' and '-' can be considered literally if they * are just before ']'. * XXX currently there is no way to specify ']' in a range, nor \ is * considered specially. * * When we compare a pattern with a specific extension, all characters in the extension * itself are considered literally. * XXX do we want to consider space as a separator as well ? * XXX do we want to consider the separators in non-patterns as well ? */ /*! * \brief helper functions to sort extension patterns in the desired way, * so that more specific patterns appear first. * * \details * The function compares individual characters (or sets of), returning * an int where bits 0-7 are the ASCII code of the first char in the set, * bits 8-15 are the number of characters in the set, and bits 16-20 are * for special cases. * This way more specific patterns (smaller character sets) appear first. * Wildcards have a special value, so that we can directly compare them to * sets by subtracting the two values. In particular: * 0x001xx one character, character set starting with xx * 0x0yyxx yy characters, character set starting with xx * 0x18000 '.' (one or more of anything) * 0x28000 '!' (zero or more of anything) * 0x30000 NUL (end of string) * 0x40000 error in set. * The pointer to the string is advanced according to needs. * NOTES: * 1. the empty set is ignored. * 2. given that a full set has always 0 as the first element, * we could encode the special cases as 0xffXX where XX * is 1, 2, 3, 4 as used above. */ static int ext_cmp_pattern_pos(const char **p, unsigned char *bitwise) { #define BITS_PER 8 /* Number of bits per unit (byte). */ unsigned char c; unsigned char cmin; int count; const char *end; do { /* Get character and advance. (Ignore '-' chars as eye candy fluff.) */ do { c = *(*p)++; } while (c == '-'); /* always return unless we have a set of chars */ switch (c) { default: /* ordinary character */ bitwise[c / BITS_PER] = 1 << ((BITS_PER - 1) - (c % BITS_PER)); return 0x0100 | c; case 'n': case 'N': /* 2..9 */ bitwise[6] = 0x3f; bitwise[7] = 0xc0; return 0x0800 | '2'; case 'x': case 'X': /* 0..9 */ bitwise[6] = 0xff; bitwise[7] = 0xc0; return 0x0A00 | '0'; case 'z': case 'Z': /* 1..9 */ bitwise[6] = 0x7f; bitwise[7] = 0xc0; return 0x0900 | '1'; case '.': /* wildcard */ return 0x18000; case '!': /* earlymatch */ return 0x28000; /* less specific than '.' */ case '\0': /* empty string */ *p = NULL; return 0x30000; case '[': /* char set */ break; } /* locate end of set */ end = strchr(*p, ']'); if (!end) { ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n"); return 0x40000; /* XXX make this entry go last... */ } count = 0; cmin = 0xFF; for (; *p < end; ++*p) { unsigned char c1; /* first char in range */ unsigned char c2; /* last char in range */ c1 = (*p)[0]; if (*p + 2 < end && (*p)[1] == '-') { /* this is a range */ c2 = (*p)[2]; *p += 2; /* skip a total of 3 chars */ } else { /* individual character */ c2 = c1; } if (c1 < cmin) { cmin = c1; } for (; c1 <= c2; ++c1) { unsigned char mask = 1 << ((BITS_PER - 1) - (c1 % BITS_PER)); /* * Note: If two character sets score the same, the one with the * lowest ASCII values will compare as coming first. Must fill * in most significant bits for lower ASCII values to accomplish * the desired sort order. */ if (!(bitwise[c1 / BITS_PER] & mask)) { /* Add the character to the set. */ bitwise[c1 / BITS_PER] |= mask; count += 0x100; } } } ++*p; } while (!count);/* While the char set was empty. */ return count | cmin; } /*! * \internal * \brief Comparison of exten patterns. * * \param left Pattern to compare. * \param right Pattern to compare. * * \retval <0 if left < right * \retval =0 if left == right * \retval >0 if left > right */ static int ext_cmp_pattern(const char *left, const char *right) { int cmp; int left_pos; int right_pos; for (;;) { unsigned char left_bitwise[32] = { 0, }; unsigned char right_bitwise[32] = { 0, }; left_pos = ext_cmp_pattern_pos(&left, left_bitwise); right_pos = ext_cmp_pattern_pos(&right, right_bitwise); cmp = left_pos - right_pos; if (!cmp) { /* * Are the character sets different, even though they score the same? * * Note: Must swap left and right to get the sense of the * comparison correct. Otherwise, we would need to multiply by * -1 instead. */ cmp = memcmp(right_bitwise, left_bitwise, ARRAY_LEN(left_bitwise)); } if (cmp) { break; } if (!left) { /* * Get here only if both patterns ended at the same time. cmp * would be non-zero if only one pattern ended. */ break; } } return cmp; } /*! * \internal * \brief Comparison of dialplan extens for sorting purposes. * * \param left Exten/pattern to compare. * \param right Exten/pattern to compare. * * \retval <0 if left < right * \retval =0 if left == right * \retval >0 if left > right */ static int ext_cmp(const char *left, const char *right) { /* Make sure non-pattern extens come first. */ if (left[0] != '_') { if (right[0] == '_') { return -1; } /* Compare two non-pattern extens. */ return ext_cmp_exten(left, right); } if (right[0] != '_') { return 1; } /* * OK, we need full pattern sorting routine. * * Skip past the underscores */ return ext_cmp_pattern(left + 1, right + 1); } int ast_extension_cmp(const char *a, const char *b) { int cmp; cmp = ext_cmp(a, b); if (cmp < 0) { return -1; } if (cmp > 0) { return 1; } return 0; } /*! * \internal * \brief used ast_extension_{match|close} * mode is as follows: * E_MATCH success only on exact match * E_MATCHMORE success only on partial match (i.e. leftover digits in pattern) * E_CANMATCH either of the above. * \retval 0 on no-match * \retval 1 on match * \retval 2 on early match. */ static int _extension_match_core(const char *pattern, const char *data, enum ext_match_t mode) { mode &= E_MATCH_MASK; /* only consider the relevant bits */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"match core: pat: '%s', dat: '%s', mode=%d\n", pattern, data, (int)mode); #endif if (pattern[0] != '_') { /* not a pattern, try exact or partial match */ int lp = ext_cmp_exten_strlen(pattern); int ld = ext_cmp_exten_strlen(data); if (lp < ld) { /* pattern too short, cannot match */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"return (0) - pattern too short, cannot match\n"); #endif return 0; } /* depending on the mode, accept full or partial match or both */ if (mode == E_MATCH) { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"return (!ext_cmp_exten(%s,%s) when mode== E_MATCH)\n", pattern, data); #endif return !ext_cmp_exten(pattern, data); /* 1 on match, 0 on fail */ } if (ld == 0 || !ext_cmp_exten_partial(pattern, data)) { /* partial or full match */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"return (mode(%d) == E_MATCHMORE ? lp(%d) > ld(%d) : 1)\n", mode, lp, ld); #endif return (mode == E_MATCHMORE) ? lp > ld : 1; /* XXX should consider '!' and '/' ? */ } else { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"return (0) when ld(%d) > 0 && pattern(%s) != data(%s)\n", ld, pattern, data); #endif return 0; } } if (mode == E_MATCH && data[0] == '_') { /* * XXX It is bad design that we don't know if we should be * comparing data and pattern as patterns or comparing data if * it conforms to pattern when the function is called. First, * assume they are both patterns. If they don't match then try * to see if data conforms to the given pattern. * * note: if this test is left out, then _x. will not match _x. !!! */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "Comparing as patterns first. pattern:%s data:%s\n", pattern, data); #endif if (!ext_cmp_pattern(pattern + 1, data + 1)) { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"return (1) - pattern matches pattern\n"); #endif return 1; } } ++pattern; /* skip leading _ */ /* * XXX below we stop at '/' which is a separator for the CID info. However we should * not store '/' in the pattern at all. When we insure it, we can remove the checks. */ for (;;) { const char *end; /* Ignore '-' chars as eye candy fluff. */ while (*data == '-') { ++data; } while (*pattern == '-') { ++pattern; } if (!*data || !*pattern || *pattern == '/') { break; } switch (*pattern) { case '[': /* a range */ ++pattern; end = strchr(pattern, ']'); /* XXX should deal with escapes ? */ if (!end) { ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n"); return 0; /* unconditional failure */ } if (pattern == end) { /* Ignore empty character sets. */ ++pattern; continue; } for (; pattern < end; ++pattern) { if (pattern+2 < end && pattern[1] == '-') { /* this is a range */ if (*data >= pattern[0] && *data <= pattern[2]) break; /* match found */ else { pattern += 2; /* skip a total of 3 chars */ continue; } } else if (*data == pattern[0]) break; /* match found */ } if (pattern >= end) { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"return (0) when pattern>=end\n"); #endif return 0; } pattern = end; /* skip and continue */ break; case 'n': case 'N': if (*data < '2' || *data > '9') { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"return (0) N is not matched\n"); #endif return 0; } break; case 'x': case 'X': if (*data < '0' || *data > '9') { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"return (0) X is not matched\n"); #endif return 0; } break; case 'z': case 'Z': if (*data < '1' || *data > '9') { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"return (0) Z is not matched\n"); #endif return 0; } break; case '.': /* Must match, even with more digits */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "return (1) when '.' is matched\n"); #endif return 1; case '!': /* Early match */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "return (2) when '!' is matched\n"); #endif return 2; default: if (*data != *pattern) { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "return (0) when *data(%c) != *pattern(%c)\n", *data, *pattern); #endif return 0; } break; } ++data; ++pattern; } if (*data) /* data longer than pattern, no match */ { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "return (0) when data longer than pattern\n"); #endif return 0; } /* * match so far, but ran off the end of data. * Depending on what is next, determine match or not. */ if (*pattern == '\0' || *pattern == '/') { /* exact match */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "at end, return (%d) in 'exact match'\n", (mode==E_MATCHMORE) ? 0 : 1); #endif return (mode == E_MATCHMORE) ? 0 : 1; /* this is a failure for E_MATCHMORE */ } else if (*pattern == '!') { /* early match */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "at end, return (2) when '!' is matched\n"); #endif return 2; } else { /* partial match */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "at end, return (%d) which deps on E_MATCH\n", (mode == E_MATCH) ? 0 : 1); #endif return (mode == E_MATCH) ? 0 : 1; /* this is a failure for E_MATCH */ } } /* * Wrapper around _extension_match_core() to do performance measurement * using the profiling code. */ static int extension_match_core(const char *pattern, const char *data, enum ext_match_t mode) { int i; static int prof_id = -2; /* marker for 'unallocated' id */ if (prof_id == -2) { prof_id = ast_add_profile("ext_match", 0); } ast_mark(prof_id, 1); i = _extension_match_core(ast_strlen_zero(pattern) ? "" : pattern, ast_strlen_zero(data) ? "" : data, mode); ast_mark(prof_id, 0); return i; } int ast_extension_match(const char *pattern, const char *data) { return extension_match_core(pattern, data, E_MATCH); } int ast_extension_close(const char *pattern, const char *data, int needmore) { if (needmore != E_MATCHMORE && needmore != E_CANMATCH) ast_log(LOG_WARNING, "invalid argument %d\n", needmore); return extension_match_core(pattern, data, needmore); } struct fake_context /* this struct is purely for matching in the hashtab */ { ast_rwlock_t lock; struct ast_exten *root; struct ast_hashtab *root_table; struct match_char *pattern_tree; struct ast_context *next; struct ast_include *includes; struct ast_ignorepat *ignorepats; const char *registrar; int refcount; AST_LIST_HEAD_NOLOCK(, ast_sw) alts; ast_mutex_t macrolock; char name[256]; }; struct ast_context *ast_context_find(const char *name) { struct ast_context *tmp; struct fake_context item; if (!name) { return NULL; } ast_rdlock_contexts(); if (contexts_table) { ast_copy_string(item.name, name, sizeof(item.name)); tmp = ast_hashtab_lookup(contexts_table, &item); } else { tmp = NULL; while ((tmp = ast_walk_contexts(tmp))) { if (!strcasecmp(name, tmp->name)) { break; } } } ast_unlock_contexts(); return tmp; } #define STATUS_NO_CONTEXT 1 #define STATUS_NO_EXTENSION 2 #define STATUS_NO_PRIORITY 3 #define STATUS_NO_LABEL 4 #define STATUS_SUCCESS 5 static int matchcid(const char *cidpattern, const char *callerid) { /* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so failing to get a number should count as a match, otherwise not */ if (ast_strlen_zero(callerid)) { return ast_strlen_zero(cidpattern) ? 1 : 0; } return ast_extension_match(cidpattern, callerid); } struct ast_exten *pbx_find_extension(struct ast_channel *chan, struct ast_context *bypass, struct pbx_find_info *q, const char *context, const char *exten, int priority, const char *label, const char *callerid, enum ext_match_t action) { int x, res; struct ast_context *tmp = NULL; struct ast_exten *e = NULL, *eroot = NULL; struct ast_include *i = NULL; struct ast_sw *sw = NULL; struct ast_exten pattern = {NULL, }; struct scoreboard score = {0, }; struct ast_str *tmpdata = NULL; pattern.label = label; pattern.priority = priority; #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "Looking for cont/ext/prio/label/action = %s/%s/%d/%s/%d\n", context, exten, priority, label, (int) action); #endif /* Initialize status if appropriate */ if (q->stacklen == 0) { q->status = STATUS_NO_CONTEXT; q->swo = NULL; q->data = NULL; q->foundcontext = NULL; } else if (q->stacklen >= AST_PBX_MAX_STACK) { ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n"); return NULL; } /* Check first to see if we've already been checked */ for (x = 0; x < q->stacklen; x++) { if (!strcasecmp(q->incstack[x], context)) return NULL; } if (bypass) { /* bypass means we only look there */ tmp = bypass; } else { /* look in contexts */ tmp = find_context(context); if (!tmp) { return NULL; } } if (q->status < STATUS_NO_EXTENSION) q->status = STATUS_NO_EXTENSION; /* Do a search for matching extension */ eroot = NULL; score.total_specificity = 0; score.exten = 0; score.total_length = 0; if (!tmp->pattern_tree && tmp->root_table) { create_match_char_tree(tmp); #ifdef NEED_DEBUG ast_log(LOG_DEBUG, "Tree Created in context %s:\n", context); log_match_char_tree(tmp->pattern_tree," "); #endif } #ifdef NEED_DEBUG ast_log(LOG_NOTICE, "The Trie we are searching in:\n"); log_match_char_tree(tmp->pattern_tree, ":: "); #endif do { if (!ast_strlen_zero(overrideswitch)) { char *osw = ast_strdupa(overrideswitch), *name; struct ast_switch *asw; ast_switch_f *aswf = NULL; char *datap; int eval = 0; name = strsep(&osw, "/"); asw = pbx_findswitch(name); if (!asw) { ast_log(LOG_WARNING, "No such switch '%s'\n", name); break; } if (osw && strchr(osw, '$')) { eval = 1; } if (eval && !(tmpdata = ast_str_thread_get(&switch_data, 512))) { ast_log(LOG_WARNING, "Can't evaluate overrideswitch?!\n"); break; } else if (eval) { /* Substitute variables now */ pbx_substitute_variables_helper(chan, osw, ast_str_buffer(tmpdata), ast_str_size(tmpdata)); datap = ast_str_buffer(tmpdata); } else { datap = osw; } /* equivalent of extension_match_core() at the switch level */ if (action == E_CANMATCH) aswf = asw->canmatch; else if (action == E_MATCHMORE) aswf = asw->matchmore; else /* action == E_MATCH */ aswf = asw->exists; if (!aswf) { res = 0; } else { if (chan) { ast_autoservice_start(chan); } res = aswf(chan, context, exten, priority, callerid, datap); if (chan) { ast_autoservice_stop(chan); } } if (res) { /* Got a match */ q->swo = asw; q->data = datap; q->foundcontext = context; /* XXX keep status = STATUS_NO_CONTEXT ? */ return NULL; } } } while (0); if (extenpatternmatchnew) { new_find_extension(exten, &score, tmp->pattern_tree, 0, 0, callerid, label, action); eroot = score.exten; if (score.last_char == '!' && action == E_MATCHMORE) { /* We match an extension ending in '!'. * The decision in this case is final and is NULL (no match). */ #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"Returning MATCHMORE NULL with exclamation point.\n"); #endif return NULL; } if (!eroot && (action == E_CANMATCH || action == E_MATCHMORE) && score.canmatch_exten) { q->status = STATUS_SUCCESS; #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"Returning CANMATCH exten %s\n", score.canmatch_exten->exten); #endif return score.canmatch_exten; } if ((action == E_MATCHMORE || action == E_CANMATCH) && eroot) { if (score.node) { struct ast_exten *z = trie_find_next_match(score.node); if (z) { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten %s\n", z->exten); #endif } else { if (score.canmatch_exten) { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE canmatchmatch exten %s(%p)\n", score.canmatch_exten->exten, score.canmatch_exten); #endif return score.canmatch_exten; } else { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten NULL\n"); #endif } } return z; } #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE, "Returning CANMATCH/MATCHMORE NULL (no next_match)\n"); #endif return NULL; /* according to the code, complete matches are null matches in MATCHMORE mode */ } if (eroot) { /* found entry, now look for the right priority */ if (q->status < STATUS_NO_PRIORITY) q->status = STATUS_NO_PRIORITY; e = NULL; if (action == E_FINDLABEL && label ) { if (q->status < STATUS_NO_LABEL) q->status = STATUS_NO_LABEL; e = ast_hashtab_lookup(eroot->peer_label_table, &pattern); } else { e = ast_hashtab_lookup(eroot->peer_table, &pattern); } if (e) { /* found a valid match */ q->status = STATUS_SUCCESS; q->foundcontext = context; #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"Returning complete match of exten %s\n", e->exten); #endif return e; } } } else { /* the old/current default exten pattern match algorithm */ /* scan the list trying to match extension and CID */ eroot = NULL; while ( (eroot = ast_walk_context_extensions(tmp, eroot)) ) { int match = extension_match_core(eroot->exten, exten, action); /* 0 on fail, 1 on match, 2 on earlymatch */ if (!match || (eroot->matchcid && !matchcid(eroot->cidmatch, callerid))) continue; /* keep trying */ if (match == 2 && action == E_MATCHMORE) { /* We match an extension ending in '!'. * The decision in this case is final and is NULL (no match). */ return NULL; } /* found entry, now look for the right priority */ if (q->status < STATUS_NO_PRIORITY) q->status = STATUS_NO_PRIORITY; e = NULL; if (action == E_FINDLABEL && label ) { if (q->status < STATUS_NO_LABEL) q->status = STATUS_NO_LABEL; e = ast_hashtab_lookup(eroot->peer_label_table, &pattern); } else { e = ast_hashtab_lookup(eroot->peer_table, &pattern); } if (e) { /* found a valid match */ q->status = STATUS_SUCCESS; q->foundcontext = context; return e; } } } /* Check alternative switches */ AST_LIST_TRAVERSE(&tmp->alts, sw, list) { struct ast_switch *asw = pbx_findswitch(sw->name); ast_switch_f *aswf = NULL; char *datap; if (!asw) { ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name); continue; } /* Substitute variables now */ if (sw->eval) { if (!(tmpdata = ast_str_thread_get(&switch_data, 512))) { ast_log(LOG_WARNING, "Can't evaluate switch?!\n"); continue; } pbx_substitute_variables_helper(chan, sw->data, ast_str_buffer(tmpdata), ast_str_size(tmpdata)); } /* equivalent of extension_match_core() at the switch level */ if (action == E_CANMATCH) aswf = asw->canmatch; else if (action == E_MATCHMORE) aswf = asw->matchmore; else /* action == E_MATCH */ aswf = asw->exists; datap = sw->eval ? ast_str_buffer(tmpdata) : sw->data; if (!aswf) res = 0; else { if (chan) ast_autoservice_start(chan); res = aswf(chan, context, exten, priority, callerid, datap); if (chan) ast_autoservice_stop(chan); } if (res) { /* Got a match */ q->swo = asw; q->data = datap; q->foundcontext = context; /* XXX keep status = STATUS_NO_CONTEXT ? */ return NULL; } } q->incstack[q->stacklen++] = tmp->name; /* Setup the stack */ /* Now try any includes we have in this context */ for (i = tmp->includes; i; i = i->next) { if (include_valid(i)) { if ((e = pbx_find_extension(chan, bypass, q, i->rname, exten, priority, label, callerid, action))) { #ifdef NEED_DEBUG_HERE ast_log(LOG_NOTICE,"Returning recursive match of %s\n", e->exten); #endif return e; } if (q->swo) return NULL; } } return NULL; } /*! * \brief extract offset:length from variable name. * \return 1 if there is a offset:length part, which is * trimmed off (values go into variables) */ static int parse_variable_name(char *var, int *offset, int *length, int *isfunc) { int parens = 0; *offset = 0; *length = INT_MAX; *isfunc = 0; for (; *var; var++) { if (*var == '(') { (*isfunc)++; parens++; } else if (*var == ')') { parens--; } else if (*var == ':' && parens == 0) { *var++ = '\0'; sscanf(var, "%30d:%30d", offset, length); return 1; /* offset:length valid */ } } return 0; } /*! *\brief takes a substring. It is ok to call with value == workspace. * \param value * \param offset < 0 means start from the end of the string and set the beginning * to be that many characters back. * \param length is the length of the substring, a value less than 0 means to leave * that many off the end. * \param workspace * \param workspace_len * Always return a copy in workspace. */ static char *substring(const char *value, int offset, int length, char *workspace, size_t workspace_len) { char *ret = workspace; int lr; /* length of the input string after the copy */ ast_copy_string(workspace, value, workspace_len); /* always make a copy */ lr = strlen(ret); /* compute length after copy, so we never go out of the workspace */ /* Quick check if no need to do anything */ if (offset == 0 && length >= lr) /* take the whole string */ return ret; if (offset < 0) { /* translate negative offset into positive ones */ offset = lr + offset; if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */ offset = 0; } /* too large offset result in empty string so we know what to return */ if (offset >= lr) return ret + lr; /* the final '\0' */ ret += offset; /* move to the start position */ if (length >= 0 && length < lr - offset) /* truncate if necessary */ ret[length] = '\0'; else if (length < 0) { if (lr > offset - length) /* After we remove from the front and from the rear, is there anything left? */ ret[lr + length - offset] = '\0'; else ret[0] = '\0'; } return ret; } static const char *ast_str_substring(struct ast_str *value, int offset, int length) { int lr; /* length of the input string after the copy */ lr = ast_str_strlen(value); /* compute length after copy, so we never go out of the workspace */ /* Quick check if no need to do anything */ if (offset == 0 && length >= lr) /* take the whole string */ return ast_str_buffer(value); if (offset < 0) { /* translate negative offset into positive ones */ offset = lr + offset; if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */ offset = 0; } /* too large offset result in empty string so we know what to return */ if (offset >= lr) { ast_str_reset(value); return ast_str_buffer(value); } if (offset > 0) { /* Go ahead and chop off the beginning */ memmove(ast_str_buffer(value), ast_str_buffer(value) + offset, ast_str_strlen(value) - offset + 1); lr -= offset; } if (length >= 0 && length < lr) { /* truncate if necessary */ char *tmp = ast_str_buffer(value); tmp[length] = '\0'; ast_str_update(value); } else if (length < 0) { if (lr > -length) { /* After we remove from the front and from the rear, is there anything left? */ char *tmp = ast_str_buffer(value); tmp[lr + length] = '\0'; ast_str_update(value); } else { ast_str_reset(value); } } else { /* Nothing to do, but update the buffer length */ ast_str_update(value); } return ast_str_buffer(value); } /*! \brief Support for Asterisk built-in variables in the dialplan \note See also - \ref AstVar Channel variables - \ref AstCauses The HANGUPCAUSE variable */ void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp) { struct ast_str *str = ast_str_create(16); const char *cret; cret = ast_str_retrieve_variable(&str, 0, c, headp, var); ast_copy_string(workspace, ast_str_buffer(str), workspacelen); *ret = cret ? workspace : NULL; ast_free(str); } const char *ast_str_retrieve_variable(struct ast_str **str, ssize_t maxlen, struct ast_channel *c, struct varshead *headp, const char *var) { const char not_found = '\0'; char *tmpvar; const char *ret; const char *s; /* the result */ int offset, length; int i, need_substring; struct varshead *places[2] = { headp, &globals }; /* list of places where we may look */ char workspace[20]; if (c) { ast_channel_lock(c); places[0] = &c->varshead; } /* * Make a copy of var because parse_variable_name() modifies the string. * Then if called directly, we might need to run substring() on the result; * remember this for later in 'need_substring', 'offset' and 'length' */ tmpvar = ast_strdupa(var); /* parse_variable_name modifies the string */ need_substring = parse_variable_name(tmpvar, &offset, &length, &i /* ignored */); /* * Look first into predefined variables, then into variable lists. * Variable 's' points to the result, according to the following rules: * s == &not_found (set at the beginning) means that we did not find a * matching variable and need to look into more places. * If s != &not_found, s is a valid result string as follows: * s = NULL if the variable does not have a value; * you typically do this when looking for an unset predefined variable. * s = workspace if the result has been assembled there; * typically done when the result is built e.g. with an snprintf(), * so we don't need to do an additional copy. * s != workspace in case we have a string, that needs to be copied * (the ast_copy_string is done once for all at the end). * Typically done when the result is already available in some string. */ s = &not_found; /* default value */ if (c) { /* This group requires a valid channel */ /* Names with common parts are looked up a piece at a time using strncmp. */ if (!strncmp(var, "CALL", 4)) { if (!strncmp(var + 4, "ING", 3)) { if (!strcmp(var + 7, "PRES")) { /* CALLINGPRES */ ast_str_set(str, maxlen, "%d", ast_party_id_presentation(&c->caller.id)); s = ast_str_buffer(*str); } else if (!strcmp(var + 7, "ANI2")) { /* CALLINGANI2 */ ast_str_set(str, maxlen, "%d", c->caller.ani2); s = ast_str_buffer(*str); } else if (!strcmp(var + 7, "TON")) { /* CALLINGTON */ ast_str_set(str, maxlen, "%d", c->caller.id.number.plan); s = ast_str_buffer(*str); } else if (!strcmp(var + 7, "TNS")) { /* CALLINGTNS */ ast_str_set(str, maxlen, "%d", c->dialed.transit_network_select); s = ast_str_buffer(*str); } } } else if (!strcmp(var, "HINT")) { s = ast_str_get_hint(str, maxlen, NULL, 0, c, c->context, c->exten) ? ast_str_buffer(*str) : NULL; } else if (!strcmp(var, "HINTNAME")) { s = ast_str_get_hint(NULL, 0, str, maxlen, c, c->context, c->exten) ? ast_str_buffer(*str) : NULL; } else if (!strcmp(var, "EXTEN")) { s = c->exten; } else if (!strcmp(var, "CONTEXT")) { s = c->context; } else if (!strcmp(var, "PRIORITY")) { ast_str_set(str, maxlen, "%d", c->priority); s = ast_str_buffer(*str); } else if (!strcmp(var, "CHANNEL")) { s = c->name; } else if (!strcmp(var, "UNIQUEID")) { s = c->uniqueid; } else if (!strcmp(var, "HANGUPCAUSE")) { ast_str_set(str, maxlen, "%d", c->hangupcause); s = ast_str_buffer(*str); } } if (s == &not_found) { /* look for more */ if (!strcmp(var, "EPOCH")) { ast_str_set(str, maxlen, "%u", (int) time(NULL)); s = ast_str_buffer(*str); } else if (!strcmp(var, "SYSTEMNAME")) { s = ast_config_AST_SYSTEM_NAME; } else if (!strcmp(var, "ENTITYID")) { ast_eid_to_str(workspace, sizeof(workspace), &ast_eid_default); s = workspace; } } /* if not found, look into chanvars or global vars */ for (i = 0; s == &not_found && i < ARRAY_LEN(places); i++) { struct ast_var_t *variables; if (!places[i]) continue; if (places[i] == &globals) ast_rwlock_rdlock(&globalslock); AST_LIST_TRAVERSE(places[i], variables, entries) { if (!strcasecmp(ast_var_name(variables), var)) { s = ast_var_value(variables); break; } } if (places[i] == &globals) ast_rwlock_unlock(&globalslock); } if (s == &not_found || s == NULL) { ast_debug(5, "Result of '%s' is NULL\n", var); ret = NULL; } else { ast_debug(5, "Result of '%s' is '%s'\n", var, s); if (s != ast_str_buffer(*str)) { ast_str_set(str, maxlen, "%s", s); } ret = ast_str_buffer(*str); if (need_substring) { ret = ast_str_substring(*str, offset, length); ast_debug(2, "Final result of '%s' is '%s'\n", var, ret); } } if (c) { ast_channel_unlock(c); } return ret; } static void exception_store_free(void *data) { struct pbx_exception *exception = data; ast_string_field_free_memory(exception); ast_free(exception); } static const struct ast_datastore_info exception_store_info = { .type = "EXCEPTION", .destroy = exception_store_free, }; /*! * \internal * \brief Set the PBX to execute the exception extension. * * \param chan Channel to raise the exception on. * \param reason Reason exception is raised. * \param priority Dialplan priority to set. * * \retval 0 on success. * \retval -1 on error. */ static int raise_exception(struct ast_channel *chan, const char *reason, int priority) { struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL); struct pbx_exception *exception = NULL; if (!ds) { ds = ast_datastore_alloc(&exception_store_info, NULL); if (!ds) return -1; if (!(exception = ast_calloc_with_stringfields(1, struct pbx_exception, 128))) { ast_datastore_free(ds); return -1; } ds->data = exception; ast_channel_datastore_add(chan, ds); } else exception = ds->data; ast_string_field_set(exception, reason, reason); ast_string_field_set(exception, context, chan->context); ast_string_field_set(exception, exten, chan->exten); exception->priority = chan->priority; set_ext_pri(chan, "e", priority); return 0; } int pbx_builtin_raise_exception(struct ast_channel *chan, const char *reason) { /* Priority will become 1, next time through the AUTOLOOP */ return raise_exception(chan, reason, 0); } static int acf_exception_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen) { struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL); struct pbx_exception *exception = NULL; if (!ds || !ds->data) return -1; exception = ds->data; if (!strcasecmp(data, "REASON")) ast_copy_string(buf, exception->reason, buflen); else if (!strcasecmp(data, "CONTEXT")) ast_copy_string(buf, exception->context, buflen); else if (!strncasecmp(data, "EXTEN", 5)) ast_copy_string(buf, exception->exten, buflen); else if (!strcasecmp(data, "PRIORITY")) snprintf(buf, buflen, "%d", exception->priority); else return -1; return 0; } static struct ast_custom_function exception_function = { .name = "EXCEPTION", .read = acf_exception_read, }; static char *handle_show_functions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_custom_function *acf; int count_acf = 0; int like = 0; switch (cmd) { case CLI_INIT: e->command = "core show functions [like]"; e->usage = "Usage: core show functions [like <text>]\n" " List builtin functions, optionally only those matching a given string\n"; return NULL; case CLI_GENERATE: return NULL; } if (a->argc == 5 && (!strcmp(a->argv[3], "like")) ) { like = 1; } else if (a->argc != 3) { return CLI_SHOWUSAGE; } ast_cli(a->fd, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like ? "Matching" : "Installed"); AST_RWLIST_RDLOCK(&acf_root); AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) { if (!like || strstr(acf->name, a->argv[4])) { count_acf++; ast_cli(a->fd, "%-20.20s %-35.35s %s\n", S_OR(acf->name, ""), S_OR(acf->syntax, ""), S_OR(acf->synopsis, "")); } } AST_RWLIST_UNLOCK(&acf_root); ast_cli(a->fd, "%d %scustom functions installed.\n", count_acf, like ? "matching " : ""); return CLI_SUCCESS; } static char *handle_show_function(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_custom_function *acf; /* Maximum number of characters added by terminal coloring is 22 */ char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40], argtitle[40], seealsotitle[40]; char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL, *seealso = NULL; char stxtitle[40], *syntax = NULL, *arguments = NULL; int syntax_size, description_size, synopsis_size, arguments_size, seealso_size; char *ret = NULL; int which = 0; int wordlen; switch (cmd) { case CLI_INIT: e->command = "core show function"; e->usage = "Usage: core show function <function>\n" " Describe a particular dialplan function.\n"; return NULL; case CLI_GENERATE: wordlen = strlen(a->word); /* case-insensitive for convenience in this 'complete' function */ AST_RWLIST_RDLOCK(&acf_root); AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) { if (!strncasecmp(a->word, acf->name, wordlen) && ++which > a->n) { ret = ast_strdup(acf->name); break; } } AST_RWLIST_UNLOCK(&acf_root); return ret; } if (a->argc < 4) { return CLI_SHOWUSAGE; } if (!(acf = ast_custom_function_find(a->argv[3]))) { ast_cli(a->fd, "No function by that name registered.\n"); return CLI_FAILURE; } syntax_size = strlen(S_OR(acf->syntax, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; if (!(syntax = ast_malloc(syntax_size))) { ast_cli(a->fd, "Memory allocation failure!\n"); return CLI_FAILURE; } snprintf(info, sizeof(info), "\n -= Info about function '%s' =- \n\n", acf->name); term_color(infotitle, info, COLOR_MAGENTA, 0, sizeof(infotitle)); term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40); term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40); term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40); term_color(argtitle, "[Arguments]\n", COLOR_MAGENTA, 0, 40); term_color(seealsotitle, "[See Also]\n", COLOR_MAGENTA, 0, 40); term_color(syntax, S_OR(acf->syntax, "Not available"), COLOR_CYAN, 0, syntax_size); #ifdef AST_XML_DOCS if (acf->docsrc == AST_XML_DOC) { arguments = ast_xmldoc_printable(S_OR(acf->arguments, "Not available"), 1); synopsis = ast_xmldoc_printable(S_OR(acf->synopsis, "Not available"), 1); description = ast_xmldoc_printable(S_OR(acf->desc, "Not available"), 1); seealso = ast_xmldoc_printable(S_OR(acf->seealso, "Not available"), 1); } else #endif { synopsis_size = strlen(S_OR(acf->synopsis, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; synopsis = ast_malloc(synopsis_size); description_size = strlen(S_OR(acf->desc, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; description = ast_malloc(description_size); arguments_size = strlen(S_OR(acf->arguments, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; arguments = ast_malloc(arguments_size); seealso_size = strlen(S_OR(acf->seealso, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; seealso = ast_malloc(seealso_size); /* check allocated memory. */ if (!synopsis || !description || !arguments || !seealso) { ast_free(synopsis); ast_free(description); ast_free(arguments); ast_free(seealso); ast_free(syntax); return CLI_FAILURE; } term_color(arguments, S_OR(acf->arguments, "Not available"), COLOR_CYAN, 0, arguments_size); term_color(synopsis, S_OR(acf->synopsis, "Not available"), COLOR_CYAN, 0, synopsis_size); term_color(description, S_OR(acf->desc, "Not available"), COLOR_CYAN, 0, description_size); term_color(seealso, S_OR(acf->seealso, "Not available"), COLOR_CYAN, 0, seealso_size); } ast_cli(a->fd, "%s%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n", infotitle, syntitle, synopsis, destitle, description, stxtitle, syntax, argtitle, arguments, seealsotitle, seealso); ast_free(arguments); ast_free(synopsis); ast_free(description); ast_free(seealso); ast_free(syntax); return CLI_SUCCESS; } struct ast_custom_function *ast_custom_function_find(const char *name) { struct ast_custom_function *acf = NULL; AST_RWLIST_RDLOCK(&acf_root); AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) { if (!strcmp(name, acf->name)) break; } AST_RWLIST_UNLOCK(&acf_root); return acf; } int ast_custom_function_unregister(struct ast_custom_function *acf) { struct ast_custom_function *cur; if (!acf) { return -1; } AST_RWLIST_WRLOCK(&acf_root); if ((cur = AST_RWLIST_REMOVE(&acf_root, acf, acflist))) { #ifdef AST_XML_DOCS if (cur->docsrc == AST_XML_DOC) { ast_string_field_free_memory(acf); } #endif ast_verb(2, "Unregistered custom function %s\n", cur->name); } AST_RWLIST_UNLOCK(&acf_root); return cur ? 0 : -1; } /*! \internal * \brief Retrieve the XML documentation of a specified ast_custom_function, * and populate ast_custom_function string fields. * \param acf ast_custom_function structure with empty 'desc' and 'synopsis' * but with a function 'name'. * \retval -1 On error. * \retval 0 On succes. */ static int acf_retrieve_docs(struct ast_custom_function *acf) { #ifdef AST_XML_DOCS char *tmpxml; /* Let's try to find it in the Documentation XML */ if (!ast_strlen_zero(acf->desc) || !ast_strlen_zero(acf->synopsis)) { return 0; } if (ast_string_field_init(acf, 128)) { return -1; } /* load synopsis */ tmpxml = ast_xmldoc_build_synopsis("function", acf->name, ast_module_name(acf->mod)); ast_string_field_set(acf, synopsis, tmpxml); ast_free(tmpxml); /* load description */ tmpxml = ast_xmldoc_build_description("function", acf->name, ast_module_name(acf->mod)); ast_string_field_set(acf, desc, tmpxml); ast_free(tmpxml); /* load syntax */ tmpxml = ast_xmldoc_build_syntax("function", acf->name, ast_module_name(acf->mod)); ast_string_field_set(acf, syntax, tmpxml); ast_free(tmpxml); /* load arguments */ tmpxml = ast_xmldoc_build_arguments("function", acf->name, ast_module_name(acf->mod)); ast_string_field_set(acf, arguments, tmpxml); ast_free(tmpxml); /* load seealso */ tmpxml = ast_xmldoc_build_seealso("function", acf->name, ast_module_name(acf->mod)); ast_string_field_set(acf, seealso, tmpxml); ast_free(tmpxml); acf->docsrc = AST_XML_DOC; #endif return 0; } int __ast_custom_function_register(struct ast_custom_function *acf, struct ast_module *mod) { struct ast_custom_function *cur; char tmps[80]; if (!acf) { return -1; } acf->mod = mod; #ifdef AST_XML_DOCS acf->docsrc = AST_STATIC_DOC; #endif if (acf_retrieve_docs(acf)) { return -1; } AST_RWLIST_WRLOCK(&acf_root); AST_RWLIST_TRAVERSE(&acf_root, cur, acflist) { if (!strcmp(acf->name, cur->name)) { ast_log(LOG_ERROR, "Function %s already registered.\n", acf->name); AST_RWLIST_UNLOCK(&acf_root); return -1; } } /* Store in alphabetical order */ AST_RWLIST_TRAVERSE_SAFE_BEGIN(&acf_root, cur, acflist) { if (strcasecmp(acf->name, cur->name) < 0) { AST_RWLIST_INSERT_BEFORE_CURRENT(acf, acflist); break; } } AST_RWLIST_TRAVERSE_SAFE_END; if (!cur) { AST_RWLIST_INSERT_TAIL(&acf_root, acf, acflist); } AST_RWLIST_UNLOCK(&acf_root); ast_verb(2, "Registered custom function '%s'\n", term_color(tmps, acf->name, COLOR_BRCYAN, 0, sizeof(tmps))); return 0; } /*! \brief return a pointer to the arguments of the function, * and terminates the function name with '\\0' */ static char *func_args(char *function) { char *args = strchr(function, '('); if (!args) { ast_log(LOG_WARNING, "Function '%s' doesn't contain parentheses. Assuming null argument.\n", function); } else { char *p; *args++ = '\0'; if ((p = strrchr(args, ')'))) { *p = '\0'; } else { ast_log(LOG_WARNING, "Can't find trailing parenthesis for function '%s(%s'?\n", function, args); } } return args; } int ast_func_read(struct ast_channel *chan, const char *function, char *workspace, size_t len) { char *copy = ast_strdupa(function); char *args = func_args(copy); struct ast_custom_function *acfptr = ast_custom_function_find(copy); int res; struct ast_module_user *u = NULL; if (acfptr == NULL) { ast_log(LOG_ERROR, "Function %s not registered\n", copy); } else if (!acfptr->read && !acfptr->read2) { ast_log(LOG_ERROR, "Function %s cannot be read\n", copy); } else if (acfptr->read) { if (acfptr->mod) { u = __ast_module_user_add(acfptr->mod, chan); } res = acfptr->read(chan, copy, args, workspace, len); if (acfptr->mod && u) { __ast_module_user_remove(acfptr->mod, u); } return res; } else { struct ast_str *str = ast_str_create(16); if (acfptr->mod) { u = __ast_module_user_add(acfptr->mod, chan); } res = acfptr->read2(chan, copy, args, &str, 0); if (acfptr->mod && u) { __ast_module_user_remove(acfptr->mod, u); } ast_copy_string(workspace, ast_str_buffer(str), len > ast_str_size(str) ? ast_str_size(str) : len); ast_free(str); return res; } return -1; } int ast_func_read2(struct ast_channel *chan, const char *function, struct ast_str **str, ssize_t maxlen) { char *copy = ast_strdupa(function); char *args = func_args(copy); struct ast_custom_function *acfptr = ast_custom_function_find(copy); int res; struct ast_module_user *u = NULL; if (acfptr == NULL) { ast_log(LOG_ERROR, "Function %s not registered\n", copy); } else if (!acfptr->read && !acfptr->read2) { ast_log(LOG_ERROR, "Function %s cannot be read\n", copy); } else { if (acfptr->mod) { u = __ast_module_user_add(acfptr->mod, chan); } ast_str_reset(*str); if (acfptr->read2) { /* ast_str enabled */ res = acfptr->read2(chan, copy, args, str, maxlen); } else { /* Legacy function pointer, allocate buffer for result */ int maxsize = ast_str_size(*str); if (maxlen > -1) { if (maxlen == 0) { if (acfptr->read_max) { maxsize = acfptr->read_max; } else { maxsize = VAR_BUF_SIZE; } } else { maxsize = maxlen; } ast_str_make_space(str, maxsize); } res = acfptr->read(chan, copy, args, ast_str_buffer(*str), maxsize); } if (acfptr->mod && u) { __ast_module_user_remove(acfptr->mod, u); } return res; } return -1; } int ast_func_write(struct ast_channel *chan, const char *function, const char *value) { char *copy = ast_strdupa(function); char *args = func_args(copy); struct ast_custom_function *acfptr = ast_custom_function_find(copy); if (acfptr == NULL) ast_log(LOG_ERROR, "Function %s not registered\n", copy); else if (!acfptr->write) ast_log(LOG_ERROR, "Function %s cannot be written to\n", copy); else { int res; struct ast_module_user *u = NULL; if (acfptr->mod) u = __ast_module_user_add(acfptr->mod, chan); res = acfptr->write(chan, copy, args, value); if (acfptr->mod && u) __ast_module_user_remove(acfptr->mod, u); return res; } return -1; } void ast_str_substitute_variables_full(struct ast_str **buf, ssize_t maxlen, struct ast_channel *c, struct varshead *headp, const char *templ, size_t *used) { /* Substitutes variables into buf, based on string templ */ char *cp4 = NULL; const char *tmp, *whereweare; int orig_size = 0; int offset, offset2, isfunction; const char *nextvar, *nextexp, *nextthing; const char *vars, *vare; char *finalvars; int pos, brackets, needsub, len; struct ast_str *substr1 = ast_str_create(16), *substr2 = NULL, *substr3 = ast_str_create(16); ast_str_reset(*buf); whereweare = tmp = templ; while (!ast_strlen_zero(whereweare)) { /* reset our buffer */ ast_str_reset(substr3); /* Assume we're copying the whole remaining string */ pos = strlen(whereweare); nextvar = NULL; nextexp = NULL; nextthing = strchr(whereweare, '$'); if (nextthing) { switch (nextthing[1]) { case '{': nextvar = nextthing; pos = nextvar - whereweare; break; case '[': nextexp = nextthing; pos = nextexp - whereweare; break; default: pos = 1; } } if (pos) { /* Copy that many bytes */ ast_str_append_substr(buf, maxlen, whereweare, pos); templ += pos; whereweare += pos; } if (nextvar) { /* We have a variable. Find the start and end, and determine if we are going to have to recursively call ourselves on the contents */ vars = vare = nextvar + 2; brackets = 1; needsub = 0; /* Find the end of it */ while (brackets && *vare) { if ((vare[0] == '$') && (vare[1] == '{')) { needsub++; } else if (vare[0] == '{') { brackets++; } else if (vare[0] == '}') { brackets--; } else if ((vare[0] == '$') && (vare[1] == '[')) needsub++; vare++; } if (brackets) ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n"); len = vare - vars - 1; /* Skip totally over variable string */ whereweare += (len + 3); /* Store variable name (and truncate) */ ast_str_set_substr(&substr1, 0, vars, len); ast_debug(5, "Evaluating '%s' (from '%s' len %d)\n", ast_str_buffer(substr1), vars, len); /* Substitute if necessary */ if (needsub) { size_t used; if (!substr2) { substr2 = ast_str_create(16); } ast_str_substitute_variables_full(&substr2, 0, c, headp, ast_str_buffer(substr1), &used); finalvars = ast_str_buffer(substr2); } else { finalvars = ast_str_buffer(substr1); } parse_variable_name(finalvars, &offset, &offset2, &isfunction); if (isfunction) { /* Evaluate function */ if (c || !headp) { cp4 = ast_func_read2(c, finalvars, &substr3, 0) ? NULL : ast_str_buffer(substr3); } else { struct varshead old; struct ast_channel *bogus = ast_dummy_channel_alloc(); if (bogus) { memcpy(&old, &bogus->varshead, sizeof(old)); memcpy(&bogus->varshead, headp, sizeof(bogus->varshead)); cp4 = ast_func_read2(c, finalvars, &substr3, 0) ? NULL : ast_str_buffer(substr3); /* Don't deallocate the varshead that was passed in */ memcpy(&bogus->varshead, &old, sizeof(bogus->varshead)); ast_channel_unref(bogus); } else { ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n"); } } ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)"); } else { /* Retrieve variable value */ ast_str_retrieve_variable(&substr3, 0, c, headp, finalvars); cp4 = ast_str_buffer(substr3); } if (cp4) { ast_str_substring(substr3, offset, offset2); ast_str_append(buf, maxlen, "%s", ast_str_buffer(substr3)); } } else if (nextexp) { /* We have an expression. Find the start and end, and determine if we are going to have to recursively call ourselves on the contents */ vars = vare = nextexp + 2; brackets = 1; needsub = 0; /* Find the end of it */ while (brackets && *vare) { if ((vare[0] == '$') && (vare[1] == '[')) { needsub++; brackets++; vare++; } else if (vare[0] == '[') { brackets++; } else if (vare[0] == ']') { brackets--; } else if ((vare[0] == '$') && (vare[1] == '{')) { needsub++; vare++; } vare++; } if (brackets) ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n"); len = vare - vars - 1; /* Skip totally over expression */ whereweare += (len + 3); /* Store variable name (and truncate) */ ast_str_set_substr(&substr1, 0, vars, len); /* Substitute if necessary */ if (needsub) { size_t used; if (!substr2) { substr2 = ast_str_create(16); } ast_str_substitute_variables_full(&substr2, 0, c, headp, ast_str_buffer(substr1), &used); finalvars = ast_str_buffer(substr2); } else { finalvars = ast_str_buffer(substr1); } if (ast_str_expr(&substr3, 0, c, finalvars)) { ast_debug(2, "Expression result is '%s'\n", ast_str_buffer(substr3)); } ast_str_append(buf, maxlen, "%s", ast_str_buffer(substr3)); } } *used = ast_str_strlen(*buf) - orig_size; ast_free(substr1); ast_free(substr2); ast_free(substr3); } void ast_str_substitute_variables(struct ast_str **buf, ssize_t maxlen, struct ast_channel *chan, const char *templ) { size_t used; ast_str_substitute_variables_full(buf, maxlen, chan, NULL, templ, &used); } void ast_str_substitute_variables_varshead(struct ast_str **buf, ssize_t maxlen, struct varshead *headp, const char *templ) { size_t used; ast_str_substitute_variables_full(buf, maxlen, NULL, headp, templ, &used); } void pbx_substitute_variables_helper_full(struct ast_channel *c, struct varshead *headp, const char *cp1, char *cp2, int count, size_t *used) { /* Substitutes variables into cp2, based on string cp1, cp2 NO LONGER NEEDS TO BE ZEROED OUT!!!! */ char *cp4 = NULL; const char *tmp, *whereweare, *orig_cp2 = cp2; int length, offset, offset2, isfunction; char *workspace = NULL; char *ltmp = NULL, *var = NULL; char *nextvar, *nextexp, *nextthing; char *vars, *vare; int pos, brackets, needsub, len; *cp2 = 0; /* just in case nothing ends up there */ whereweare=tmp=cp1; while (!ast_strlen_zero(whereweare) && count) { /* Assume we're copying the whole remaining string */ pos = strlen(whereweare); nextvar = NULL; nextexp = NULL; nextthing = strchr(whereweare, '$'); if (nextthing) { switch (nextthing[1]) { case '{': nextvar = nextthing; pos = nextvar - whereweare; break; case '[': nextexp = nextthing; pos = nextexp - whereweare; break; default: pos = 1; } } if (pos) { /* Can't copy more than 'count' bytes */ if (pos > count) pos = count; /* Copy that many bytes */ memcpy(cp2, whereweare, pos); count -= pos; cp2 += pos; whereweare += pos; *cp2 = 0; } if (nextvar) { /* We have a variable. Find the start and end, and determine if we are going to have to recursively call ourselves on the contents */ vars = vare = nextvar + 2; brackets = 1; needsub = 0; /* Find the end of it */ while (brackets && *vare) { if ((vare[0] == '$') && (vare[1] == '{')) { needsub++; } else if (vare[0] == '{') { brackets++; } else if (vare[0] == '}') { brackets--; } else if ((vare[0] == '$') && (vare[1] == '[')) needsub++; vare++; } if (brackets) ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n"); len = vare - vars - 1; /* Skip totally over variable string */ whereweare += (len + 3); if (!var) var = ast_alloca(VAR_BUF_SIZE); /* Store variable name (and truncate) */ ast_copy_string(var, vars, len + 1); /* Substitute if necessary */ if (needsub) { size_t used; if (!ltmp) ltmp = ast_alloca(VAR_BUF_SIZE); pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1, &used); vars = ltmp; } else { vars = var; } if (!workspace) workspace = ast_alloca(VAR_BUF_SIZE); workspace[0] = '\0'; parse_variable_name(vars, &offset, &offset2, &isfunction); if (isfunction) { /* Evaluate function */ if (c || !headp) cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace; else { struct varshead old; struct ast_channel *c = ast_dummy_channel_alloc(); if (c) { memcpy(&old, &c->varshead, sizeof(old)); memcpy(&c->varshead, headp, sizeof(c->varshead)); cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace; /* Don't deallocate the varshead that was passed in */ memcpy(&c->varshead, &old, sizeof(c->varshead)); c = ast_channel_unref(c); } else { ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n"); } } ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)"); } else { /* Retrieve variable value */ pbx_retrieve_variable(c, vars, &cp4, workspace, VAR_BUF_SIZE, headp); } if (cp4) { cp4 = substring(cp4, offset, offset2, workspace, VAR_BUF_SIZE); length = strlen(cp4); if (length > count) length = count; memcpy(cp2, cp4, length); count -= length; cp2 += length; *cp2 = 0; } } else if (nextexp) { /* We have an expression. Find the start and end, and determine if we are going to have to recursively call ourselves on the contents */ vars = vare = nextexp + 2; brackets = 1; needsub = 0; /* Find the end of it */ while (brackets && *vare) { if ((vare[0] == '$') && (vare[1] == '[')) { needsub++; brackets++; vare++; } else if (vare[0] == '[') { brackets++; } else if (vare[0] == ']') { brackets--; } else if ((vare[0] == '$') && (vare[1] == '{')) { needsub++; vare++; } vare++; } if (brackets) ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n"); len = vare - vars - 1; /* Skip totally over expression */ whereweare += (len + 3); if (!var) var = ast_alloca(VAR_BUF_SIZE); /* Store variable name (and truncate) */ ast_copy_string(var, vars, len + 1); /* Substitute if necessary */ if (needsub) { size_t used; if (!ltmp) ltmp = ast_alloca(VAR_BUF_SIZE); pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1, &used); vars = ltmp; } else { vars = var; } length = ast_expr(vars, cp2, count, c); if (length) { ast_debug(1, "Expression result is '%s'\n", cp2); count -= length; cp2 += length; *cp2 = 0; } } } *used = cp2 - orig_cp2; } void pbx_substitute_variables_helper(struct ast_channel *c, const char *cp1, char *cp2, int count) { size_t used; pbx_substitute_variables_helper_full(c, (c) ? &c->varshead : NULL, cp1, cp2, count, &used); } void pbx_substitute_variables_varshead(struct varshead *headp, const char *cp1, char *cp2, int count) { size_t used; pbx_substitute_variables_helper_full(NULL, headp, cp1, cp2, count, &used); } static void pbx_substitute_variables(char *passdata, int datalen, struct ast_channel *c, struct ast_exten *e) { const char *tmp; /* Nothing more to do */ if (!e->data) { *passdata = '\0'; return; } /* No variables or expressions in e->data, so why scan it? */ if ((!(tmp = strchr(e->data, '$'))) || (!strstr(tmp, "${") && !strstr(tmp, "$["))) { ast_copy_string(passdata, e->data, datalen); return; } pbx_substitute_variables_helper(c, e->data, passdata, datalen - 1); } /*! * \brief The return value depends on the action: * * E_MATCH, E_CANMATCH, E_MATCHMORE require a real match, * and return 0 on failure, -1 on match; * E_FINDLABEL maps the label to a priority, and returns * the priority on success, ... XXX * E_SPAWN, spawn an application, * * \retval 0 on success. * \retval -1 on failure. * * \note The channel is auto-serviced in this function, because doing an extension * match may block for a long time. For example, if the lookup has to use a network * dialplan switch, such as DUNDi or IAX2, it may take a while. However, the channel * auto-service code will queue up any important signalling frames to be processed * after this is done. */ static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con, const char *context, const char *exten, int priority, const char *label, const char *callerid, enum ext_match_t action, int *found, int combined_find_spawn) { struct ast_exten *e; struct ast_app *app; int res; struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */ char passdata[EXT_DATA_SIZE]; int matching_action = (action == E_MATCH || action == E_CANMATCH || action == E_MATCHMORE); ast_rdlock_contexts(); if (found) *found = 0; e = pbx_find_extension(c, con, &q, context, exten, priority, label, callerid, action); if (e) { if (found) *found = 1; if (matching_action) { ast_unlock_contexts(); return -1; /* success, we found it */ } else if (action == E_FINDLABEL) { /* map the label to a priority */ res = e->priority; ast_unlock_contexts(); return res; /* the priority we were looking for */ } else { /* spawn */ if (!e->cached_app) e->cached_app = pbx_findapp(e->app); app = e->cached_app; ast_unlock_contexts(); if (!app) { ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority); return -1; } if (c->context != context) ast_copy_string(c->context, context, sizeof(c->context)); if (c->exten != exten) ast_copy_string(c->exten, exten, sizeof(c->exten)); c->priority = priority; pbx_substitute_variables(passdata, sizeof(passdata), c, e); #ifdef CHANNEL_TRACE ast_channel_trace_update(c); #endif ast_debug(1, "Launching '%s'\n", app->name); if (VERBOSITY_ATLEAST(3)) { char tmp[80], tmp2[80], tmp3[EXT_DATA_SIZE]; ast_verb(3, "Executing [%s@%s:%d] %s(\"%s\", \"%s\") %s\n", exten, context, priority, term_color(tmp, app->name, COLOR_BRCYAN, 0, sizeof(tmp)), term_color(tmp2, c->name, COLOR_BRMAGENTA, 0, sizeof(tmp2)), term_color(tmp3, passdata, COLOR_BRMAGENTA, 0, sizeof(tmp3)), "in new stack"); } manager_event(EVENT_FLAG_DIALPLAN, "Newexten", "Channel: %s\r\n" "Context: %s\r\n" "Extension: %s\r\n" "Priority: %d\r\n" "Application: %s\r\n" "AppData: %s\r\n" "Uniqueid: %s\r\n", c->name, c->context, c->exten, c->priority, app->name, passdata, c->uniqueid); return pbx_exec(c, app, passdata); /* 0 on success, -1 on failure */ } } else if (q.swo) { /* not found here, but in another switch */ if (found) *found = 1; ast_unlock_contexts(); if (matching_action) { return -1; } else { if (!q.swo->exec) { ast_log(LOG_WARNING, "No execution engine for switch %s\n", q.swo->name); res = -1; } return q.swo->exec(c, q.foundcontext ? q.foundcontext : context, exten, priority, callerid, q.data); } } else { /* not found anywhere, see what happened */ ast_unlock_contexts(); /* Using S_OR here because Solaris doesn't like NULL being passed to ast_log */ switch (q.status) { case STATUS_NO_CONTEXT: if (!matching_action && !combined_find_spawn) ast_log(LOG_NOTICE, "Cannot find extension context '%s'\n", S_OR(context, "")); break; case STATUS_NO_EXTENSION: if (!matching_action && !combined_find_spawn) ast_log(LOG_NOTICE, "Cannot find extension '%s' in context '%s'\n", exten, S_OR(context, "")); break; case STATUS_NO_PRIORITY: if (!matching_action && !combined_find_spawn) ast_log(LOG_NOTICE, "No such priority %d in extension '%s' in context '%s'\n", priority, exten, S_OR(context, "")); break; case STATUS_NO_LABEL: if (context && !combined_find_spawn) ast_log(LOG_NOTICE, "No such label '%s' in extension '%s' in context '%s'\n", label, exten, S_OR(context, "")); break; default: ast_debug(1, "Shouldn't happen!\n"); } return (matching_action) ? 0 : -1; } } /*! \brief Find hint for given extension in context */ static struct ast_exten *ast_hint_extension_nolock(struct ast_channel *c, const char *context, const char *exten) { struct pbx_find_info q = { .stacklen = 0 }; /* the rest is set in pbx_find_context */ return pbx_find_extension(c, NULL, &q, context, exten, PRIORITY_HINT, NULL, "", E_MATCH); } static struct ast_exten *ast_hint_extension(struct ast_channel *c, const char *context, const char *exten) { struct ast_exten *e; ast_rdlock_contexts(); e = ast_hint_extension_nolock(c, context, exten); ast_unlock_contexts(); return e; } enum ast_extension_states ast_devstate_to_extenstate(enum ast_device_state devstate) { switch (devstate) { case AST_DEVICE_ONHOLD: return AST_EXTENSION_ONHOLD; case AST_DEVICE_BUSY: return AST_EXTENSION_BUSY; case AST_DEVICE_UNKNOWN: return AST_EXTENSION_NOT_INUSE; case AST_DEVICE_UNAVAILABLE: case AST_DEVICE_INVALID: return AST_EXTENSION_UNAVAILABLE; case AST_DEVICE_RINGINUSE: return (AST_EXTENSION_INUSE | AST_EXTENSION_RINGING); case AST_DEVICE_RINGING: return AST_EXTENSION_RINGING; case AST_DEVICE_INUSE: return AST_EXTENSION_INUSE; case AST_DEVICE_NOT_INUSE: return AST_EXTENSION_NOT_INUSE; case AST_DEVICE_TOTAL: /* not a device state, included for completeness */ break; } return AST_EXTENSION_NOT_INUSE; } static int ast_extension_state3(struct ast_str *hint_app) { char *cur; char *rest; struct ast_devstate_aggregate agg; /* One or more devices separated with a & character */ rest = ast_str_buffer(hint_app); ast_devstate_aggregate_init(&agg); while ((cur = strsep(&rest, "&"))) { ast_devstate_aggregate_add(&agg, ast_device_state(cur)); } return ast_devstate_to_extenstate(ast_devstate_aggregate_result(&agg)); } /*! \brief Check state of extension by using hints */ static int ast_extension_state2(struct ast_exten *e) { struct ast_str *hint_app = ast_str_thread_get(&extensionstate_buf, 32); if (!e || !hint_app) { return -1; } ast_str_set(&hint_app, 0, "%s", ast_get_extension_app(e)); return ast_extension_state3(hint_app); } /*! \brief Return extension_state as string */ const char *ast_extension_state2str(int extension_state) { int i; for (i = 0; (i < ARRAY_LEN(extension_states)); i++) { if (extension_states[i].extension_state == extension_state) return extension_states[i].text; } return "Unknown"; } /*! \brief Check extension state for an extension by using hint */ int ast_extension_state(struct ast_channel *c, const char *context, const char *exten) { struct ast_exten *e; if (!(e = ast_hint_extension(c, context, exten))) { /* Do we have a hint for this extension ? */ return -1; /* No hint, return -1 */ } if (e->exten[0] == '_') { /* Create this hint on-the-fly */ ast_add_extension(e->parent->name, 0, exten, e->priority, e->label, e->matchcid ? e->cidmatch : NULL, e->app, ast_strdup(e->data), ast_free_ptr, e->registrar); if (!(e = ast_hint_extension(c, context, exten))) { /* Improbable, but not impossible */ return -1; } } return ast_extension_state2(e); /* Check all devices in the hint */ } static int handle_statechange(void *datap) { struct ast_hint *hint; struct ast_str *hint_app; struct statechange *sc = datap; struct ao2_iterator i; struct ao2_iterator cb_iter; char context_name[AST_MAX_CONTEXT]; char exten_name[AST_MAX_EXTENSION]; hint_app = ast_str_create(1024); if (!hint_app) { ast_free(sc); return -1; } ast_mutex_lock(&context_merge_lock);/* Hold off ast_merge_contexts_and_delete */ i = ao2_iterator_init(hints, 0); for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) { struct ast_state_cb *state_cb; char *cur, *parse; int state; ao2_lock(hint); if (!hint->exten) { /* The extension has already been destroyed */ ao2_unlock(hint); continue; } /* Does this hint monitor the device that changed state? */ ast_str_set(&hint_app, 0, "%s", ast_get_extension_app(hint->exten)); parse = ast_str_buffer(hint_app); while ((cur = strsep(&parse, "&"))) { if (!strcasecmp(cur, sc->dev)) { /* The hint monitors the device. */ break; } } if (!cur) { /* The hint does not monitor the device. */ ao2_unlock(hint); continue; } /* * Save off strings in case the hint extension gets destroyed * while we are notifying the watchers. */ ast_copy_string(context_name, ast_get_context_name(ast_get_extension_context(hint->exten)), sizeof(context_name)); ast_copy_string(exten_name, ast_get_extension_name(hint->exten), sizeof(exten_name)); ast_str_set(&hint_app, 0, "%s", ast_get_extension_app(hint->exten)); ao2_unlock(hint); /* * Get device state for this hint. * * NOTE: We cannot hold any locks while determining the hint * device state or notifying the watchers without causing a * deadlock. (conlock, hints, and hint) */ state = ast_extension_state3(hint_app); if (state == hint->laststate) { continue; } /* Device state changed since last check - notify the watchers. */ hint->laststate = state; /* record we saw the change */ /* For general callbacks */ cb_iter = ao2_iterator_init(statecbs, 0); for (; (state_cb = ao2_iterator_next(&cb_iter)); ao2_ref(state_cb, -1)) { state_cb->change_cb(context_name, exten_name, state, state_cb->data); } ao2_iterator_destroy(&cb_iter); /* For extension callbacks */ cb_iter = ao2_iterator_init(hint->callbacks, 0); for (; (state_cb = ao2_iterator_next(&cb_iter)); ao2_ref(state_cb, -1)) { state_cb->change_cb(context_name, exten_name, state, state_cb->data); } ao2_iterator_destroy(&cb_iter); } ao2_iterator_destroy(&i); ast_mutex_unlock(&context_merge_lock); ast_free(hint_app); ast_free(sc); return 0; } /*! * \internal * \brief Destroy the given state callback object. * * \param doomed State callback to destroy. * * \return Nothing */ static void destroy_state_cb(void *doomed) { struct ast_state_cb *state_cb = doomed; if (state_cb->destroy_cb) { state_cb->destroy_cb(state_cb->id, state_cb->data); } } /*! \brief Add watcher for extension states with destructor */ int ast_extension_state_add_destroy(const char *context, const char *exten, ast_state_cb_type change_cb, ast_state_cb_destroy_type destroy_cb, void *data) { struct ast_hint *hint; struct ast_state_cb *state_cb; struct ast_exten *e; int id; /* If there's no context and extension: add callback to statecbs list */ if (!context && !exten) { /* Prevent multiple adds from adding the same change_cb at the same time. */ ao2_lock(statecbs); /* Remove any existing change_cb. */ ao2_find(statecbs, change_cb, OBJ_UNLINK | OBJ_NODATA); /* Now insert the change_cb */ if (!(state_cb = ao2_alloc(sizeof(*state_cb), destroy_state_cb))) { ao2_unlock(statecbs); return -1; } state_cb->id = 0; state_cb->change_cb = change_cb; state_cb->destroy_cb = destroy_cb; state_cb->data = data; ao2_link(statecbs, state_cb); ao2_ref(state_cb, -1); ao2_unlock(statecbs); return 0; } if (!context || !exten) return -1; /* This callback type is for only one hint, so get the hint */ e = ast_hint_extension(NULL, context, exten); if (!e) { return -1; } /* If this is a pattern, dynamically create a new extension for this * particular match. Note that this will only happen once for each * individual extension, because the pattern will no longer match first. */ if (e->exten[0] == '_') { ast_add_extension(e->parent->name, 0, exten, e->priority, e->label, e->matchcid ? e->cidmatch : NULL, e->app, ast_strdup(e->data), ast_free_ptr, e->registrar); e = ast_hint_extension(NULL, context, exten); if (!e || e->exten[0] == '_') { return -1; } } /* Find the hint in the hints container */ ao2_lock(hints);/* Locked to hold off ast_merge_contexts_and_delete */ hint = ao2_find(hints, e, 0); if (!hint) { ao2_unlock(hints); return -1; } /* Now insert the callback in the callback list */ if (!(state_cb = ao2_alloc(sizeof(*state_cb), destroy_state_cb))) { ao2_ref(hint, -1); ao2_unlock(hints); return -1; } do { id = stateid++; /* Unique ID for this callback */ /* Do not allow id to ever be -1 or 0. */ } while (id == -1 || id == 0); state_cb->id = id; state_cb->change_cb = change_cb; /* Pointer to callback routine */ state_cb->destroy_cb = destroy_cb; state_cb->data = data; /* Data for the callback */ ao2_link(hint->callbacks, state_cb); ao2_ref(state_cb, -1); ao2_ref(hint, -1); ao2_unlock(hints); return id; } /*! \brief Add watcher for extension states */ int ast_extension_state_add(const char *context, const char *exten, ast_state_cb_type change_cb, void *data) { return ast_extension_state_add_destroy(context, exten, change_cb, NULL, data); } /*! \brief Remove a watcher from the callback list */ static int find_hint_by_cb_id(void *obj, void *arg, int flags) { struct ast_state_cb *state_cb; const struct ast_hint *hint = obj; int *id = arg; if ((state_cb = ao2_find(hint->callbacks, id, 0))) { ao2_ref(state_cb, -1); return CMP_MATCH | CMP_STOP; } return 0; } /*! \brief ast_extension_state_del: Remove a watcher from the callback list */ int ast_extension_state_del(int id, ast_state_cb_type change_cb) { struct ast_state_cb *p_cur; int ret = -1; if (!id) { /* id == 0 is a callback without extension */ if (!change_cb) { return ret; } p_cur = ao2_find(statecbs, change_cb, OBJ_UNLINK); if (p_cur) { ret = 0; ao2_ref(p_cur, -1); } } else { /* callback with extension, find the callback based on ID */ struct ast_hint *hint; ao2_lock(hints);/* Locked to hold off ast_merge_contexts_and_delete */ hint = ao2_callback(hints, 0, find_hint_by_cb_id, &id); if (hint) { p_cur = ao2_find(hint->callbacks, &id, OBJ_UNLINK); if (p_cur) { ret = 0; ao2_ref(p_cur, -1); } ao2_ref(hint, -1); } ao2_unlock(hints); } return ret; } static int hint_id_cmp(void *obj, void *arg, int flags) { const struct ast_state_cb *cb = obj; int *id = arg; return (cb->id == *id) ? CMP_MATCH | CMP_STOP : 0; } /*! * \internal * \brief Destroy the given hint object. * * \param obj Hint to destroy. * * \return Nothing */ static void destroy_hint(void *obj) { struct ast_hint *hint = obj; if (hint->callbacks) { struct ast_state_cb *state_cb; const char *context_name; const char *exten_name; if (hint->exten) { context_name = ast_get_context_name(ast_get_extension_context(hint->exten)); exten_name = ast_get_extension_name(hint->exten); hint->exten = NULL; } else { /* The extension has already been destroyed */ context_name = hint->context_name; exten_name = hint->exten_name; } while ((state_cb = ao2_callback(hint->callbacks, OBJ_UNLINK, NULL, NULL))) { /* Notify with -1 and remove all callbacks */ /* NOTE: The casts will not be needed for v1.10 and later */ state_cb->change_cb((char *) context_name, (char *) exten_name, AST_EXTENSION_DEACTIVATED, state_cb->data); ao2_ref(state_cb, -1); } ao2_ref(hint->callbacks, -1); } } /*! \brief Remove hint from extension */ static int ast_remove_hint(struct ast_exten *e) { /* Cleanup the Notifys if hint is removed */ struct ast_hint *hint; if (!e) { return -1; } hint = ao2_find(hints, e, OBJ_UNLINK); if (!hint) { return -1; } /* * The extension is being destroyed so we must save some * information to notify that the extension is deactivated. */ ao2_lock(hint); ast_copy_string(hint->context_name, ast_get_context_name(ast_get_extension_context(hint->exten)), sizeof(hint->context_name)); ast_copy_string(hint->exten_name, ast_get_extension_name(hint->exten), sizeof(hint->exten_name)); hint->exten = NULL; ao2_unlock(hint); ao2_ref(hint, -1); return 0; } /*! \brief Add hint to hint list, check initial extension state */ static int ast_add_hint(struct ast_exten *e) { struct ast_hint *hint_new; struct ast_hint *hint_found; if (!e) { return -1; } /* * We must create the hint we wish to add before determining if * it is already in the hints container to avoid possible * deadlock when getting the current extension state. */ hint_new = ao2_alloc(sizeof(*hint_new), destroy_hint); if (!hint_new) { return -1; } /* Initialize new hint. */ hint_new->callbacks = ao2_container_alloc(1, NULL, hint_id_cmp); if (!hint_new->callbacks) { ao2_ref(hint_new, -1); return -1; } hint_new->exten = e; hint_new->laststate = ast_extension_state2(e); /* Prevent multiple add hints from adding the same hint at the same time. */ ao2_lock(hints); /* Search if hint exists, do nothing */ hint_found = ao2_find(hints, e, 0); if (hint_found) { ao2_ref(hint_found, -1); ao2_unlock(hints); ao2_ref(hint_new, -1); ast_debug(2, "HINTS: Not re-adding existing hint %s: %s\n", ast_get_extension_name(e), ast_get_extension_app(e)); return -1; } /* Add new hint to the hints container */ ast_debug(2, "HINTS: Adding hint %s: %s\n", ast_get_extension_name(e), ast_get_extension_app(e)); ao2_link(hints, hint_new); ao2_unlock(hints); ao2_ref(hint_new, -1); return 0; } /*! \brief Change hint for an extension */ static int ast_change_hint(struct ast_exten *oe, struct ast_exten *ne) { struct ast_hint *hint; if (!oe || !ne) { return -1; } ao2_lock(hints);/* Locked to hold off others while we move the hint around. */ /* * Unlink the hint from the hints container as the extension * name (which is the hash value) could change. */ hint = ao2_find(hints, oe, OBJ_UNLINK); if (!hint) { ao2_unlock(hints); return -1; } /* Update the hint and put it back in the hints container. */ ao2_lock(hint); hint->exten = ne; ao2_unlock(hint); ao2_link(hints, hint); ao2_unlock(hints); ao2_ref(hint, -1); return 0; } /*! \brief Get hint for channel */ int ast_get_hint(char *hint, int hintsize, char *name, int namesize, struct ast_channel *c, const char *context, const char *exten) { struct ast_exten *e = ast_hint_extension(c, context, exten); if (e) { if (hint) ast_copy_string(hint, ast_get_extension_app(e), hintsize); if (name) { const char *tmp = ast_get_extension_app_data(e); if (tmp) ast_copy_string(name, tmp, namesize); } return -1; } return 0; } /*! \brief Get hint for channel */ int ast_str_get_hint(struct ast_str **hint, ssize_t hintsize, struct ast_str **name, ssize_t namesize, struct ast_channel *c, const char *context, const char *exten) { struct ast_exten *e = ast_hint_extension(c, context, exten); if (!e) { return 0; } if (hint) { ast_str_set(hint, hintsize, "%s", ast_get_extension_app(e)); } if (name) { const char *tmp = ast_get_extension_app_data(e); if (tmp) { ast_str_set(name, namesize, "%s", tmp); } } return -1; } int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid) { return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCH, 0, 0); } int ast_findlabel_extension(struct ast_channel *c, const char *context, const char *exten, const char *label, const char *callerid) { return pbx_extension_helper(c, NULL, context, exten, 0, label, callerid, E_FINDLABEL, 0, 0); } int ast_findlabel_extension2(struct ast_channel *c, struct ast_context *con, const char *exten, const char *label, const char *callerid) { return pbx_extension_helper(c, con, NULL, exten, 0, label, callerid, E_FINDLABEL, 0, 0); } int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid) { return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_CANMATCH, 0, 0); } int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid) { return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCHMORE, 0, 0); } int ast_spawn_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid, int *found, int combined_find_spawn) { return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_SPAWN, found, combined_find_spawn); } /*! helper function to set extension and priority */ static void set_ext_pri(struct ast_channel *c, const char *exten, int pri) { ast_channel_lock(c); ast_copy_string(c->exten, exten, sizeof(c->exten)); c->priority = pri; ast_channel_unlock(c); } /*! * \brief collect digits from the channel into the buffer. * \param c, buf, buflen, pos * \param waittime is in milliseconds * \retval 0 on timeout or done. * \retval -1 on error. */ static int collect_digits(struct ast_channel *c, int waittime, char *buf, int buflen, int pos) { int digit; buf[pos] = '\0'; /* make sure it is properly terminated */ while (ast_matchmore_extension(c, c->context, buf, 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { /* As long as we're willing to wait, and as long as it's not defined, keep reading digits until we can't possibly get a right answer anymore. */ digit = ast_waitfordigit(c, waittime); if (c->_softhangup & AST_SOFTHANGUP_ASYNCGOTO) { ast_channel_clear_softhangup(c, AST_SOFTHANGUP_ASYNCGOTO); } else { if (!digit) /* No entry */ break; if (digit < 0) /* Error, maybe a hangup */ return -1; if (pos < buflen - 1) { /* XXX maybe error otherwise ? */ buf[pos++] = digit; buf[pos] = '\0'; } waittime = c->pbx->dtimeoutms; } } return 0; } static enum ast_pbx_result __ast_pbx_run(struct ast_channel *c, struct ast_pbx_args *args) { int found = 0; /* set if we find at least one match */ int res = 0; int autoloopflag; int error = 0; /* set an error conditions */ /* A little initial setup here */ if (c->pbx) { ast_log(LOG_WARNING, "%s already has PBX structure??\n", c->name); /* XXX and now what ? */ ast_free(c->pbx); } if (!(c->pbx = ast_calloc(1, sizeof(*c->pbx)))) return -1; /* Set reasonable defaults */ c->pbx->rtimeoutms = 10000; c->pbx->dtimeoutms = 5000; autoloopflag = ast_test_flag(c, AST_FLAG_IN_AUTOLOOP); /* save value to restore at the end */ ast_set_flag(c, AST_FLAG_IN_AUTOLOOP); /* Start by trying whatever the channel is set to */ if (!ast_exists_extension(c, c->context, c->exten, c->priority, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { /* If not successful fall back to 's' */ ast_verb(2, "Starting %s at %s,%s,%d failed so falling back to exten 's'\n", c->name, c->context, c->exten, c->priority); /* XXX the original code used the existing priority in the call to * ast_exists_extension(), and reset it to 1 afterwards. * I believe the correct thing is to set it to 1 immediately. */ set_ext_pri(c, "s", 1); if (!ast_exists_extension(c, c->context, c->exten, c->priority, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { /* JK02: And finally back to default if everything else failed */ ast_verb(2, "Starting %s at %s,%s,%d still failed so falling back to context 'default'\n", c->name, c->context, c->exten, c->priority); ast_copy_string(c->context, "default", sizeof(c->context)); } } ast_channel_lock(c); if (c->cdr) { /* allow CDR variables that have been collected after channel was created to be visible during call */ ast_cdr_update(c); } ast_channel_unlock(c); for (;;) { char dst_exten[256]; /* buffer to accumulate digits */ int pos = 0; /* XXX should check bounds */ int digit = 0; int invalid = 0; int timeout = 0; /* No digits pressed yet */ dst_exten[pos] = '\0'; /* loop on priorities in this context/exten */ while (!(res = ast_spawn_extension(c, c->context, c->exten, c->priority, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL), &found, 1))) { if (!ast_check_hangup(c)) { ++c->priority; continue; } /* Check softhangup flags. */ if (c->_softhangup & AST_SOFTHANGUP_ASYNCGOTO) { ast_channel_clear_softhangup(c, AST_SOFTHANGUP_ASYNCGOTO); continue; } if (c->_softhangup & AST_SOFTHANGUP_TIMEOUT) { if (ast_exists_extension(c, c->context, "T", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { set_ext_pri(c, "T", 1); /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */ memset(&c->whentohangup, 0, sizeof(c->whentohangup)); ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT); continue; } else if (ast_exists_extension(c, c->context, "e", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { raise_exception(c, "ABSOLUTETIMEOUT", 1); /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */ memset(&c->whentohangup, 0, sizeof(c->whentohangup)); ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT); continue; } /* Call timed out with no special extension to jump to. */ error = 1; break; } ast_debug(1, "Extension %s, priority %d returned normally even though call was hung up\n", c->exten, c->priority); error = 1; break; } /* end while - from here on we can use 'break' to go out */ if (found && res) { /* Something bad happened, or a hangup has been requested. */ if (strchr("0123456789ABCDEF*#", res)) { ast_debug(1, "Oooh, got something to jump out with ('%c')!\n", res); pos = 0; dst_exten[pos++] = digit = res; dst_exten[pos] = '\0'; } else if (res == AST_PBX_INCOMPLETE) { ast_debug(1, "Spawn extension (%s,%s,%d) exited INCOMPLETE on '%s'\n", c->context, c->exten, c->priority, c->name); ast_verb(2, "Spawn extension (%s, %s, %d) exited INCOMPLETE on '%s'\n", c->context, c->exten, c->priority, c->name); /* Don't cycle on incomplete - this will happen if the only extension that matches is our "incomplete" extension */ if (!ast_matchmore_extension(c, c->context, c->exten, 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { invalid = 1; } else { ast_copy_string(dst_exten, c->exten, sizeof(dst_exten)); digit = 1; pos = strlen(dst_exten); } } else { ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name); ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name); if ((res == AST_PBX_ERROR) && ast_exists_extension(c, c->context, "e", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { /* if we are already on the 'e' exten, don't jump to it again */ if (!strcmp(c->exten, "e")) { ast_verb(2, "Spawn extension (%s, %s, %d) exited ERROR while already on 'e' exten on '%s'\n", c->context, c->exten, c->priority, c->name); error = 1; } else { raise_exception(c, "ERROR", 1); continue; } } if (c->_softhangup & AST_SOFTHANGUP_ASYNCGOTO) { ast_channel_clear_softhangup(c, AST_SOFTHANGUP_ASYNCGOTO); continue; } if (c->_softhangup & AST_SOFTHANGUP_TIMEOUT) { if (ast_exists_extension(c, c->context, "T", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { set_ext_pri(c, "T", 1); /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */ memset(&c->whentohangup, 0, sizeof(c->whentohangup)); ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT); continue; } else if (ast_exists_extension(c, c->context, "e", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { raise_exception(c, "ABSOLUTETIMEOUT", 1); /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */ memset(&c->whentohangup, 0, sizeof(c->whentohangup)); ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT); continue; } /* Call timed out with no special extension to jump to. */ } ast_channel_lock(c); if (c->cdr) { ast_cdr_update(c); } ast_channel_unlock(c); error = 1; break; } } if (error) break; /*!\note * We get here on a failure of some kind: non-existing extension or * hangup. We have options, here. We can either catch the failure * and continue, or we can drop out entirely. */ if (invalid || (ast_strlen_zero(dst_exten) && !ast_exists_extension(c, c->context, c->exten, 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL)))) { /*!\note * If there is no match at priority 1, it is not a valid extension anymore. * Try to continue at "i" (for invalid) or "e" (for exception) or exit if * neither exist. */ if (ast_exists_extension(c, c->context, "i", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { ast_verb(3, "Sent into invalid extension '%s' in context '%s' on %s\n", c->exten, c->context, c->name); pbx_builtin_setvar_helper(c, "INVALID_EXTEN", c->exten); set_ext_pri(c, "i", 1); } else if (ast_exists_extension(c, c->context, "e", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { raise_exception(c, "INVALID", 1); } else { ast_log(LOG_WARNING, "Channel '%s' sent into invalid extension '%s' in context '%s', but no invalid handler\n", c->name, c->exten, c->context); error = 1; /* we know what to do with it */ break; } } else if (c->_softhangup & AST_SOFTHANGUP_TIMEOUT) { /* If we get this far with AST_SOFTHANGUP_TIMEOUT, then we know that the "T" extension is next. */ ast_channel_clear_softhangup(c, AST_SOFTHANGUP_TIMEOUT); } else { /* keypress received, get more digits for a full extension */ int waittime = 0; if (digit) waittime = c->pbx->dtimeoutms; else if (!autofallthrough) waittime = c->pbx->rtimeoutms; if (!waittime) { const char *status = pbx_builtin_getvar_helper(c, "DIALSTATUS"); if (!status) status = "UNKNOWN"; ast_verb(3, "Auto fallthrough, channel '%s' status is '%s'\n", c->name, status); if (!strcasecmp(status, "CONGESTION")) res = pbx_builtin_congestion(c, "10"); else if (!strcasecmp(status, "CHANUNAVAIL")) res = pbx_builtin_congestion(c, "10"); else if (!strcasecmp(status, "BUSY")) res = pbx_builtin_busy(c, "10"); error = 1; /* XXX disable message */ break; /* exit from the 'for' loop */ } if (collect_digits(c, waittime, dst_exten, sizeof(dst_exten), pos)) break; if (res == AST_PBX_INCOMPLETE && ast_strlen_zero(&dst_exten[pos])) timeout = 1; if (!timeout && ast_exists_extension(c, c->context, dst_exten, 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { /* Prepare the next cycle */ set_ext_pri(c, dst_exten, 1); } else { /* No such extension */ if (!timeout && !ast_strlen_zero(dst_exten)) { /* An invalid extension */ if (ast_exists_extension(c, c->context, "i", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { ast_verb(3, "Invalid extension '%s' in context '%s' on %s\n", dst_exten, c->context, c->name); pbx_builtin_setvar_helper(c, "INVALID_EXTEN", dst_exten); set_ext_pri(c, "i", 1); } else if (ast_exists_extension(c, c->context, "e", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { raise_exception(c, "INVALID", 1); } else { ast_log(LOG_WARNING, "Invalid extension '%s', but no rule 'i' or 'e' in context '%s'\n", dst_exten, c->context); found = 1; /* XXX disable message */ break; } } else { /* A simple timeout */ if (ast_exists_extension(c, c->context, "t", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { ast_verb(3, "Timeout on %s\n", c->name); set_ext_pri(c, "t", 1); } else if (ast_exists_extension(c, c->context, "e", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { raise_exception(c, "RESPONSETIMEOUT", 1); } else { ast_log(LOG_WARNING, "Timeout, but no rule 't' or 'e' in context '%s'\n", c->context); found = 1; /* XXX disable message */ break; } } } ast_channel_lock(c); if (c->cdr) { ast_verb(2, "CDR updated on %s\n",c->name); ast_cdr_update(c); } ast_channel_unlock(c); } } if (!found && !error) { ast_log(LOG_WARNING, "Don't know what to do with '%s'\n", c->name); } if (!args || !args->no_hangup_chan) { ast_softhangup(c, AST_SOFTHANGUP_APPUNLOAD); } if ((!args || !args->no_hangup_chan) && !ast_test_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN) && ast_exists_extension(c, c->context, "h", 1, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL))) { set_ext_pri(c, "h", 1); if (c->cdr && ast_opt_end_cdr_before_h_exten) { ast_cdr_end(c->cdr); } while ((res = ast_spawn_extension(c, c->context, c->exten, c->priority, S_COR(c->caller.id.number.valid, c->caller.id.number.str, NULL), &found, 1)) == 0) { c->priority++; } if (found && res) { /* Something bad happened, or a hangup has been requested. */ ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name); ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name); } } ast_set2_flag(c, autoloopflag, AST_FLAG_IN_AUTOLOOP); ast_clear_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN); /* from one round to the next, make sure this gets cleared */ pbx_destroy(c->pbx); c->pbx = NULL; if (!args || !args->no_hangup_chan) { ast_hangup(c); } return 0; } /*! * \brief Increase call count for channel * \retval 0 on success * \retval non-zero if a configured limit (maxcalls, maxload, minmemfree) was reached */ static int increase_call_count(const struct ast_channel *c) { int failed = 0; double curloadavg; #if defined(HAVE_SYSINFO) long curfreemem; struct sysinfo sys_info; #endif ast_mutex_lock(&maxcalllock); if (option_maxcalls) { if (countcalls >= option_maxcalls) { ast_log(LOG_WARNING, "Maximum call limit of %d calls exceeded by '%s'!\n", option_maxcalls, c->name); failed = -1; } } if (option_maxload) { getloadavg(&curloadavg, 1); if (curloadavg >= option_maxload) { ast_log(LOG_WARNING, "Maximum loadavg limit of %f load exceeded by '%s' (currently %f)!\n", option_maxload, c->name, curloadavg); failed = -1; } } #if defined(HAVE_SYSINFO) if (option_minmemfree) { if (!sysinfo(&sys_info)) { /* make sure that the free system memory is above the configured low watermark * convert the amount of freeram from mem_units to MB */ curfreemem = sys_info.freeram * sys_info.mem_unit; curfreemem /= 1024 * 1024; if (curfreemem < option_minmemfree) { ast_log(LOG_WARNING, "Available system memory (~%ldMB) is below the configured low watermark (%ldMB)\n", curfreemem, option_minmemfree); failed = -1; } } } #endif if (!failed) { countcalls++; totalcalls++; } ast_mutex_unlock(&maxcalllock); return failed; } static void decrease_call_count(void) { ast_mutex_lock(&maxcalllock); if (countcalls > 0) countcalls--; ast_mutex_unlock(&maxcalllock); } static void destroy_exten(struct ast_exten *e) { if (e->priority == PRIORITY_HINT) ast_remove_hint(e); if (e->peer_table) ast_hashtab_destroy(e->peer_table,0); if (e->peer_label_table) ast_hashtab_destroy(e->peer_label_table, 0); if (e->datad) e->datad(e->data); ast_free(e); } static void *pbx_thread(void *data) { /* Oh joyeous kernel, we're a new thread, with nothing to do but answer this channel and get it going. */ /* NOTE: The launcher of this function _MUST_ increment 'countcalls' before invoking the function; it will be decremented when the PBX has finished running on the channel */ struct ast_channel *c = data; __ast_pbx_run(c, NULL); decrease_call_count(); pthread_exit(NULL); return NULL; } enum ast_pbx_result ast_pbx_start(struct ast_channel *c) { pthread_t t; if (!c) { ast_log(LOG_WARNING, "Asked to start thread on NULL channel?\n"); return AST_PBX_FAILED; } if (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) { ast_log(LOG_WARNING, "PBX requires Asterisk to be fully booted\n"); return AST_PBX_FAILED; } if (increase_call_count(c)) return AST_PBX_CALL_LIMIT; /* Start a new thread, and get something handling this channel. */ if (ast_pthread_create_detached(&t, NULL, pbx_thread, c)) { ast_log(LOG_WARNING, "Failed to create new channel thread\n"); decrease_call_count(); return AST_PBX_FAILED; } return AST_PBX_SUCCESS; } enum ast_pbx_result ast_pbx_run_args(struct ast_channel *c, struct ast_pbx_args *args) { enum ast_pbx_result res = AST_PBX_SUCCESS; if (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) { ast_log(LOG_WARNING, "PBX requires Asterisk to be fully booted\n"); return AST_PBX_FAILED; } if (increase_call_count(c)) { return AST_PBX_CALL_LIMIT; } res = __ast_pbx_run(c, args); decrease_call_count(); return res; } enum ast_pbx_result ast_pbx_run(struct ast_channel *c) { return ast_pbx_run_args(c, NULL); } int ast_active_calls(void) { return countcalls; } int ast_processed_calls(void) { return totalcalls; } int pbx_set_autofallthrough(int newval) { int oldval = autofallthrough; autofallthrough = newval; return oldval; } int pbx_set_extenpatternmatchnew(int newval) { int oldval = extenpatternmatchnew; extenpatternmatchnew = newval; return oldval; } void pbx_set_overrideswitch(const char *newval) { if (overrideswitch) { ast_free(overrideswitch); } if (!ast_strlen_zero(newval)) { overrideswitch = ast_strdup(newval); } else { overrideswitch = NULL; } } /*! * \brief lookup for a context with a given name, * \retval found context or NULL if not found. */ static struct ast_context *find_context(const char *context) { struct fake_context item; ast_copy_string(item.name, context, sizeof(item.name)); return ast_hashtab_lookup(contexts_table, &item); } /*! * \brief lookup for a context with a given name, * \retval with conlock held if found. * \retval NULL if not found. */ static struct ast_context *find_context_locked(const char *context) { struct ast_context *c; struct fake_context item; ast_copy_string(item.name, context, sizeof(item.name)); ast_rdlock_contexts(); c = ast_hashtab_lookup(contexts_table, &item); if (!c) { ast_unlock_contexts(); } return c; } /*! * \brief Remove included contexts. * This function locks contexts list by &conlist, search for the right context * structure, leave context list locked and call ast_context_remove_include2 * which removes include, unlock contexts list and return ... */ int ast_context_remove_include(const char *context, const char *include, const char *registrar) { int ret = -1; struct ast_context *c; c = find_context_locked(context); if (c) { /* found, remove include from this context ... */ ret = ast_context_remove_include2(c, include, registrar); ast_unlock_contexts(); } return ret; } /*! * \brief Locks context, remove included contexts, unlocks context. * When we call this function, &conlock lock must be locked, because when * we giving *con argument, some process can remove/change this context * and after that there can be segfault. * * \retval 0 on success. * \retval -1 on failure. */ int ast_context_remove_include2(struct ast_context *con, const char *include, const char *registrar) { struct ast_include *i, *pi = NULL; int ret = -1; ast_wrlock_context(con); /* find our include */ for (i = con->includes; i; pi = i, i = i->next) { if (!strcmp(i->name, include) && (!registrar || !strcmp(i->registrar, registrar))) { /* remove from list */ ast_verb(3, "Removing inclusion of context '%s' in context '%s; registrar=%s'\n", include, ast_get_context_name(con), registrar); if (pi) pi->next = i->next; else con->includes = i->next; /* free include and return */ ast_destroy_timing(&(i->timing)); ast_free(i); ret = 0; break; } } ast_unlock_context(con); return ret; } /*! * \note This function locks contexts list by &conlist, search for the rigt context * structure, leave context list locked and call ast_context_remove_switch2 * which removes switch, unlock contexts list and return ... */ int ast_context_remove_switch(const char *context, const char *sw, const char *data, const char *registrar) { int ret = -1; /* default error return */ struct ast_context *c; c = find_context_locked(context); if (c) { /* remove switch from this context ... */ ret = ast_context_remove_switch2(c, sw, data, registrar); ast_unlock_contexts(); } return ret; } /*! * \brief This function locks given context, removes switch, unlock context and * return. * \note When we call this function, &conlock lock must be locked, because when * we giving *con argument, some process can remove/change this context * and after that there can be segfault. * */ int ast_context_remove_switch2(struct ast_context *con, const char *sw, const char *data, const char *registrar) { struct ast_sw *i; int ret = -1; ast_wrlock_context(con); /* walk switches */ AST_LIST_TRAVERSE_SAFE_BEGIN(&con->alts, i, list) { if (!strcmp(i->name, sw) && !strcmp(i->data, data) && (!registrar || !strcmp(i->registrar, registrar))) { /* found, remove from list */ ast_verb(3, "Removing switch '%s' from context '%s; registrar=%s'\n", sw, ast_get_context_name(con), registrar); AST_LIST_REMOVE_CURRENT(list); ast_free(i); /* free switch and return */ ret = 0; break; } } AST_LIST_TRAVERSE_SAFE_END; ast_unlock_context(con); return ret; } /*! \note This function will lock conlock. */ int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar) { return ast_context_remove_extension_callerid(context, extension, priority, NULL, 0, registrar); } int ast_context_remove_extension_callerid(const char *context, const char *extension, int priority, const char *callerid, int matchcallerid, const char *registrar) { int ret = -1; /* default error return */ struct ast_context *c; c = find_context_locked(context); if (c) { /* ... remove extension ... */ ret = ast_context_remove_extension_callerid2(c, extension, priority, callerid, matchcallerid, registrar, 0); ast_unlock_contexts(); } return ret; } /*! * \brief This functionc locks given context, search for the right extension and * fires out all peer in this extensions with given priority. If priority * is set to 0, all peers are removed. After that, unlock context and * return. * \note When do you want to call this function, make sure that &conlock is locked, * because some process can handle with your *con context before you lock * it. * */ int ast_context_remove_extension2(struct ast_context *con, const char *extension, int priority, const char *registrar, int already_locked) { return ast_context_remove_extension_callerid2(con, extension, priority, NULL, 0, registrar, already_locked); } int ast_context_remove_extension_callerid2(struct ast_context *con, const char *extension, int priority, const char *callerid, int matchcallerid, const char *registrar, int already_locked) { struct ast_exten *exten, *prev_exten = NULL; struct ast_exten *peer; struct ast_exten ex, *exten2, *exten3; char dummy_name[1024]; struct ast_exten *previous_peer = NULL; struct ast_exten *next_peer = NULL; int found = 0; if (!already_locked) ast_wrlock_context(con); /* Handle this is in the new world */ /* FIXME For backwards compatibility, if callerid==NULL, then remove ALL * peers, not just those matching the callerid. */ #ifdef NEED_DEBUG ast_verb(3,"Removing %s/%s/%d%s%s from trees, registrar=%s\n", con->name, extension, priority, matchcallerid ? "/" : "", matchcallerid ? callerid : "", registrar); #endif #ifdef CONTEXT_DEBUG check_contexts(__FILE__, __LINE__); #endif /* find this particular extension */ ex.exten = dummy_name; ex.matchcid = matchcallerid && !ast_strlen_zero(callerid); /* don't say match if there's no callerid */ ex.cidmatch = callerid; ast_copy_string(dummy_name, extension, sizeof(dummy_name)); exten = ast_hashtab_lookup(con->root_table, &ex); if (exten) { if (priority == 0) { exten2 = ast_hashtab_remove_this_object(con->root_table, exten); if (!exten2) ast_log(LOG_ERROR,"Trying to delete the exten %s from context %s, but could not remove from the root_table\n", extension, con->name); if (con->pattern_tree) { struct match_char *x = add_exten_to_pattern_tree(con, exten, 1); if (x->exten) { /* this test for safety purposes */ x->deleted = 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */ x->exten = 0; /* get rid of what will become a bad pointer */ } else { ast_log(LOG_WARNING,"Trying to delete an exten from a context, but the pattern tree node returned isn't a full extension\n"); } } } else { ex.priority = priority; exten2 = ast_hashtab_lookup(exten->peer_table, &ex); if (exten2) { if (exten2->label) { /* if this exten has a label, remove that, too */ exten3 = ast_hashtab_remove_this_object(exten->peer_label_table,exten2); if (!exten3) ast_log(LOG_ERROR,"Did not remove this priority label (%d/%s) from the peer_label_table of context %s, extension %s!\n", priority, exten2->label, con->name, exten2->exten); } exten3 = ast_hashtab_remove_this_object(exten->peer_table, exten2); if (!exten3) ast_log(LOG_ERROR,"Did not remove this priority (%d) from the peer_table of context %s, extension %s!\n", priority, con->name, exten2->exten); if (exten2 == exten && exten2->peer) { exten2 = ast_hashtab_remove_this_object(con->root_table, exten); ast_hashtab_insert_immediate(con->root_table, exten2->peer); } if (ast_hashtab_size(exten->peer_table) == 0) { /* well, if the last priority of an exten is to be removed, then, the extension is removed, too! */ exten3 = ast_hashtab_remove_this_object(con->root_table, exten); if (!exten3) ast_log(LOG_ERROR,"Did not remove this exten (%s) from the context root_table (%s) (priority %d)\n", exten->exten, con->name, priority); if (con->pattern_tree) { struct match_char *x = add_exten_to_pattern_tree(con, exten, 1); if (x->exten) { /* this test for safety purposes */ x->deleted = 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */ x->exten = 0; /* get rid of what will become a bad pointer */ } } } } else { ast_log(LOG_ERROR,"Could not find priority %d of exten %s in context %s!\n", priority, exten->exten, con->name); } } } else { /* hmmm? this exten is not in this pattern tree? */ ast_log(LOG_WARNING,"Cannot find extension %s in root_table in context %s\n", extension, con->name); } #ifdef NEED_DEBUG if (con->pattern_tree) { ast_log(LOG_NOTICE,"match char tree after exten removal:\n"); log_match_char_tree(con->pattern_tree, " "); } #endif /* scan the extension list to find first matching extension-registrar */ for (exten = con->root; exten; prev_exten = exten, exten = exten->next) { if (!strcmp(exten->exten, extension) && (!registrar || !strcmp(exten->registrar, registrar)) && (!matchcallerid || (!ast_strlen_zero(callerid) && !ast_strlen_zero(exten->cidmatch) && !strcmp(exten->cidmatch, callerid)) || (ast_strlen_zero(callerid) && ast_strlen_zero(exten->cidmatch)))) break; } if (!exten) { /* we can't find right extension */ if (!already_locked) ast_unlock_context(con); return -1; } /* scan the priority list to remove extension with exten->priority == priority */ for (peer = exten, next_peer = exten->peer ? exten->peer : exten->next; peer && !strcmp(peer->exten, extension) && (!matchcallerid || (!ast_strlen_zero(callerid) && !ast_strlen_zero(peer->cidmatch) && !strcmp(peer->cidmatch,callerid)) || (ast_strlen_zero(callerid) && ast_strlen_zero(peer->cidmatch))); peer = next_peer, next_peer = next_peer ? (next_peer->peer ? next_peer->peer : next_peer->next) : NULL) { if ((priority == 0 || peer->priority == priority) && (!callerid || !matchcallerid || (matchcallerid && !strcmp(peer->cidmatch, callerid))) && (!registrar || !strcmp(peer->registrar, registrar) )) { found = 1; /* we are first priority extension? */ if (!previous_peer) { /* * We are first in the priority chain, so must update the extension chain. * The next node is either the next priority or the next extension */ struct ast_exten *next_node = peer->peer ? peer->peer : peer->next; if (peer->peer) { /* move the peer_table and peer_label_table down to the next peer, if it is there */ peer->peer->peer_table = peer->peer_table; peer->peer->peer_label_table = peer->peer_label_table; peer->peer_table = NULL; peer->peer_label_table = NULL; } if (!prev_exten) { /* change the root... */ con->root = next_node; } else { prev_exten->next = next_node; /* unlink */ } if (peer->peer) { /* update the new head of the pri list */ peer->peer->next = peer->next; } } else { /* easy, we are not first priority in extension */ previous_peer->peer = peer->peer; } /* now, free whole priority extension */ destroy_exten(peer); } else { previous_peer = peer; } } if (!already_locked) ast_unlock_context(con); return found ? 0 : -1; } /*! * \note This function locks contexts list by &conlist, searches for the right context * structure, and locks the macrolock mutex in that context. * macrolock is used to limit a macro to be executed by one call at a time. */ int ast_context_lockmacro(const char *context) { struct ast_context *c; int ret = -1; c = find_context_locked(context); if (c) { ast_unlock_contexts(); /* if we found context, lock macrolock */ ret = ast_mutex_lock(&c->macrolock); } return ret; } /*! * \note This function locks contexts list by &conlist, searches for the right context * structure, and unlocks the macrolock mutex in that context. * macrolock is used to limit a macro to be executed by one call at a time. */ int ast_context_unlockmacro(const char *context) { struct ast_context *c; int ret = -1; c = find_context_locked(context); if (c) { ast_unlock_contexts(); /* if we found context, unlock macrolock */ ret = ast_mutex_unlock(&c->macrolock); } return ret; } /*! \brief Dynamically register a new dial plan application */ int ast_register_application2(const char *app, int (*execute)(struct ast_channel *, const char *), const char *synopsis, const char *description, void *mod) { struct ast_app *tmp, *cur = NULL; char tmps[80]; int length, res; #ifdef AST_XML_DOCS char *tmpxml; #endif AST_RWLIST_WRLOCK(&apps); AST_RWLIST_TRAVERSE(&apps, tmp, list) { if (!(res = strcasecmp(app, tmp->name))) { ast_log(LOG_WARNING, "Already have an application '%s'\n", app); AST_RWLIST_UNLOCK(&apps); return -1; } else if (res < 0) break; } length = sizeof(*tmp) + strlen(app) + 1; if (!(tmp = ast_calloc(1, length))) { AST_RWLIST_UNLOCK(&apps); return -1; } if (ast_string_field_init(tmp, 128)) { AST_RWLIST_UNLOCK(&apps); ast_free(tmp); return -1; } strcpy(tmp->name, app); tmp->execute = execute; tmp->module = mod; #ifdef AST_XML_DOCS /* Try to lookup the docs in our XML documentation database */ if (ast_strlen_zero(synopsis) && ast_strlen_zero(description)) { /* load synopsis */ tmpxml = ast_xmldoc_build_synopsis("application", app, ast_module_name(tmp->module)); ast_string_field_set(tmp, synopsis, tmpxml); ast_free(tmpxml); /* load description */ tmpxml = ast_xmldoc_build_description("application", app, ast_module_name(tmp->module)); ast_string_field_set(tmp, description, tmpxml); ast_free(tmpxml); /* load syntax */ tmpxml = ast_xmldoc_build_syntax("application", app, ast_module_name(tmp->module)); ast_string_field_set(tmp, syntax, tmpxml); ast_free(tmpxml); /* load arguments */ tmpxml = ast_xmldoc_build_arguments("application", app, ast_module_name(tmp->module)); ast_string_field_set(tmp, arguments, tmpxml); ast_free(tmpxml); /* load seealso */ tmpxml = ast_xmldoc_build_seealso("application", app, ast_module_name(tmp->module)); ast_string_field_set(tmp, seealso, tmpxml); ast_free(tmpxml); tmp->docsrc = AST_XML_DOC; } else { #endif ast_string_field_set(tmp, synopsis, synopsis); ast_string_field_set(tmp, description, description); #ifdef AST_XML_DOCS tmp->docsrc = AST_STATIC_DOC; } #endif /* Store in alphabetical order */ AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps, cur, list) { if (strcasecmp(tmp->name, cur->name) < 0) { AST_RWLIST_INSERT_BEFORE_CURRENT(tmp, list); break; } } AST_RWLIST_TRAVERSE_SAFE_END; if (!cur) AST_RWLIST_INSERT_TAIL(&apps, tmp, list); ast_verb(2, "Registered application '%s'\n", term_color(tmps, tmp->name, COLOR_BRCYAN, 0, sizeof(tmps))); AST_RWLIST_UNLOCK(&apps); return 0; } /* * Append to the list. We don't have a tail pointer because we need * to scan the list anyways to check for duplicates during insertion. */ int ast_register_switch(struct ast_switch *sw) { struct ast_switch *tmp; AST_RWLIST_WRLOCK(&switches); AST_RWLIST_TRAVERSE(&switches, tmp, list) { if (!strcasecmp(tmp->name, sw->name)) { AST_RWLIST_UNLOCK(&switches); ast_log(LOG_WARNING, "Switch '%s' already found\n", sw->name); return -1; } } AST_RWLIST_INSERT_TAIL(&switches, sw, list); AST_RWLIST_UNLOCK(&switches); return 0; } void ast_unregister_switch(struct ast_switch *sw) { AST_RWLIST_WRLOCK(&switches); AST_RWLIST_REMOVE(&switches, sw, list); AST_RWLIST_UNLOCK(&switches); } /* * Help for CLI commands ... */ static void print_app_docs(struct ast_app *aa, int fd) { /* Maximum number of characters added by terminal coloring is 22 */ char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40], stxtitle[40], argtitle[40]; char seealsotitle[40]; char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL, *syntax = NULL, *arguments = NULL; char *seealso = NULL; int syntax_size, synopsis_size, description_size, arguments_size, seealso_size; snprintf(info, sizeof(info), "\n -= Info about application '%s' =- \n\n", aa->name); term_color(infotitle, info, COLOR_MAGENTA, 0, sizeof(infotitle)); term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40); term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40); term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40); term_color(argtitle, "[Arguments]\n", COLOR_MAGENTA, 0, 40); term_color(seealsotitle, "[See Also]\n", COLOR_MAGENTA, 0, 40); #ifdef AST_XML_DOCS if (aa->docsrc == AST_XML_DOC) { description = ast_xmldoc_printable(S_OR(aa->description, "Not available"), 1); arguments = ast_xmldoc_printable(S_OR(aa->arguments, "Not available"), 1); synopsis = ast_xmldoc_printable(S_OR(aa->synopsis, "Not available"), 1); seealso = ast_xmldoc_printable(S_OR(aa->seealso, "Not available"), 1); if (!synopsis || !description || !arguments || !seealso) { goto return_cleanup; } } else #endif { synopsis_size = strlen(S_OR(aa->synopsis, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; synopsis = ast_malloc(synopsis_size); description_size = strlen(S_OR(aa->description, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; description = ast_malloc(description_size); arguments_size = strlen(S_OR(aa->arguments, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; arguments = ast_malloc(arguments_size); seealso_size = strlen(S_OR(aa->seealso, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; seealso = ast_malloc(seealso_size); if (!synopsis || !description || !arguments || !seealso) { goto return_cleanup; } term_color(synopsis, S_OR(aa->synopsis, "Not available"), COLOR_CYAN, 0, synopsis_size); term_color(description, S_OR(aa->description, "Not available"), COLOR_CYAN, 0, description_size); term_color(arguments, S_OR(aa->arguments, "Not available"), COLOR_CYAN, 0, arguments_size); term_color(seealso, S_OR(aa->seealso, "Not available"), COLOR_CYAN, 0, seealso_size); } /* Handle the syntax the same for both XML and raw docs */ syntax_size = strlen(S_OR(aa->syntax, "Not Available")) + AST_TERM_MAX_ESCAPE_CHARS; if (!(syntax = ast_malloc(syntax_size))) { goto return_cleanup; } term_color(syntax, S_OR(aa->syntax, "Not available"), COLOR_CYAN, 0, syntax_size); ast_cli(fd, "%s%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n", infotitle, syntitle, synopsis, destitle, description, stxtitle, syntax, argtitle, arguments, seealsotitle, seealso); return_cleanup: ast_free(description); ast_free(arguments); ast_free(synopsis); ast_free(seealso); ast_free(syntax); } /* * \brief 'show application' CLI command implementation function... */ static char *handle_show_application(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_app *aa; int app, no_registered_app = 1; switch (cmd) { case CLI_INIT: e->command = "core show application"; e->usage = "Usage: core show application <application> [<application> [<application> [...]]]\n" " Describes a particular application.\n"; return NULL; case CLI_GENERATE: /* * There is a possibility to show informations about more than one * application at one time. You can type 'show application Dial Echo' and * you will see informations about these two applications ... */ return ast_complete_applications(a->line, a->word, a->n); } if (a->argc < 4) { return CLI_SHOWUSAGE; } AST_RWLIST_RDLOCK(&apps); AST_RWLIST_TRAVERSE(&apps, aa, list) { /* Check for each app that was supplied as an argument */ for (app = 3; app < a->argc; app++) { if (strcasecmp(aa->name, a->argv[app])) { continue; } /* We found it! */ no_registered_app = 0; print_app_docs(aa, a->fd); } } AST_RWLIST_UNLOCK(&apps); /* we found at least one app? no? */ if (no_registered_app) { ast_cli(a->fd, "Your application(s) is (are) not registered\n"); return CLI_FAILURE; } return CLI_SUCCESS; } /*! \brief handle_show_hints: CLI support for listing registered dial plan hints */ static char *handle_show_hints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_hint *hint; int num = 0; int watchers; struct ao2_iterator i; switch (cmd) { case CLI_INIT: e->command = "core show hints"; e->usage = "Usage: core show hints\n" " List registered hints\n"; return NULL; case CLI_GENERATE: return NULL; } if (ao2_container_count(hints) == 0) { ast_cli(a->fd, "There are no registered dialplan hints\n"); return CLI_SUCCESS; } /* ... we have hints ... */ ast_cli(a->fd, "\n -= Registered Asterisk Dial Plan Hints =-\n"); i = ao2_iterator_init(hints, 0); for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) { ao2_lock(hint); if (!hint->exten) { /* The extension has already been destroyed */ ao2_unlock(hint); continue; } watchers = ao2_container_count(hint->callbacks); ast_cli(a->fd, " %20s@%-20.20s: %-20.20s State:%-15.15s Watchers %2d\n", ast_get_extension_name(hint->exten), ast_get_context_name(ast_get_extension_context(hint->exten)), ast_get_extension_app(hint->exten), ast_extension_state2str(hint->laststate), watchers); ao2_unlock(hint); num++; } ao2_iterator_destroy(&i); ast_cli(a->fd, "----------------\n"); ast_cli(a->fd, "- %d hints registered\n", num); return CLI_SUCCESS; } /*! \brief autocomplete for CLI command 'core show hint' */ static char *complete_core_show_hint(const char *line, const char *word, int pos, int state) { struct ast_hint *hint; char *ret = NULL; int which = 0; int wordlen; struct ao2_iterator i; if (pos != 3) return NULL; wordlen = strlen(word); /* walk through all hints */ i = ao2_iterator_init(hints, 0); for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) { ao2_lock(hint); if (!hint->exten) { /* The extension has already been destroyed */ ao2_unlock(hint); continue; } if (!strncasecmp(word, ast_get_extension_name(hint->exten), wordlen) && ++which > state) { ret = ast_strdup(ast_get_extension_name(hint->exten)); ao2_unlock(hint); ao2_ref(hint, -1); break; } ao2_unlock(hint); } ao2_iterator_destroy(&i); return ret; } /*! \brief handle_show_hint: CLI support for listing registered dial plan hint */ static char *handle_show_hint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_hint *hint; int watchers; int num = 0, extenlen; struct ao2_iterator i; switch (cmd) { case CLI_INIT: e->command = "core show hint"; e->usage = "Usage: core show hint <exten>\n" " List registered hint\n"; return NULL; case CLI_GENERATE: return complete_core_show_hint(a->line, a->word, a->pos, a->n); } if (a->argc < 4) return CLI_SHOWUSAGE; if (ao2_container_count(hints) == 0) { ast_cli(a->fd, "There are no registered dialplan hints\n"); return CLI_SUCCESS; } extenlen = strlen(a->argv[3]); i = ao2_iterator_init(hints, 0); for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) { ao2_lock(hint); if (!hint->exten) { /* The extension has already been destroyed */ ao2_unlock(hint); continue; } if (!strncasecmp(ast_get_extension_name(hint->exten), a->argv[3], extenlen)) { watchers = ao2_container_count(hint->callbacks); ast_cli(a->fd, " %20s@%-20.20s: %-20.20s State:%-15.15s Watchers %2d\n", ast_get_extension_name(hint->exten), ast_get_context_name(ast_get_extension_context(hint->exten)), ast_get_extension_app(hint->exten), ast_extension_state2str(hint->laststate), watchers); num++; } ao2_unlock(hint); } ao2_iterator_destroy(&i); if (!num) ast_cli(a->fd, "No hints matching extension %s\n", a->argv[3]); else ast_cli(a->fd, "%d hint%s matching extension %s\n", num, (num!=1 ? "s":""), a->argv[3]); return CLI_SUCCESS; } /*! \brief handle_show_switches: CLI support for listing registered dial plan switches */ static char *handle_show_switches(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_switch *sw; switch (cmd) { case CLI_INIT: e->command = "core show switches"; e->usage = "Usage: core show switches\n" " List registered switches\n"; return NULL; case CLI_GENERATE: return NULL; } AST_RWLIST_RDLOCK(&switches); if (AST_RWLIST_EMPTY(&switches)) { AST_RWLIST_UNLOCK(&switches); ast_cli(a->fd, "There are no registered alternative switches\n"); return CLI_SUCCESS; } ast_cli(a->fd, "\n -= Registered Asterisk Alternative Switches =-\n"); AST_RWLIST_TRAVERSE(&switches, sw, list) ast_cli(a->fd, "%s: %s\n", sw->name, sw->description); AST_RWLIST_UNLOCK(&switches); return CLI_SUCCESS; } static char *handle_show_applications(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_app *aa; int like = 0, describing = 0; int total_match = 0; /* Number of matches in like clause */ int total_apps = 0; /* Number of apps registered */ static const char * const choices[] = { "like", "describing", NULL }; switch (cmd) { case CLI_INIT: e->command = "core show applications [like|describing]"; e->usage = "Usage: core show applications [{like|describing} <text>]\n" " List applications which are currently available.\n" " If 'like', <text> will be a substring of the app name\n" " If 'describing', <text> will be a substring of the description\n"; return NULL; case CLI_GENERATE: return (a->pos != 3) ? NULL : ast_cli_complete(a->word, choices, a->n); } AST_RWLIST_RDLOCK(&apps); if (AST_RWLIST_EMPTY(&apps)) { ast_cli(a->fd, "There are no registered applications\n"); AST_RWLIST_UNLOCK(&apps); return CLI_SUCCESS; } /* core list applications like <keyword> */ if ((a->argc == 5) && (!strcmp(a->argv[3], "like"))) { like = 1; } else if ((a->argc > 4) && (!strcmp(a->argv[3], "describing"))) { describing = 1; } /* core list applications describing <keyword1> [<keyword2>] [...] */ if ((!like) && (!describing)) { ast_cli(a->fd, " -= Registered Asterisk Applications =-\n"); } else { ast_cli(a->fd, " -= Matching Asterisk Applications =-\n"); } AST_RWLIST_TRAVERSE(&apps, aa, list) { int printapp = 0; total_apps++; if (like) { if (strcasestr(aa->name, a->argv[4])) { printapp = 1; total_match++; } } else if (describing) { if (aa->description) { /* Match all words on command line */ int i; printapp = 1; for (i = 4; i < a->argc; i++) { if (!strcasestr(aa->description, a->argv[i])) { printapp = 0; } else { total_match++; } } } } else { printapp = 1; } if (printapp) { ast_cli(a->fd," %20s: %s\n", aa->name, aa->synopsis ? aa->synopsis : "<Synopsis not available>"); } } if ((!like) && (!describing)) { ast_cli(a->fd, " -= %d Applications Registered =-\n",total_apps); } else { ast_cli(a->fd, " -= %d Applications Matching =-\n",total_match); } AST_RWLIST_UNLOCK(&apps); return CLI_SUCCESS; } /* * 'show dialplan' CLI command implementation functions ... */ static char *complete_show_dialplan_context(const char *line, const char *word, int pos, int state) { struct ast_context *c = NULL; char *ret = NULL; int which = 0; int wordlen; /* we are do completion of [exten@]context on second position only */ if (pos != 2) return NULL; ast_rdlock_contexts(); wordlen = strlen(word); /* walk through all contexts and return the n-th match */ while ( (c = ast_walk_contexts(c)) ) { if (!strncasecmp(word, ast_get_context_name(c), wordlen) && ++which > state) { ret = ast_strdup(ast_get_context_name(c)); break; } } ast_unlock_contexts(); return ret; } /*! \brief Counters for the show dialplan manager command */ struct dialplan_counters { int total_items; int total_context; int total_exten; int total_prio; int context_existence; int extension_existence; }; /*! \brief helper function to print an extension */ static void print_ext(struct ast_exten *e, char * buf, int buflen) { int prio = ast_get_extension_priority(e); if (prio == PRIORITY_HINT) { snprintf(buf, buflen, "hint: %s", ast_get_extension_app(e)); } else { snprintf(buf, buflen, "%d. %s(%s)", prio, ast_get_extension_app(e), (!ast_strlen_zero(ast_get_extension_app_data(e)) ? (char *)ast_get_extension_app_data(e) : "")); } } /* XXX not verified */ static int show_dialplan_helper(int fd, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, const char *includes[]) { struct ast_context *c = NULL; int res = 0, old_total_exten = dpc->total_exten; ast_rdlock_contexts(); /* walk all contexts ... */ while ( (c = ast_walk_contexts(c)) ) { struct ast_exten *e; struct ast_include *i; struct ast_ignorepat *ip; char buf[256], buf2[256]; int context_info_printed = 0; if (context && strcmp(ast_get_context_name(c), context)) continue; /* skip this one, name doesn't match */ dpc->context_existence = 1; ast_rdlock_context(c); /* are we looking for exten too? if yes, we print context * only if we find our extension. * Otherwise print context even if empty ? * XXX i am not sure how the rinclude is handled. * I think it ought to go inside. */ if (!exten) { dpc->total_context++; ast_cli(fd, "[ Context '%s' created by '%s' ]\n", ast_get_context_name(c), ast_get_context_registrar(c)); context_info_printed = 1; } /* walk extensions ... */ e = NULL; while ( (e = ast_walk_context_extensions(c, e)) ) { struct ast_exten *p; if (exten && !ast_extension_match(ast_get_extension_name(e), exten)) continue; /* skip, extension match failed */ dpc->extension_existence = 1; /* may we print context info? */ if (!context_info_printed) { dpc->total_context++; if (rinclude) { /* TODO Print more info about rinclude */ ast_cli(fd, "[ Included context '%s' created by '%s' ]\n", ast_get_context_name(c), ast_get_context_registrar(c)); } else { ast_cli(fd, "[ Context '%s' created by '%s' ]\n", ast_get_context_name(c), ast_get_context_registrar(c)); } context_info_printed = 1; } dpc->total_prio++; /* write extension name and first peer */ if (e->matchcid) snprintf(buf, sizeof(buf), "'%s' (CID match '%s') => ", ast_get_extension_name(e), e->cidmatch); else snprintf(buf, sizeof(buf), "'%s' =>", ast_get_extension_name(e)); print_ext(e, buf2, sizeof(buf2)); ast_cli(fd, " %-17s %-45s [%s]\n", buf, buf2, ast_get_extension_registrar(e)); dpc->total_exten++; /* walk next extension peers */ p = e; /* skip the first one, we already got it */ while ( (p = ast_walk_extension_priorities(e, p)) ) { const char *el = ast_get_extension_label(p); dpc->total_prio++; if (el) snprintf(buf, sizeof(buf), " [%s]", el); else buf[0] = '\0'; print_ext(p, buf2, sizeof(buf2)); ast_cli(fd," %-17s %-45s [%s]\n", buf, buf2, ast_get_extension_registrar(p)); } } /* walk included and write info ... */ i = NULL; while ( (i = ast_walk_context_includes(c, i)) ) { snprintf(buf, sizeof(buf), "'%s'", ast_get_include_name(i)); if (exten) { /* Check all includes for the requested extension */ if (includecount >= AST_PBX_MAX_STACK) { ast_log(LOG_WARNING, "Maximum include depth exceeded!\n"); } else { int dupe = 0; int x; for (x = 0; x < includecount; x++) { if (!strcasecmp(includes[x], ast_get_include_name(i))) { dupe++; break; } } if (!dupe) { includes[includecount] = ast_get_include_name(i); show_dialplan_helper(fd, ast_get_include_name(i), exten, dpc, i, includecount + 1, includes); } else { ast_log(LOG_WARNING, "Avoiding circular include of %s within %s\n", ast_get_include_name(i), context); } } } else { ast_cli(fd, " Include => %-45s [%s]\n", buf, ast_get_include_registrar(i)); } } /* walk ignore patterns and write info ... */ ip = NULL; while ( (ip = ast_walk_context_ignorepats(c, ip)) ) { const char *ipname = ast_get_ignorepat_name(ip); char ignorepat[AST_MAX_EXTENSION]; snprintf(buf, sizeof(buf), "'%s'", ipname); snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname); if (!exten || ast_extension_match(ignorepat, exten)) { ast_cli(fd, " Ignore pattern => %-45s [%s]\n", buf, ast_get_ignorepat_registrar(ip)); } } if (!rinclude) { struct ast_sw *sw = NULL; while ( (sw = ast_walk_context_switches(c, sw)) ) { snprintf(buf, sizeof(buf), "'%s/%s'", ast_get_switch_name(sw), ast_get_switch_data(sw)); ast_cli(fd, " Alt. Switch => %-45s [%s]\n", buf, ast_get_switch_registrar(sw)); } } ast_unlock_context(c); /* if we print something in context, make an empty line */ if (context_info_printed) ast_cli(fd, "\n"); } ast_unlock_contexts(); return (dpc->total_exten == old_total_exten) ? -1 : res; } static int show_debug_helper(int fd, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, const char *includes[]) { struct ast_context *c = NULL; int res = 0, old_total_exten = dpc->total_exten; ast_cli(fd,"\n In-mem exten Trie for Fast Extension Pattern Matching:\n\n"); ast_cli(fd,"\n Explanation: Node Contents Format = <char(s) to match>:<pattern?>:<specif>:[matched extension]\n"); ast_cli(fd, " Where <char(s) to match> is a set of chars, any one of which should match the current character\n"); ast_cli(fd, " <pattern?>: Y if this a pattern match (eg. _XZN[5-7]), N otherwise\n"); ast_cli(fd, " <specif>: an assigned 'exactness' number for this matching char. The lower the number, the more exact the match\n"); ast_cli(fd, " [matched exten]: If all chars matched to this point, which extension this matches. In form: EXTEN:<exten string>\n"); ast_cli(fd, " In general, you match a trie node to a string character, from left to right. All possible matching chars\n"); ast_cli(fd, " are in a string vertically, separated by an unbroken string of '+' characters.\n\n"); ast_rdlock_contexts(); /* walk all contexts ... */ while ( (c = ast_walk_contexts(c)) ) { int context_info_printed = 0; if (context && strcmp(ast_get_context_name(c), context)) continue; /* skip this one, name doesn't match */ dpc->context_existence = 1; if (!c->pattern_tree) { /* Ignore check_return warning from Coverity for ast_exists_extension below */ ast_exists_extension(NULL, c->name, "s", 1, ""); /* do this to force the trie to built, if it is not already */ } ast_rdlock_context(c); dpc->total_context++; ast_cli(fd, "[ Context '%s' created by '%s' ]\n", ast_get_context_name(c), ast_get_context_registrar(c)); context_info_printed = 1; if (c->pattern_tree) { cli_match_char_tree(c->pattern_tree, " ", fd); } else { ast_cli(fd,"\n No Pattern Trie present. Perhaps the context is empty...or there is trouble...\n\n"); } ast_unlock_context(c); /* if we print something in context, make an empty line */ if (context_info_printed) ast_cli(fd, "\n"); } ast_unlock_contexts(); return (dpc->total_exten == old_total_exten) ? -1 : res; } static char *handle_show_dialplan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { char *exten = NULL, *context = NULL; /* Variables used for different counters */ struct dialplan_counters counters; const char *incstack[AST_PBX_MAX_STACK]; switch (cmd) { case CLI_INIT: e->command = "dialplan show"; e->usage = "Usage: dialplan show [[exten@]context]\n" " Show dialplan\n"; return NULL; case CLI_GENERATE: return complete_show_dialplan_context(a->line, a->word, a->pos, a->n); } memset(&counters, 0, sizeof(counters)); if (a->argc != 2 && a->argc != 3) return CLI_SHOWUSAGE; /* we obtain [exten@]context? if yes, split them ... */ if (a->argc == 3) { if (strchr(a->argv[2], '@')) { /* split into exten & context */ context = ast_strdupa(a->argv[2]); exten = strsep(&context, "@"); /* change empty strings to NULL */ if (ast_strlen_zero(exten)) exten = NULL; } else { /* no '@' char, only context given */ context = ast_strdupa(a->argv[2]); } if (ast_strlen_zero(context)) context = NULL; } /* else Show complete dial plan, context and exten are NULL */ show_dialplan_helper(a->fd, context, exten, &counters, NULL, 0, incstack); /* check for input failure and throw some error messages */ if (context && !counters.context_existence) { ast_cli(a->fd, "There is no existence of '%s' context\n", context); return CLI_FAILURE; } if (exten && !counters.extension_existence) { if (context) ast_cli(a->fd, "There is no existence of %s@%s extension\n", exten, context); else ast_cli(a->fd, "There is no existence of '%s' extension in all contexts\n", exten); return CLI_FAILURE; } ast_cli(a->fd,"-= %d %s (%d %s) in %d %s. =-\n", counters.total_exten, counters.total_exten == 1 ? "extension" : "extensions", counters.total_prio, counters.total_prio == 1 ? "priority" : "priorities", counters.total_context, counters.total_context == 1 ? "context" : "contexts"); /* everything ok */ return CLI_SUCCESS; } /*! \brief Send ack once */ static char *handle_debug_dialplan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { char *exten = NULL, *context = NULL; /* Variables used for different counters */ struct dialplan_counters counters; const char *incstack[AST_PBX_MAX_STACK]; switch (cmd) { case CLI_INIT: e->command = "dialplan debug"; e->usage = "Usage: dialplan debug [context]\n" " Show dialplan context Trie(s). Usually only useful to folks debugging the deep internals of the fast pattern matcher\n"; return NULL; case CLI_GENERATE: return complete_show_dialplan_context(a->line, a->word, a->pos, a->n); } memset(&counters, 0, sizeof(counters)); if (a->argc != 2 && a->argc != 3) return CLI_SHOWUSAGE; /* we obtain [exten@]context? if yes, split them ... */ /* note: we ignore the exten totally here .... */ if (a->argc == 3) { if (strchr(a->argv[2], '@')) { /* split into exten & context */ context = ast_strdupa(a->argv[2]); exten = strsep(&context, "@"); /* change empty strings to NULL */ if (ast_strlen_zero(exten)) exten = NULL; } else { /* no '@' char, only context given */ context = ast_strdupa(a->argv[2]); } if (ast_strlen_zero(context)) context = NULL; } /* else Show complete dial plan, context and exten are NULL */ show_debug_helper(a->fd, context, exten, &counters, NULL, 0, incstack); /* check for input failure and throw some error messages */ if (context && !counters.context_existence) { ast_cli(a->fd, "There is no existence of '%s' context\n", context); return CLI_FAILURE; } ast_cli(a->fd,"-= %d %s. =-\n", counters.total_context, counters.total_context == 1 ? "context" : "contexts"); /* everything ok */ return CLI_SUCCESS; } /*! \brief Send ack once */ static void manager_dpsendack(struct mansession *s, const struct message *m) { astman_send_listack(s, m, "DialPlan list will follow", "start"); } /*! \brief Show dialplan extensions * XXX this function is similar but not exactly the same as the CLI's * show dialplan. Must check whether the difference is intentional or not. */ static int manager_show_dialplan_helper(struct mansession *s, const struct message *m, const char *actionidtext, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude) { struct ast_context *c; int res = 0, old_total_exten = dpc->total_exten; if (ast_strlen_zero(exten)) exten = NULL; if (ast_strlen_zero(context)) context = NULL; ast_debug(3, "manager_show_dialplan: Context: -%s- Extension: -%s-\n", context, exten); /* try to lock contexts */ if (ast_rdlock_contexts()) { astman_send_error(s, m, "Failed to lock contexts"); ast_log(LOG_WARNING, "Failed to lock contexts list for manager: listdialplan\n"); return -1; } c = NULL; /* walk all contexts ... */ while ( (c = ast_walk_contexts(c)) ) { struct ast_exten *e; struct ast_include *i; struct ast_ignorepat *ip; if (context && strcmp(ast_get_context_name(c), context) != 0) continue; /* not the name we want */ dpc->context_existence = 1; dpc->total_context++; ast_debug(3, "manager_show_dialplan: Found Context: %s \n", ast_get_context_name(c)); if (ast_rdlock_context(c)) { /* failed to lock */ ast_debug(3, "manager_show_dialplan: Failed to lock context\n"); continue; } /* XXX note- an empty context is not printed */ e = NULL; /* walk extensions in context */ while ( (e = ast_walk_context_extensions(c, e)) ) { struct ast_exten *p; /* looking for extension? is this our extension? */ if (exten && !ast_extension_match(ast_get_extension_name(e), exten)) { /* not the one we are looking for, continue */ ast_debug(3, "manager_show_dialplan: Skipping extension %s\n", ast_get_extension_name(e)); continue; } ast_debug(3, "manager_show_dialplan: Found Extension: %s \n", ast_get_extension_name(e)); dpc->extension_existence = 1; dpc->total_exten++; p = NULL; /* walk next extension peers */ while ( (p = ast_walk_extension_priorities(e, p)) ) { int prio = ast_get_extension_priority(p); dpc->total_prio++; if (!dpc->total_items++) manager_dpsendack(s, m); astman_append(s, "Event: ListDialplan\r\n%s", actionidtext); astman_append(s, "Context: %s\r\nExtension: %s\r\n", ast_get_context_name(c), ast_get_extension_name(e) ); /* XXX maybe make this conditional, if p != e ? */ if (ast_get_extension_label(p)) astman_append(s, "ExtensionLabel: %s\r\n", ast_get_extension_label(p)); if (prio == PRIORITY_HINT) { astman_append(s, "Priority: hint\r\nApplication: %s\r\n", ast_get_extension_app(p)); } else { astman_append(s, "Priority: %d\r\nApplication: %s\r\nAppData: %s\r\n", prio, ast_get_extension_app(p), (char *) ast_get_extension_app_data(p)); } astman_append(s, "Registrar: %s\r\n\r\n", ast_get_extension_registrar(e)); } } i = NULL; /* walk included and write info ... */ while ( (i = ast_walk_context_includes(c, i)) ) { if (exten) { /* Check all includes for the requested extension */ manager_show_dialplan_helper(s, m, actionidtext, ast_get_include_name(i), exten, dpc, i); } else { if (!dpc->total_items++) manager_dpsendack(s, m); astman_append(s, "Event: ListDialplan\r\n%s", actionidtext); astman_append(s, "Context: %s\r\nIncludeContext: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_include_name(i), ast_get_include_registrar(i)); astman_append(s, "\r\n"); ast_debug(3, "manager_show_dialplan: Found Included context: %s \n", ast_get_include_name(i)); } } ip = NULL; /* walk ignore patterns and write info ... */ while ( (ip = ast_walk_context_ignorepats(c, ip)) ) { const char *ipname = ast_get_ignorepat_name(ip); char ignorepat[AST_MAX_EXTENSION]; snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname); if (!exten || ast_extension_match(ignorepat, exten)) { if (!dpc->total_items++) manager_dpsendack(s, m); astman_append(s, "Event: ListDialplan\r\n%s", actionidtext); astman_append(s, "Context: %s\r\nIgnorePattern: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ipname, ast_get_ignorepat_registrar(ip)); astman_append(s, "\r\n"); } } if (!rinclude) { struct ast_sw *sw = NULL; while ( (sw = ast_walk_context_switches(c, sw)) ) { if (!dpc->total_items++) manager_dpsendack(s, m); astman_append(s, "Event: ListDialplan\r\n%s", actionidtext); astman_append(s, "Context: %s\r\nSwitch: %s/%s\r\nRegistrar: %s\r\n", ast_get_context_name(c), ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_registrar(sw)); astman_append(s, "\r\n"); ast_debug(3, "manager_show_dialplan: Found Switch : %s \n", ast_get_switch_name(sw)); } } ast_unlock_context(c); } ast_unlock_contexts(); if (dpc->total_exten == old_total_exten) { ast_debug(3, "manager_show_dialplan: Found nothing new\n"); /* Nothing new under the sun */ return -1; } else { return res; } } /*! \brief Manager listing of dial plan */ static int manager_show_dialplan(struct mansession *s, const struct message *m) { const char *exten, *context; const char *id = astman_get_header(m, "ActionID"); char idtext[256]; /* Variables used for different counters */ struct dialplan_counters counters; if (!ast_strlen_zero(id)) snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id); else idtext[0] = '\0'; memset(&counters, 0, sizeof(counters)); exten = astman_get_header(m, "Extension"); context = astman_get_header(m, "Context"); manager_show_dialplan_helper(s, m, idtext, context, exten, &counters, NULL); if (!ast_strlen_zero(context) && !counters.context_existence) { char errorbuf[BUFSIZ]; snprintf(errorbuf, sizeof(errorbuf), "Did not find context %s", context); astman_send_error(s, m, errorbuf); return 0; } if (!ast_strlen_zero(exten) && !counters.extension_existence) { char errorbuf[BUFSIZ]; if (!ast_strlen_zero(context)) snprintf(errorbuf, sizeof(errorbuf), "Did not find extension %s@%s", exten, context); else snprintf(errorbuf, sizeof(errorbuf), "Did not find extension %s in any context", exten); astman_send_error(s, m, errorbuf); return 0; } if (!counters.total_items) { manager_dpsendack(s, m); } astman_append(s, "Event: ShowDialPlanComplete\r\n" "EventList: Complete\r\n" "ListItems: %d\r\n" "ListExtensions: %d\r\n" "ListPriorities: %d\r\n" "ListContexts: %d\r\n" "%s" "\r\n", counters.total_items, counters.total_exten, counters.total_prio, counters.total_context, idtext); /* everything ok */ return 0; } /*! \brief CLI support for listing global variables in a parseable way */ static char *handle_show_globals(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { int i = 0; struct ast_var_t *newvariable; switch (cmd) { case CLI_INIT: e->command = "dialplan show globals"; e->usage = "Usage: dialplan show globals\n" " List current global dialplan variables and their values\n"; return NULL; case CLI_GENERATE: return NULL; } ast_rwlock_rdlock(&globalslock); AST_LIST_TRAVERSE (&globals, newvariable, entries) { i++; ast_cli(a->fd, " %s=%s\n", ast_var_name(newvariable), ast_var_value(newvariable)); } ast_rwlock_unlock(&globalslock); ast_cli(a->fd, "\n -- %d variable(s)\n", i); return CLI_SUCCESS; } #ifdef AST_DEVMODE static char *handle_show_device2extenstate(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_devstate_aggregate agg; int i, j, exten, combined; switch (cmd) { case CLI_INIT: e->command = "core show device2extenstate"; e->usage = "Usage: core show device2extenstate\n" " Lists device state to extension state combinations.\n"; case CLI_GENERATE: return NULL; } for (i = 0; i < AST_DEVICE_TOTAL; i++) { for (j = 0; j < AST_DEVICE_TOTAL; j++) { ast_devstate_aggregate_init(&agg); ast_devstate_aggregate_add(&agg, i); ast_devstate_aggregate_add(&agg, j); combined = ast_devstate_aggregate_result(&agg); exten = ast_devstate_to_extenstate(combined); ast_cli(a->fd, "\n Exten:%14s CombinedDevice:%12s Dev1:%12s Dev2:%12s", ast_extension_state2str(exten), ast_devstate_str(combined), ast_devstate_str(j), ast_devstate_str(i)); } } ast_cli(a->fd, "\n"); return CLI_SUCCESS; } #endif /*! \brief CLI support for listing chanvar's variables in a parseable way */ static char *handle_show_chanvar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_channel *chan = NULL; struct ast_str *vars = ast_str_alloca(BUFSIZ * 4); /* XXX large because we might have lots of channel vars */ switch (cmd) { case CLI_INIT: e->command = "dialplan show chanvar"; e->usage = "Usage: dialplan show chanvar <channel>\n" " List current channel variables and their values\n"; return NULL; case CLI_GENERATE: return ast_complete_channels(a->line, a->word, a->pos, a->n, 3); } if (a->argc != e->args + 1) return CLI_SHOWUSAGE; if (!(chan = ast_channel_get_by_name(a->argv[e->args]))) { ast_cli(a->fd, "Channel '%s' not found\n", a->argv[e->args]); return CLI_FAILURE; } pbx_builtin_serialize_variables(chan, &vars); if (ast_str_strlen(vars)) { ast_cli(a->fd, "\nVariables for channel %s:\n%s\n", a->argv[e->args], ast_str_buffer(vars)); } chan = ast_channel_unref(chan); return CLI_SUCCESS; } static char *handle_set_global(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { switch (cmd) { case CLI_INIT: e->command = "dialplan set global"; e->usage = "Usage: dialplan set global <name> <value>\n" " Set global dialplan variable <name> to <value>\n"; return NULL; case CLI_GENERATE: return NULL; } if (a->argc != e->args + 2) return CLI_SHOWUSAGE; pbx_builtin_setvar_helper(NULL, a->argv[3], a->argv[4]); ast_cli(a->fd, "\n -- Global variable '%s' set to '%s'\n", a->argv[3], a->argv[4]); return CLI_SUCCESS; } static char *handle_set_chanvar(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct ast_channel *chan; const char *chan_name, *var_name, *var_value; switch (cmd) { case CLI_INIT: e->command = "dialplan set chanvar"; e->usage = "Usage: dialplan set chanvar <channel> <varname> <value>\n" " Set channel variable <varname> to <value>\n"; return NULL; case CLI_GENERATE: return ast_complete_channels(a->line, a->word, a->pos, a->n, 3); } if (a->argc != e->args + 3) return CLI_SHOWUSAGE; chan_name = a->argv[e->args]; var_name = a->argv[e->args + 1]; var_value = a->argv[e->args + 2]; if (!(chan = ast_channel_get_by_name(chan_name))) { ast_cli(a->fd, "Channel '%s' not found\n", chan_name); return CLI_FAILURE; } pbx_builtin_setvar_helper(chan, var_name, var_value); chan = ast_channel_unref(chan); ast_cli(a->fd, "\n -- Channel variable '%s' set to '%s' for '%s'\n", var_name, var_value, chan_name); return CLI_SUCCESS; } static char *handle_set_extenpatternmatchnew(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { int oldval = 0; switch (cmd) { case CLI_INIT: e->command = "dialplan set extenpatternmatchnew true"; e->usage = "Usage: dialplan set extenpatternmatchnew true|false\n" " Use the NEW extension pattern matching algorithm, true or false.\n"; return NULL; case CLI_GENERATE: return NULL; } if (a->argc != 4) return CLI_SHOWUSAGE; oldval = pbx_set_extenpatternmatchnew(1); if (oldval) ast_cli(a->fd, "\n -- Still using the NEW pattern match algorithm for extension names in the dialplan.\n"); else ast_cli(a->fd, "\n -- Switched to using the NEW pattern match algorithm for extension names in the dialplan.\n"); return CLI_SUCCESS; } static char *handle_unset_extenpatternmatchnew(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { int oldval = 0; switch (cmd) { case CLI_INIT: e->command = "dialplan set extenpatternmatchnew false"; e->usage = "Usage: dialplan set extenpatternmatchnew true|false\n" " Use the NEW extension pattern matching algorithm, true or false.\n"; return NULL; case CLI_GENERATE: return NULL; } if (a->argc != 4) return CLI_SHOWUSAGE; oldval = pbx_set_extenpatternmatchnew(0); if (!oldval) ast_cli(a->fd, "\n -- Still using the OLD pattern match algorithm for extension names in the dialplan.\n"); else ast_cli(a->fd, "\n -- Switched to using the OLD pattern match algorithm for extension names in the dialplan.\n"); return CLI_SUCCESS; } /* * CLI entries for upper commands ... */ static struct ast_cli_entry pbx_cli[] = { AST_CLI_DEFINE(handle_show_applications, "Shows registered dialplan applications"), AST_CLI_DEFINE(handle_show_functions, "Shows registered dialplan functions"), AST_CLI_DEFINE(handle_show_switches, "Show alternative switches"), AST_CLI_DEFINE(handle_show_hints, "Show dialplan hints"), AST_CLI_DEFINE(handle_show_hint, "Show dialplan hint"), AST_CLI_DEFINE(handle_show_globals, "Show global dialplan variables"), #ifdef AST_DEVMODE AST_CLI_DEFINE(handle_show_device2extenstate, "Show expected exten state from multiple device states"), #endif AST_CLI_DEFINE(handle_show_chanvar, "Show channel variables"), AST_CLI_DEFINE(handle_show_function, "Describe a specific dialplan function"), AST_CLI_DEFINE(handle_show_application, "Describe a specific dialplan application"), AST_CLI_DEFINE(handle_set_global, "Set global dialplan variable"), AST_CLI_DEFINE(handle_set_chanvar, "Set a channel variable"), AST_CLI_DEFINE(handle_show_dialplan, "Show dialplan"), AST_CLI_DEFINE(handle_debug_dialplan, "Show fast extension pattern matching data structures"), AST_CLI_DEFINE(handle_unset_extenpatternmatchnew, "Use the Old extension pattern matching algorithm."), AST_CLI_DEFINE(handle_set_extenpatternmatchnew, "Use the New extension pattern matching algorithm."), }; static void unreference_cached_app(struct ast_app *app) { struct ast_context *context = NULL; struct ast_exten *eroot = NULL, *e = NULL; ast_rdlock_contexts(); while ((context = ast_walk_contexts(context))) { while ((eroot = ast_walk_context_extensions(context, eroot))) { while ((e = ast_walk_extension_priorities(eroot, e))) { if (e->cached_app == app) e->cached_app = NULL; } } } ast_unlock_contexts(); return; } int ast_unregister_application(const char *app) { struct ast_app *tmp; AST_RWLIST_WRLOCK(&apps); AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps, tmp, list) { if (!strcasecmp(app, tmp->name)) { unreference_cached_app(tmp); AST_RWLIST_REMOVE_CURRENT(list); ast_verb(2, "Unregistered application '%s'\n", tmp->name); ast_string_field_free_memory(tmp); ast_free(tmp); break; } } AST_RWLIST_TRAVERSE_SAFE_END; AST_RWLIST_UNLOCK(&apps); return tmp ? 0 : -1; } struct ast_context *ast_context_find_or_create(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *name, const char *registrar) { struct ast_context *tmp, **local_contexts; struct fake_context search; int length = sizeof(struct ast_context) + strlen(name) + 1; if (!contexts_table) { /* Protect creation of contexts_table from reentrancy. */ ast_wrlock_contexts(); if (!contexts_table) { contexts_table = ast_hashtab_create(17, ast_hashtab_compare_contexts, ast_hashtab_resize_java, ast_hashtab_newsize_java, ast_hashtab_hash_contexts, 0); } ast_unlock_contexts(); } ast_copy_string(search.name, name, sizeof(search.name)); if (!extcontexts) { ast_rdlock_contexts(); local_contexts = &contexts; tmp = ast_hashtab_lookup(contexts_table, &search); ast_unlock_contexts(); if (tmp) { tmp->refcount++; return tmp; } } else { /* local contexts just in a linked list; search there for the new context; slow, linear search, but not frequent */ local_contexts = extcontexts; tmp = ast_hashtab_lookup(exttable, &search); if (tmp) { tmp->refcount++; return tmp; } } if ((tmp = ast_calloc(1, length))) { ast_rwlock_init(&tmp->lock); ast_mutex_init(&tmp->macrolock); strcpy(tmp->name, name); tmp->root = NULL; tmp->root_table = NULL; tmp->registrar = ast_strdup(registrar); tmp->includes = NULL; tmp->ignorepats = NULL; tmp->refcount = 1; } else { ast_log(LOG_ERROR, "Danger! We failed to allocate a context for %s!\n", name); return NULL; } if (!extcontexts) { ast_wrlock_contexts(); tmp->next = *local_contexts; *local_contexts = tmp; ast_hashtab_insert_safe(contexts_table, tmp); /*put this context into the tree */ ast_unlock_contexts(); ast_debug(1, "Registered context '%s'(%p) in table %p registrar: %s\n", tmp->name, tmp, contexts_table, registrar); ast_verb(3, "Registered extension context '%s'; registrar: %s\n", tmp->name, registrar); } else { tmp->next = *local_contexts; if (exttable) ast_hashtab_insert_immediate(exttable, tmp); /*put this context into the tree */ *local_contexts = tmp; ast_debug(1, "Registered context '%s'(%p) in local table %p; registrar: %s\n", tmp->name, tmp, exttable, registrar); ast_verb(3, "Registered extension context '%s'; registrar: %s\n", tmp->name, registrar); } return tmp; } void __ast_context_destroy(struct ast_context *list, struct ast_hashtab *contexttab, struct ast_context *con, const char *registrar); struct store_hint { char *context; char *exten; AST_LIST_HEAD_NOLOCK(, ast_state_cb) callbacks; int laststate; AST_LIST_ENTRY(store_hint) list; char data[1]; }; AST_LIST_HEAD_NOLOCK(store_hints, store_hint); static void context_merge_incls_swits_igps_other_registrars(struct ast_context *new, struct ast_context *old, const char *registrar) { struct ast_include *i; struct ast_ignorepat *ip; struct ast_sw *sw; ast_verb(3, "merging incls/swits/igpats from old(%s) to new(%s) context, registrar = %s\n", ast_get_context_name(old), ast_get_context_name(new), registrar); /* copy in the includes, switches, and ignorepats */ /* walk through includes */ for (i = NULL; (i = ast_walk_context_includes(old, i)) ; ) { if (strcmp(ast_get_include_registrar(i), registrar) == 0) continue; /* not mine */ ast_context_add_include2(new, ast_get_include_name(i), ast_get_include_registrar(i)); } /* walk through switches */ for (sw = NULL; (sw = ast_walk_context_switches(old, sw)) ; ) { if (strcmp(ast_get_switch_registrar(sw), registrar) == 0) continue; /* not mine */ ast_context_add_switch2(new, ast_get_switch_name(sw), ast_get_switch_data(sw), ast_get_switch_eval(sw), ast_get_switch_registrar(sw)); } /* walk thru ignorepats ... */ for (ip = NULL; (ip = ast_walk_context_ignorepats(old, ip)); ) { if (strcmp(ast_get_ignorepat_registrar(ip), registrar) == 0) continue; /* not mine */ ast_context_add_ignorepat2(new, ast_get_ignorepat_name(ip), ast_get_ignorepat_registrar(ip)); } } /* the purpose of this routine is to duplicate a context, with all its substructure, except for any extens that have a matching registrar */ static void context_merge(struct ast_context **extcontexts, struct ast_hashtab *exttable, struct ast_context *context, const char *registrar) { struct ast_context *new = ast_hashtab_lookup(exttable, context); /* is there a match in the new set? */ struct ast_exten *exten_item, *prio_item, *new_exten_item, *new_prio_item; struct ast_hashtab_iter *exten_iter; struct ast_hashtab_iter *prio_iter; int insert_count = 0; int first = 1; /* We'll traverse all the extensions/prios, and see which are not registrar'd with the current registrar, and copy them to the new context. If the new context does not exist, we'll create it "on demand". If no items are in this context to copy, then we'll only create the empty matching context if the old one meets the criteria */ if (context->root_table) { exten_iter = ast_hashtab_start_traversal(context->root_table); while ((exten_item=ast_hashtab_next(exten_iter))) { if (new) { new_exten_item = ast_hashtab_lookup(new->root_table, exten_item); } else { new_exten_item = NULL; } prio_iter = ast_hashtab_start_traversal(exten_item->peer_table); while ((prio_item=ast_hashtab_next(prio_iter))) { int res1; char *dupdstr; if (new_exten_item) { new_prio_item = ast_hashtab_lookup(new_exten_item->peer_table, prio_item); } else { new_prio_item = NULL; } if (strcmp(prio_item->registrar,registrar) == 0) { continue; } /* make sure the new context exists, so we have somewhere to stick this exten/prio */ if (!new) { new = ast_context_find_or_create(extcontexts, exttable, context->name, prio_item->registrar); /* a new context created via priority from a different context in the old dialplan, gets its registrar from the prio's registrar */ } /* copy in the includes, switches, and ignorepats */ if (first) { /* but, only need to do this once */ context_merge_incls_swits_igps_other_registrars(new, context, registrar); first = 0; } if (!new) { ast_log(LOG_ERROR,"Could not allocate a new context for %s in merge_and_delete! Danger!\n", context->name); ast_hashtab_end_traversal(prio_iter); ast_hashtab_end_traversal(exten_iter); return; /* no sense continuing. */ } /* we will not replace existing entries in the new context with stuff from the old context. but, if this is because of some sort of registrar conflict, we ought to say something... */ dupdstr = ast_strdup(prio_item->data); res1 = ast_add_extension2(new, 0, prio_item->exten, prio_item->priority, prio_item->label, prio_item->matchcid ? prio_item->cidmatch : NULL, prio_item->app, dupdstr, prio_item->datad, prio_item->registrar); if (!res1 && new_exten_item && new_prio_item){ ast_verb(3,"Dropping old dialplan item %s/%s/%d [%s(%s)] (registrar=%s) due to conflict with new dialplan\n", context->name, prio_item->exten, prio_item->priority, prio_item->app, (char*)prio_item->data, prio_item->registrar); } else { /* we do NOT pass the priority data from the old to the new -- we pass a copy of it, so no changes to the current dialplan take place, and no double frees take place, either! */ insert_count++; } } ast_hashtab_end_traversal(prio_iter); } ast_hashtab_end_traversal(exten_iter); } if (!insert_count && !new && (strcmp(context->registrar, registrar) != 0 || (strcmp(context->registrar, registrar) == 0 && context->refcount > 1))) { /* we could have given it the registrar of the other module who incremented the refcount, but that's not available, so we give it the registrar we know about */ new = ast_context_find_or_create(extcontexts, exttable, context->name, context->registrar); /* copy in the includes, switches, and ignorepats */ context_merge_incls_swits_igps_other_registrars(new, context, registrar); } } /* XXX this does not check that multiple contexts are merged */ void ast_merge_contexts_and_delete(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *registrar) { double ft; struct ast_context *tmp; struct ast_context *oldcontextslist; struct ast_hashtab *oldtable; struct store_hints hints_stored = AST_LIST_HEAD_NOLOCK_INIT_VALUE; struct store_hints hints_removed = AST_LIST_HEAD_NOLOCK_INIT_VALUE; struct store_hint *saved_hint; struct ast_hint *hint; struct ast_exten *exten; int length; struct ast_state_cb *thiscb; struct ast_hashtab_iter *iter; struct ao2_iterator i; struct timeval begintime; struct timeval writelocktime; struct timeval endlocktime; struct timeval enddeltime; /* * It is very important that this function hold the hints * container lock _and_ the conlock during its operation; not * only do we need to ensure that the list of contexts and * extensions does not change, but also that no hint callbacks * (watchers) are added or removed during the merge/delete * process * * In addition, the locks _must_ be taken in this order, because * there are already other code paths that use this order */ begintime = ast_tvnow(); ast_mutex_lock(&context_merge_lock);/* Serialize ast_merge_contexts_and_delete */ ast_wrlock_contexts(); iter = ast_hashtab_start_traversal(contexts_table); while ((tmp = ast_hashtab_next(iter))) { context_merge(extcontexts, exttable, tmp, registrar); } ast_hashtab_end_traversal(iter); ao2_lock(hints); writelocktime = ast_tvnow(); /* preserve all watchers for hints */ i = ao2_iterator_init(hints, AO2_ITERATOR_DONTLOCK); for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) { if (ao2_container_count(hint->callbacks)) { ao2_lock(hint); if (!hint->exten) { /* The extension has already been destroyed. (Should never happen here) */ ao2_unlock(hint); continue; } length = strlen(hint->exten->exten) + strlen(hint->exten->parent->name) + 2 + sizeof(*saved_hint); if (!(saved_hint = ast_calloc(1, length))) { ao2_unlock(hint); continue; } /* This removes all the callbacks from the hint into saved_hint. */ while ((thiscb = ao2_callback(hint->callbacks, OBJ_UNLINK, NULL, NULL))) { AST_LIST_INSERT_TAIL(&saved_hint->callbacks, thiscb, entry); /* * We intentionally do not unref thiscb to account for the * non-ao2 reference in saved_hint->callbacks */ } saved_hint->laststate = hint->laststate; saved_hint->context = saved_hint->data; strcpy(saved_hint->data, hint->exten->parent->name); saved_hint->exten = saved_hint->data + strlen(saved_hint->context) + 1; strcpy(saved_hint->exten, hint->exten->exten); ao2_unlock(hint); AST_LIST_INSERT_HEAD(&hints_stored, saved_hint, list); } } ao2_iterator_destroy(&i); /* save the old table and list */ oldtable = contexts_table; oldcontextslist = contexts; /* move in the new table and list */ contexts_table = exttable; contexts = *extcontexts; /* * Restore the watchers for hints that can be found; notify * those that cannot be restored. */ while ((saved_hint = AST_LIST_REMOVE_HEAD(&hints_stored, list))) { struct pbx_find_info q = { .stacklen = 0 }; exten = pbx_find_extension(NULL, NULL, &q, saved_hint->context, saved_hint->exten, PRIORITY_HINT, NULL, "", E_MATCH); /* * If this is a pattern, dynamically create a new extension for this * particular match. Note that this will only happen once for each * individual extension, because the pattern will no longer match first. */ if (exten && exten->exten[0] == '_') { ast_add_extension_nolock(exten->parent->name, 0, saved_hint->exten, PRIORITY_HINT, NULL, 0, exten->app, ast_strdup(exten->data), ast_free_ptr, exten->registrar); /* rwlocks are not recursive locks */ exten = ast_hint_extension_nolock(NULL, saved_hint->context, saved_hint->exten); } /* Find the hint in the hints container */ hint = exten ? ao2_find(hints, exten, 0) : NULL; if (!hint) { /* * Notify watchers of this removed hint later when we aren't * encumberd by so many locks. */ AST_LIST_INSERT_HEAD(&hints_removed, saved_hint, list); } else { ao2_lock(hint); while ((thiscb = AST_LIST_REMOVE_HEAD(&saved_hint->callbacks, entry))) { ao2_link(hint->callbacks, thiscb); /* Ref that we added when putting into saved_hint->callbacks */ ao2_ref(thiscb, -1); } hint->laststate = saved_hint->laststate; ao2_unlock(hint); ao2_ref(hint, -1); ast_free(saved_hint); } } ao2_unlock(hints); ast_unlock_contexts(); /* * Notify watchers of all removed hints with the same lock * environment as handle_statechange(). */ while ((saved_hint = AST_LIST_REMOVE_HEAD(&hints_removed, list))) { /* this hint has been removed, notify the watchers */ while ((thiscb = AST_LIST_REMOVE_HEAD(&saved_hint->callbacks, entry))) { thiscb->change_cb(saved_hint->context, saved_hint->exten, AST_EXTENSION_REMOVED, thiscb->data); /* Ref that we added when putting into saved_hint->callbacks */ ao2_ref(thiscb, -1); } ast_free(saved_hint); } ast_mutex_unlock(&context_merge_lock); endlocktime = ast_tvnow(); /* * The old list and hashtab no longer are relevant, delete them * while the rest of asterisk is now freely using the new stuff * instead. */ ast_hashtab_destroy(oldtable, NULL); for (tmp = oldcontextslist; tmp; ) { struct ast_context *next; /* next starting point */ next = tmp->next; __ast_internal_context_destroy(tmp); tmp = next; } enddeltime = ast_tvnow(); ft = ast_tvdiff_us(writelocktime, begintime); ft /= 1000000.0; ast_verb(3,"Time to scan old dialplan and merge leftovers back into the new: %8.6f sec\n", ft); ft = ast_tvdiff_us(endlocktime, writelocktime); ft /= 1000000.0; ast_verb(3,"Time to restore hints and swap in new dialplan: %8.6f sec\n", ft); ft = ast_tvdiff_us(enddeltime, endlocktime); ft /= 1000000.0; ast_verb(3,"Time to delete the old dialplan: %8.6f sec\n", ft); ft = ast_tvdiff_us(enddeltime, begintime); ft /= 1000000.0; ast_verb(3,"Total time merge_contexts_delete: %8.6f sec\n", ft); } /* * errno values * EBUSY - can't lock * ENOENT - no existence of context */ int ast_context_add_include(const char *context, const char *include, const char *registrar) { int ret = -1; struct ast_context *c; c = find_context_locked(context); if (c) { ret = ast_context_add_include2(c, include, registrar); ast_unlock_contexts(); } return ret; } /*! \brief Helper for get_range. * return the index of the matching entry, starting from 1. * If names is not supplied, try numeric values. */ static int lookup_name(const char *s, const char * const names[], int max) { int i; if (names && *s > '9') { for (i = 0; names[i]; i++) { if (!strcasecmp(s, names[i])) { return i; } } } /* Allow months and weekdays to be specified as numbers, as well */ if (sscanf(s, "%2d", &i) == 1 && i >= 1 && i <= max) { /* What the array offset would have been: "1" would be at offset 0 */ return i - 1; } return -1; /* error return */ } /*! \brief helper function to return a range up to max (7, 12, 31 respectively). * names, if supplied, is an array of names that should be mapped to numbers. */ static unsigned get_range(char *src, int max, const char * const names[], const char *msg) { int start, end; /* start and ending position */ unsigned int mask = 0; char *part; /* Check for whole range */ if (ast_strlen_zero(src) || !strcmp(src, "*")) { return (1 << max) - 1; } while ((part = strsep(&src, "&"))) { /* Get start and ending position */ char *endpart = strchr(part, '-'); if (endpart) { *endpart++ = '\0'; } /* Find the start */ if ((start = lookup_name(part, names, max)) < 0) { ast_log(LOG_WARNING, "Invalid %s '%s', skipping element\n", msg, part); continue; } if (endpart) { /* find end of range */ if ((end = lookup_name(endpart, names, max)) < 0) { ast_log(LOG_WARNING, "Invalid end %s '%s', skipping element\n", msg, endpart); continue; } } else { end = start; } /* Fill the mask. Remember that ranges are cyclic */ mask |= (1 << end); /* initialize with last element */ while (start != end) { mask |= (1 << start); if (++start >= max) { start = 0; } } } return mask; } /*! \brief store a bitmask of valid times, one bit each 1 minute */ static void get_timerange(struct ast_timing *i, char *times) { char *endpart, *part; int x; int st_h, st_m; int endh, endm; int minute_start, minute_end; /* start disabling all times, fill the fields with 0's, as they may contain garbage */ memset(i->minmask, 0, sizeof(i->minmask)); /* 1-minute per bit */ /* Star is all times */ if (ast_strlen_zero(times) || !strcmp(times, "*")) { /* 48, because each hour takes 2 integers; 30 bits each */ for (x = 0; x < 48; x++) { i->minmask[x] = 0x3fffffff; /* 30 bits */ } return; } /* Otherwise expect a range */ while ((part = strsep(&times, "&"))) { if (!(endpart = strchr(part, '-'))) { if (sscanf(part, "%2d:%2d", &st_h, &st_m) != 2 || st_h < 0 || st_h > 23 || st_m < 0 || st_m > 59) { ast_log(LOG_WARNING, "%s isn't a valid time.\n", part); continue; } i->minmask[st_h * 2 + (st_m >= 30 ? 1 : 0)] |= (1 << (st_m % 30)); continue; } *endpart++ = '\0'; /* why skip non digits? Mostly to skip spaces */ while (*endpart && !isdigit(*endpart)) { endpart++; } if (!*endpart) { ast_log(LOG_WARNING, "Invalid time range starting with '%s-'.\n", part); continue; } if (sscanf(part, "%2d:%2d", &st_h, &st_m) != 2 || st_h < 0 || st_h > 23 || st_m < 0 || st_m > 59) { ast_log(LOG_WARNING, "'%s' isn't a valid start time.\n", part); continue; } if (sscanf(endpart, "%2d:%2d", &endh, &endm) != 2 || endh < 0 || endh > 23 || endm < 0 || endm > 59) { ast_log(LOG_WARNING, "'%s' isn't a valid end time.\n", endpart); continue; } minute_start = st_h * 60 + st_m; minute_end = endh * 60 + endm; /* Go through the time and enable each appropriate bit */ for (x = minute_start; x != minute_end; x = (x + 1) % (24 * 60)) { i->minmask[x / 30] |= (1 << (x % 30)); } /* Do the last one */ i->minmask[x / 30] |= (1 << (x % 30)); } /* All done */ return; } static const char * const days[] = { "sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL, }; static const char * const months[] = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", NULL, }; int ast_build_timing(struct ast_timing *i, const char *info_in) { char *info; int j, num_fields, last_sep = -1; /* Check for empty just in case */ if (ast_strlen_zero(info_in)) { return 0; } /* make a copy just in case we were passed a static string */ info = ast_strdupa(info_in); /* count the number of fields in the timespec */ for (j = 0, num_fields = 1; info[j] != '\0'; j++) { if (info[j] == ',') { last_sep = j; num_fields++; } } /* save the timezone, if it is specified */ if (num_fields == 5) { i->timezone = ast_strdup(info + last_sep + 1); } else { i->timezone = NULL; } /* Assume everything except time */ i->monthmask = 0xfff; /* 12 bits */ i->daymask = 0x7fffffffU; /* 31 bits */ i->dowmask = 0x7f; /* 7 bits */ /* on each call, use strsep() to move info to the next argument */ get_timerange(i, strsep(&info, "|,")); if (info) i->dowmask = get_range(strsep(&info, "|,"), 7, days, "day of week"); if (info) i->daymask = get_range(strsep(&info, "|,"), 31, NULL, "day"); if (info) i->monthmask = get_range(strsep(&info, "|,"), 12, months, "month"); return 1; } int ast_check_timing(const struct ast_timing *i) { return ast_check_timing2(i, ast_tvnow()); } int ast_check_timing2(const struct ast_timing *i, const struct timeval tv) { struct ast_tm tm; ast_localtime(&tv, &tm, i->timezone); /* If it's not the right month, return */ if (!(i->monthmask & (1 << tm.tm_mon))) return 0; /* If it's not that time of the month.... */ /* Warning, tm_mday has range 1..31! */ if (!(i->daymask & (1 << (tm.tm_mday-1)))) return 0; /* If it's not the right day of the week */ if (!(i->dowmask & (1 << tm.tm_wday))) return 0; /* Sanity check the hour just to be safe */ if ((tm.tm_hour < 0) || (tm.tm_hour > 23)) { ast_log(LOG_WARNING, "Insane time...\n"); return 0; } /* Now the tough part, we calculate if it fits in the right time based on min/hour */ if (!(i->minmask[tm.tm_hour * 2 + (tm.tm_min >= 30 ? 1 : 0)] & (1 << (tm.tm_min >= 30 ? tm.tm_min - 30 : tm.tm_min)))) return 0; /* If we got this far, then we're good */ return 1; } int ast_destroy_timing(struct ast_timing *i) { if (i->timezone) { ast_free(i->timezone); i->timezone = NULL; } return 0; } /* * errno values * ENOMEM - out of memory * EBUSY - can't lock * EEXIST - already included * EINVAL - there is no existence of context for inclusion */ int ast_context_add_include2(struct ast_context *con, const char *value, const char *registrar) { struct ast_include *new_include; char *c; struct ast_include *i, *il = NULL; /* include, include_last */ int length; char *p; length = sizeof(struct ast_include); length += 2 * (strlen(value) + 1); /* allocate new include structure ... */ if (!(new_include = ast_calloc(1, length))) return -1; /* Fill in this structure. Use 'p' for assignments, as the fields * in the structure are 'const char *' */ p = new_include->stuff; new_include->name = p; strcpy(p, value); p += strlen(value) + 1; new_include->rname = p; strcpy(p, value); /* Strip off timing info, and process if it is there */ if ( (c = strchr(p, ',')) ) { *c++ = '\0'; new_include->hastime = ast_build_timing(&(new_include->timing), c); } new_include->next = NULL; new_include->registrar = registrar; ast_wrlock_context(con); /* ... go to last include and check if context is already included too... */ for (i = con->includes; i; i = i->next) { if (!strcasecmp(i->name, new_include->name)) { ast_destroy_timing(&(new_include->timing)); ast_free(new_include); ast_unlock_context(con); errno = EEXIST; return -1; } il = i; } /* ... include new context into context list, unlock, return */ if (il) il->next = new_include; else con->includes = new_include; ast_verb(3, "Including context '%s' in context '%s'\n", new_include->name, ast_get_context_name(con)); ast_unlock_context(con); return 0; } /* * errno values * EBUSY - can't lock * ENOENT - no existence of context */ int ast_context_add_switch(const char *context, const char *sw, const char *data, int eval, const char *registrar) { int ret = -1; struct ast_context *c; c = find_context_locked(context); if (c) { /* found, add switch to this context */ ret = ast_context_add_switch2(c, sw, data, eval, registrar); ast_unlock_contexts(); } return ret; } /* * errno values * ENOMEM - out of memory * EBUSY - can't lock * EEXIST - already included * EINVAL - there is no existence of context for inclusion */ int ast_context_add_switch2(struct ast_context *con, const char *value, const char *data, int eval, const char *registrar) { struct ast_sw *new_sw; struct ast_sw *i; int length; char *p; length = sizeof(struct ast_sw); length += strlen(value) + 1; if (data) length += strlen(data); length++; /* allocate new sw structure ... */ if (!(new_sw = ast_calloc(1, length))) return -1; /* ... fill in this structure ... */ p = new_sw->stuff; new_sw->name = p; strcpy(new_sw->name, value); p += strlen(value) + 1; new_sw->data = p; if (data) { strcpy(new_sw->data, data); p += strlen(data) + 1; } else { strcpy(new_sw->data, ""); p++; } new_sw->eval = eval; new_sw->registrar = registrar; /* ... try to lock this context ... */ ast_wrlock_context(con); /* ... go to last sw and check if context is already swd too... */ AST_LIST_TRAVERSE(&con->alts, i, list) { if (!strcasecmp(i->name, new_sw->name) && !strcasecmp(i->data, new_sw->data)) { ast_free(new_sw); ast_unlock_context(con); errno = EEXIST; return -1; } } /* ... sw new context into context list, unlock, return */ AST_LIST_INSERT_TAIL(&con->alts, new_sw, list); ast_verb(3, "Including switch '%s/%s' in context '%s'\n", new_sw->name, new_sw->data, ast_get_context_name(con)); ast_unlock_context(con); return 0; } /* * EBUSY - can't lock * ENOENT - there is not context existence */ int ast_context_remove_ignorepat(const char *context, const char *ignorepat, const char *registrar) { int ret = -1; struct ast_context *c; c = find_context_locked(context); if (c) { ret = ast_context_remove_ignorepat2(c, ignorepat, registrar); ast_unlock_contexts(); } return ret; } int ast_context_remove_ignorepat2(struct ast_context *con, const char *ignorepat, const char *registrar) { struct ast_ignorepat *ip, *ipl = NULL; ast_wrlock_context(con); for (ip = con->ignorepats; ip; ip = ip->next) { if (!strcmp(ip->pattern, ignorepat) && (!registrar || (registrar == ip->registrar))) { if (ipl) { ipl->next = ip->next; ast_free(ip); } else { con->ignorepats = ip->next; ast_free(ip); } ast_unlock_context(con); return 0; } ipl = ip; } ast_unlock_context(con); errno = EINVAL; return -1; } /* * EBUSY - can't lock * ENOENT - there is no existence of context */ int ast_context_add_ignorepat(const char *context, const char *value, const char *registrar) { int ret = -1; struct ast_context *c; c = find_context_locked(context); if (c) { ret = ast_context_add_ignorepat2(c, value, registrar); ast_unlock_contexts(); } return ret; } int ast_context_add_ignorepat2(struct ast_context *con, const char *value, const char *registrar) { struct ast_ignorepat *ignorepat, *ignorepatc, *ignorepatl = NULL; int length; char *pattern; length = sizeof(struct ast_ignorepat); length += strlen(value) + 1; if (!(ignorepat = ast_calloc(1, length))) return -1; /* The cast to char * is because we need to write the initial value. * The field is not supposed to be modified otherwise. Also, gcc 4.2 * sees the cast as dereferencing a type-punned pointer and warns about * it. This is the workaround (we're telling gcc, yes, that's really * what we wanted to do). */ pattern = (char *) ignorepat->pattern; strcpy(pattern, value); ignorepat->next = NULL; ignorepat->registrar = registrar; ast_wrlock_context(con); for (ignorepatc = con->ignorepats; ignorepatc; ignorepatc = ignorepatc->next) { ignorepatl = ignorepatc; if (!strcasecmp(ignorepatc->pattern, value)) { /* Already there */ ast_unlock_context(con); ast_free(ignorepat); errno = EEXIST; return -1; } } if (ignorepatl) ignorepatl->next = ignorepat; else con->ignorepats = ignorepat; ast_unlock_context(con); return 0; } int ast_ignore_pattern(const char *context, const char *pattern) { struct ast_context *con = ast_context_find(context); if (con) { struct ast_ignorepat *pat; for (pat = con->ignorepats; pat; pat = pat->next) { if (ast_extension_match(pat->pattern, pattern)) return 1; } } return 0; } /* * ast_add_extension_nolock -- use only in situations where the conlock is already held * ENOENT - no existence of context * */ static int ast_add_extension_nolock(const char *context, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void (*datad)(void *), const char *registrar) { int ret = -1; struct ast_context *c; c = find_context(context); if (c) { ret = ast_add_extension2_lockopt(c, replace, extension, priority, label, callerid, application, data, datad, registrar, 1); } return ret; } /* * EBUSY - can't lock * ENOENT - no existence of context * */ int ast_add_extension(const char *context, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void (*datad)(void *), const char *registrar) { int ret = -1; struct ast_context *c; c = find_context_locked(context); if (c) { ret = ast_add_extension2(c, replace, extension, priority, label, callerid, application, data, datad, registrar); ast_unlock_contexts(); } return ret; } int ast_explicit_goto(struct ast_channel *chan, const char *context, const char *exten, int priority) { if (!chan) return -1; ast_channel_lock(chan); if (!ast_strlen_zero(context)) ast_copy_string(chan->context, context, sizeof(chan->context)); if (!ast_strlen_zero(exten)) ast_copy_string(chan->exten, exten, sizeof(chan->exten)); if (priority > -1) { chan->priority = priority; /* see flag description in channel.h for explanation */ if (ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP)) chan->priority--; } ast_channel_unlock(chan); return 0; } int ast_async_goto(struct ast_channel *chan, const char *context, const char *exten, int priority) { int res = 0; struct ast_channel *tmpchan; struct { char *accountcode; char *exten; char *context; char *linkedid; char *name; struct ast_cdr *cdr; int amaflags; int state; format_t readformat; format_t writeformat; } tmpvars = { 0, }; ast_channel_lock(chan); if (chan->pbx) { /* This channel is currently in the PBX */ ast_explicit_goto(chan, context, exten, priority + 1); ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO); ast_channel_unlock(chan); return res; } /* In order to do it when the channel doesn't really exist within * the PBX, we have to make a new channel, masquerade, and start the PBX * at the new location */ tmpvars.accountcode = ast_strdupa(chan->accountcode); tmpvars.exten = ast_strdupa(chan->exten); tmpvars.context = ast_strdupa(chan->context); tmpvars.linkedid = ast_strdupa(chan->linkedid); tmpvars.name = ast_strdupa(chan->name); tmpvars.amaflags = chan->amaflags; tmpvars.state = chan->_state; tmpvars.writeformat = chan->writeformat; tmpvars.readformat = chan->readformat; tmpvars.cdr = chan->cdr ? ast_cdr_dup(chan->cdr) : NULL; ast_channel_unlock(chan); /* Do not hold any channel locks while calling channel_alloc() since the function * locks the channel container when linking the new channel in. */ if (!(tmpchan = ast_channel_alloc(0, tmpvars.state, 0, 0, tmpvars.accountcode, tmpvars.exten, tmpvars.context, tmpvars.linkedid, tmpvars.amaflags, "AsyncGoto/%s", tmpvars.name))) { ast_cdr_discard(tmpvars.cdr); return -1; } /* copy the cdr info over */ if (tmpvars.cdr) { ast_cdr_discard(tmpchan->cdr); tmpchan->cdr = tmpvars.cdr; tmpvars.cdr = NULL; } /* Make formats okay */ tmpchan->readformat = tmpvars.readformat; tmpchan->writeformat = tmpvars.writeformat; /* Setup proper location. Never hold another channel lock while calling this function. */ ast_explicit_goto(tmpchan, S_OR(context, tmpvars.context), S_OR(exten, tmpvars.exten), priority); /* Masquerade into tmp channel */ if (ast_channel_masquerade(tmpchan, chan)) { /* Failed to set up the masquerade. It's probably chan_local * in the middle of optimizing itself out. Sad. :( */ ast_hangup(tmpchan); tmpchan = NULL; res = -1; } else { ast_do_masquerade(tmpchan); /* Start the PBX going on our stolen channel */ if (ast_pbx_start(tmpchan)) { ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmpchan->name); ast_hangup(tmpchan); res = -1; } } return res; } int ast_async_goto_by_name(const char *channame, const char *context, const char *exten, int priority) { struct ast_channel *chan; int res = -1; if ((chan = ast_channel_get_by_name(channame))) { res = ast_async_goto(chan, context, exten, priority); chan = ast_channel_unref(chan); } return res; } /*! \brief copy a string skipping whitespace */ static int ext_strncpy(char *dst, const char *src, int len) { int count = 0; int insquares = 0; while (*src && (count < len - 1)) { if (*src == '[') { insquares = 1; } else if (*src == ']') { insquares = 0; } else if (*src == ' ' && !insquares) { src++; continue; } *dst = *src; dst++; src++; count++; } *dst = '\0'; return count; } /*! * \brief add the extension in the priority chain. * \retval 0 on success. * \retval -1 on failure. */ static int add_priority(struct ast_context *con, struct ast_exten *tmp, struct ast_exten *el, struct ast_exten *e, int replace) { struct ast_exten *ep; struct ast_exten *eh=e; int repeated_label = 0; /* Track if this label is a repeat, assume no. */ for (ep = NULL; e ; ep = e, e = e->peer) { if (e->label && tmp->label && e->priority != tmp->priority && !strcmp(e->label, tmp->label)) { if (strcmp(e->exten, tmp->exten)) { ast_log(LOG_WARNING, "Extension '%s' priority %d in '%s', label '%s' already in use at aliased extension '%s' priority %d\n", tmp->exten, tmp->priority, con->name, tmp->label, e->exten, e->priority); } else { ast_log(LOG_WARNING, "Extension '%s' priority %d in '%s', label '%s' already in use at priority %d\n", tmp->exten, tmp->priority, con->name, tmp->label, e->priority); } repeated_label = 1; } if (e->priority >= tmp->priority) { break; } } if (repeated_label) { /* Discard the label since it's a repeat. */ tmp->label = NULL; } if (!e) { /* go at the end, and ep is surely set because the list is not empty */ ast_hashtab_insert_safe(eh->peer_table, tmp); if (tmp->label) { ast_hashtab_insert_safe(eh->peer_label_table, tmp); } ep->peer = tmp; return 0; /* success */ } if (e->priority == tmp->priority) { /* Can't have something exactly the same. Is this a replacement? If so, replace, otherwise, bonk. */ if (!replace) { if (strcmp(e->exten, tmp->exten)) { ast_log(LOG_WARNING, "Unable to register extension '%s' priority %d in '%s', already in use by aliased extension '%s'\n", tmp->exten, tmp->priority, con->name, e->exten); } else { ast_log(LOG_WARNING, "Unable to register extension '%s' priority %d in '%s', already in use\n", tmp->exten, tmp->priority, con->name); } if (tmp->datad) { tmp->datad(tmp->data); /* if you free this, null it out */ tmp->data = NULL; } ast_free(tmp); return -1; } /* we are replacing e, so copy the link fields and then update * whoever pointed to e to point to us */ tmp->next = e->next; /* not meaningful if we are not first in the peer list */ tmp->peer = e->peer; /* always meaningful */ if (ep) { /* We're in the peer list, just insert ourselves */ ast_hashtab_remove_object_via_lookup(eh->peer_table,e); if (e->label) { ast_hashtab_remove_object_via_lookup(eh->peer_label_table,e); } ast_hashtab_insert_safe(eh->peer_table,tmp); if (tmp->label) { ast_hashtab_insert_safe(eh->peer_label_table,tmp); } ep->peer = tmp; } else if (el) { /* We're the first extension. Take over e's functions */ struct match_char *x = add_exten_to_pattern_tree(con, e, 1); tmp->peer_table = e->peer_table; tmp->peer_label_table = e->peer_label_table; ast_hashtab_remove_object_via_lookup(tmp->peer_table,e); ast_hashtab_insert_safe(tmp->peer_table,tmp); if (e->label) { ast_hashtab_remove_object_via_lookup(tmp->peer_label_table, e); } if (tmp->label) { ast_hashtab_insert_safe(tmp->peer_label_table, tmp); } ast_hashtab_remove_object_via_lookup(con->root_table, e); ast_hashtab_insert_safe(con->root_table, tmp); el->next = tmp; /* The pattern trie points to this exten; replace the pointer, and all will be well */ if (x) { /* if the trie isn't formed yet, don't sweat this */ if (x->exten) { /* this test for safety purposes */ x->exten = tmp; /* replace what would become a bad pointer */ } else { ast_log(LOG_ERROR,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n"); } } } else { /* We're the very first extension. */ struct match_char *x = add_exten_to_pattern_tree(con, e, 1); ast_hashtab_remove_object_via_lookup(con->root_table, e); ast_hashtab_insert_safe(con->root_table, tmp); tmp->peer_table = e->peer_table; tmp->peer_label_table = e->peer_label_table; ast_hashtab_remove_object_via_lookup(tmp->peer_table, e); ast_hashtab_insert_safe(tmp->peer_table, tmp); if (e->label) { ast_hashtab_remove_object_via_lookup(tmp->peer_label_table, e); } if (tmp->label) { ast_hashtab_insert_safe(tmp->peer_label_table, tmp); } ast_hashtab_remove_object_via_lookup(con->root_table, e); ast_hashtab_insert_safe(con->root_table, tmp); con->root = tmp; /* The pattern trie points to this exten; replace the pointer, and all will be well */ if (x) { /* if the trie isn't formed yet; no problem */ if (x->exten) { /* this test for safety purposes */ x->exten = tmp; /* replace what would become a bad pointer */ } else { ast_log(LOG_ERROR,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n"); } } } if (tmp->priority == PRIORITY_HINT) ast_change_hint(e,tmp); /* Destroy the old one */ if (e->datad) e->datad(e->data); ast_free(e); } else { /* Slip ourselves in just before e */ tmp->peer = e; tmp->next = e->next; /* extension chain, or NULL if e is not the first extension */ if (ep) { /* Easy enough, we're just in the peer list */ if (tmp->label) { ast_hashtab_insert_safe(eh->peer_label_table, tmp); } ast_hashtab_insert_safe(eh->peer_table, tmp); ep->peer = tmp; } else { /* we are the first in some peer list, so link in the ext list */ tmp->peer_table = e->peer_table; tmp->peer_label_table = e->peer_label_table; e->peer_table = 0; e->peer_label_table = 0; ast_hashtab_insert_safe(tmp->peer_table, tmp); if (tmp->label) { ast_hashtab_insert_safe(tmp->peer_label_table, tmp); } ast_hashtab_remove_object_via_lookup(con->root_table, e); ast_hashtab_insert_safe(con->root_table, tmp); if (el) el->next = tmp; /* in the middle... */ else con->root = tmp; /* ... or at the head */ e->next = NULL; /* e is no more at the head, so e->next must be reset */ } /* And immediately return success. */ if (tmp->priority == PRIORITY_HINT) { ast_add_hint(tmp); } } return 0; } /*! \brief * Main interface to add extensions to the list for out context. * * We sort extensions in order of matching preference, so that we can * stop the search as soon as we find a suitable match. * This ordering also takes care of wildcards such as '.' (meaning * "one or more of any character") and '!' (which is 'earlymatch', * meaning "zero or more of any character" but also impacts the * return value from CANMATCH and EARLYMATCH. * * The extension match rules defined in the devmeeting 2006.05.05 are * quite simple: WE SELECT THE LONGEST MATCH. * In detail, "longest" means the number of matched characters in * the extension. In case of ties (e.g. _XXX and 333) in the length * of a pattern, we give priority to entries with the smallest cardinality * (e.g, [5-9] comes before [2-8] before the former has only 5 elements, * while the latter has 7, etc. * In case of same cardinality, the first element in the range counts. * If we still have a tie, any final '!' will make this as a possibly * less specific pattern. * * EBUSY - can't lock * EEXIST - extension with the same priority exist and no replace is set * */ int ast_add_extension2(struct ast_context *con, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void (*datad)(void *), const char *registrar) { return ast_add_extension2_lockopt(con, replace, extension, priority, label, callerid, application, data, datad, registrar, 1); } /*! * \brief Same as ast_add_extension2() but controls the context locking. * * \details * Does all the work of ast_add_extension2, but adds an arg to * determine if context locking should be done. */ static int ast_add_extension2_lockopt(struct ast_context *con, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void (*datad)(void *), const char *registrar, int lock_context) { /* * Sort extensions (or patterns) according to the rules indicated above. * These are implemented by the function ext_cmp()). * All priorities for the same ext/pattern/cid are kept in a list, * using the 'peer' field as a link field.. */ struct ast_exten *tmp, *tmp2, *e, *el = NULL; int res; int length; char *p; char expand_buf[VAR_BUF_SIZE]; struct ast_exten dummy_exten = {0}; char dummy_name[1024]; if (ast_strlen_zero(extension)) { ast_log(LOG_ERROR,"You have to be kidding-- add exten '' to context %s? Figure out a name and call me back. Action ignored.\n", con->name); return -1; } /* If we are adding a hint evalulate in variables and global variables */ if (priority == PRIORITY_HINT && strstr(application, "${") && extension[0] != '_') { struct ast_channel *c = ast_dummy_channel_alloc(); if (c) { ast_copy_string(c->exten, extension, sizeof(c->exten)); ast_copy_string(c->context, con->name, sizeof(c->context)); } pbx_substitute_variables_helper(c, application, expand_buf, sizeof(expand_buf)); application = expand_buf; if (c) { ast_channel_unref(c); } } length = sizeof(struct ast_exten); length += strlen(extension) + 1; length += strlen(application) + 1; if (label) length += strlen(label) + 1; if (callerid) length += strlen(callerid) + 1; else length ++; /* just the '\0' */ /* Be optimistic: Build the extension structure first */ if (!(tmp = ast_calloc(1, length))) return -1; if (ast_strlen_zero(label)) /* let's turn empty labels to a null ptr */ label = 0; /* use p as dst in assignments, as the fields are const char * */ p = tmp->stuff; if (label) { tmp->label = p; strcpy(p, label); p += strlen(label) + 1; } tmp->exten = p; p += ext_strncpy(p, extension, strlen(extension) + 1) + 1; tmp->priority = priority; tmp->cidmatch = p; /* but use p for assignments below */ /* Blank callerid and NULL callerid are two SEPARATE things. Do NOT confuse the two!!! */ if (callerid) { p += ext_strncpy(p, callerid, strlen(callerid) + 1) + 1; tmp->matchcid = 1; } else { *p++ = '\0'; tmp->matchcid = 0; } tmp->app = p; strcpy(p, application); tmp->parent = con; tmp->data = data; tmp->datad = datad; tmp->registrar = registrar; if (lock_context) { ast_wrlock_context(con); } if (con->pattern_tree) { /* usually, on initial load, the pattern_tree isn't formed until the first find_exten; so if we are adding an extension, and the trie exists, then we need to incrementally add this pattern to it. */ ast_copy_string(dummy_name, extension, sizeof(dummy_name)); dummy_exten.exten = dummy_name; dummy_exten.matchcid = 0; dummy_exten.cidmatch = 0; tmp2 = ast_hashtab_lookup(con->root_table, &dummy_exten); if (!tmp2) { /* hmmm, not in the trie; */ add_exten_to_pattern_tree(con, tmp, 0); ast_hashtab_insert_safe(con->root_table, tmp); /* for the sake of completeness */ } } res = 0; /* some compilers will think it is uninitialized otherwise */ for (e = con->root; e; el = e, e = e->next) { /* scan the extension list */ res = ext_cmp(e->exten, tmp->exten); if (res == 0) { /* extension match, now look at cidmatch */ if (!e->matchcid && !tmp->matchcid) res = 0; else if (tmp->matchcid && !e->matchcid) res = 1; else if (e->matchcid && !tmp->matchcid) res = -1; else res = ext_cmp(e->cidmatch, tmp->cidmatch); } if (res >= 0) break; } if (e && res == 0) { /* exact match, insert in the priority chain */ res = add_priority(con, tmp, el, e, replace); if (lock_context) { ast_unlock_context(con); } if (res < 0) { errno = EEXIST; /* XXX do we care ? */ return 0; /* XXX should we return -1 maybe ? */ } } else { /* * not an exact match, this is the first entry with this pattern, * so insert in the main list right before 'e' (if any) */ tmp->next = e; if (el) { /* there is another exten already in this context */ el->next = tmp; tmp->peer_table = ast_hashtab_create(13, hashtab_compare_exten_numbers, ast_hashtab_resize_java, ast_hashtab_newsize_java, hashtab_hash_priority, 0); tmp->peer_label_table = ast_hashtab_create(7, hashtab_compare_exten_labels, ast_hashtab_resize_java, ast_hashtab_newsize_java, hashtab_hash_labels, 0); if (label) { ast_hashtab_insert_safe(tmp->peer_label_table, tmp); } ast_hashtab_insert_safe(tmp->peer_table, tmp); } else { /* this is the first exten in this context */ if (!con->root_table) con->root_table = ast_hashtab_create(27, hashtab_compare_extens, ast_hashtab_resize_java, ast_hashtab_newsize_java, hashtab_hash_extens, 0); con->root = tmp; con->root->peer_table = ast_hashtab_create(13, hashtab_compare_exten_numbers, ast_hashtab_resize_java, ast_hashtab_newsize_java, hashtab_hash_priority, 0); con->root->peer_label_table = ast_hashtab_create(7, hashtab_compare_exten_labels, ast_hashtab_resize_java, ast_hashtab_newsize_java, hashtab_hash_labels, 0); if (label) { ast_hashtab_insert_safe(con->root->peer_label_table, tmp); } ast_hashtab_insert_safe(con->root->peer_table, tmp); } ast_hashtab_insert_safe(con->root_table, tmp); if (lock_context) { ast_unlock_context(con); } if (tmp->priority == PRIORITY_HINT) { ast_add_hint(tmp); } } if (option_debug) { if (tmp->matchcid) { ast_debug(1, "Added extension '%s' priority %d (CID match '%s') to %s (%p)\n", tmp->exten, tmp->priority, tmp->cidmatch, con->name, con); } else { ast_debug(1, "Added extension '%s' priority %d to %s (%p)\n", tmp->exten, tmp->priority, con->name, con); } } if (tmp->matchcid) { ast_verb(3, "Added extension '%s' priority %d (CID match '%s') to %s\n", tmp->exten, tmp->priority, tmp->cidmatch, con->name); } else { ast_verb(3, "Added extension '%s' priority %d to %s\n", tmp->exten, tmp->priority, con->name); } return 0; } struct async_stat { pthread_t p; struct ast_channel *chan; char context[AST_MAX_CONTEXT]; char exten[AST_MAX_EXTENSION]; int priority; int timeout; char app[AST_MAX_EXTENSION]; char appdata[1024]; }; static void *async_wait(void *data) { struct async_stat *as = data; struct ast_channel *chan = as->chan; int timeout = as->timeout; int res; struct ast_frame *f; struct ast_app *app; struct timeval start = ast_tvnow(); int ms; while ((ms = ast_remaining_ms(start, timeout)) && chan->_state != AST_STATE_UP) { res = ast_waitfor(chan, ms); if (res < 1) break; f = ast_read(chan); if (!f) break; if (f->frametype == AST_FRAME_CONTROL) { if ((f->subclass.integer == AST_CONTROL_BUSY) || (f->subclass.integer == AST_CONTROL_CONGESTION) ) { ast_frfree(f); break; } } ast_frfree(f); } if (chan->_state == AST_STATE_UP) { if (!ast_strlen_zero(as->app)) { app = pbx_findapp(as->app); if (app) { ast_verb(3, "Launching %s(%s) on %s\n", as->app, as->appdata, chan->name); pbx_exec(chan, app, as->appdata); } else ast_log(LOG_WARNING, "No such application '%s'\n", as->app); } else { if (!ast_strlen_zero(as->context)) ast_copy_string(chan->context, as->context, sizeof(chan->context)); if (!ast_strlen_zero(as->exten)) ast_copy_string(chan->exten, as->exten, sizeof(chan->exten)); if (as->priority > 0) chan->priority = as->priority; /* Run the PBX */ if (ast_pbx_run(chan)) { ast_log(LOG_ERROR, "Failed to start PBX on %s\n", chan->name); } else { /* PBX will have taken care of this */ chan = NULL; } } } ast_free(as); if (chan) ast_hangup(chan); return NULL; } /*! * \brief Function to post an empty cdr after a spool call fails. * \note This function posts an empty cdr for a failed spool call */ static int ast_pbx_outgoing_cdr_failed(void) { /* allocate a channel */ struct ast_channel *chan = ast_dummy_channel_alloc(); if (!chan) return -1; /* failure */ chan->cdr = ast_cdr_alloc(); if (!chan->cdr) { /* allocation of the cdr failed */ chan = ast_channel_unref(chan); /* free the channel */ return -1; /* return failure */ } /* allocation of the cdr was successful */ ast_cdr_init(chan->cdr, chan); /* initialize our channel's cdr */ ast_cdr_start(chan->cdr); /* record the start and stop time */ ast_cdr_end(chan->cdr); ast_cdr_failed(chan->cdr); /* set the status to failed */ ast_cdr_detach(chan->cdr); /* post and free the record */ chan->cdr = NULL; chan = ast_channel_unref(chan); /* free the channel */ return 0; /* success */ } int ast_pbx_outgoing_exten(const char *type, format_t format, void *data, int timeout, const char *context, const char *exten, int priority, int *reason, int synchronous, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **channel) { struct ast_channel *chan; struct async_stat *as; int res = -1, cdr_res = -1; struct outgoing_helper oh; if (synchronous) { oh.context = context; oh.exten = exten; oh.priority = priority; oh.cid_num = cid_num; oh.cid_name = cid_name; oh.account = account; oh.vars = vars; oh.parent_channel = NULL; chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh); if (channel) { *channel = chan; if (chan) ast_channel_lock(chan); } if (chan) { if (chan->_state == AST_STATE_UP) { res = 0; ast_verb(4, "Channel %s was answered.\n", chan->name); if (synchronous > 1) { if (channel) ast_channel_unlock(chan); if (ast_pbx_run(chan)) { ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name); if (channel) *channel = NULL; ast_hangup(chan); chan = NULL; res = -1; } } else { if (ast_pbx_start(chan)) { ast_log(LOG_ERROR, "Unable to start PBX on %s\n", chan->name); if (channel) { *channel = NULL; ast_channel_unlock(chan); } ast_hangup(chan); res = -1; } chan = NULL; } } else { ast_verb(4, "Channel %s was never answered.\n", chan->name); if (chan->cdr) { /* update the cdr */ /* here we update the status of the call, which sould be busy. * if that fails then we set the status to failed */ if (ast_cdr_disposition(chan->cdr, chan->hangupcause)) ast_cdr_failed(chan->cdr); } if (channel) { *channel = NULL; ast_channel_unlock(chan); } ast_hangup(chan); chan = NULL; } } if (res < 0) { /* the call failed for some reason */ if (*reason == 0) { /* if the call failed (not busy or no answer) * update the cdr with the failed message */ cdr_res = ast_pbx_outgoing_cdr_failed(); if (cdr_res != 0) { res = cdr_res; goto outgoing_exten_cleanup; } } /* create a fake channel and execute the "failed" extension (if it exists) within the requested context */ /* check if "failed" exists */ if (ast_exists_extension(chan, context, "failed", 1, NULL)) { chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", NULL, 0, "OutgoingSpoolFailed"); if (chan) { char failed_reason[4] = ""; if (!ast_strlen_zero(context)) ast_copy_string(chan->context, context, sizeof(chan->context)); set_ext_pri(chan, "failed", 1); ast_set_variables(chan, vars); snprintf(failed_reason, sizeof(failed_reason), "%d", *reason); pbx_builtin_setvar_helper(chan, "REASON", failed_reason); if (account) ast_cdr_setaccount(chan, account); if (ast_pbx_run(chan)) { ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name); ast_hangup(chan); } chan = NULL; } } } } else { if (!(as = ast_calloc(1, sizeof(*as)))) { res = -1; goto outgoing_exten_cleanup; } chan = ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name); if (channel) { *channel = chan; if (chan) ast_channel_lock(chan); } if (!chan) { ast_free(as); res = -1; goto outgoing_exten_cleanup; } as->chan = chan; ast_copy_string(as->context, context, sizeof(as->context)); set_ext_pri(as->chan, exten, priority); as->timeout = timeout; ast_set_variables(chan, vars); if (account) ast_cdr_setaccount(chan, account); if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) { ast_log(LOG_WARNING, "Failed to start async wait\n"); ast_free(as); if (channel) { *channel = NULL; ast_channel_unlock(chan); } ast_hangup(chan); res = -1; goto outgoing_exten_cleanup; } res = 0; } outgoing_exten_cleanup: ast_variables_destroy(vars); return res; } struct app_tmp { struct ast_channel *chan; pthread_t t; AST_DECLARE_STRING_FIELDS ( AST_STRING_FIELD(app); AST_STRING_FIELD(data); ); }; /*! \brief run the application and free the descriptor once done */ static void *ast_pbx_run_app(void *data) { struct app_tmp *tmp = data; struct ast_app *app; app = pbx_findapp(tmp->app); if (app) { ast_verb(4, "Launching %s(%s) on %s\n", tmp->app, tmp->data, tmp->chan->name); pbx_exec(tmp->chan, app, tmp->data); } else ast_log(LOG_WARNING, "No such application '%s'\n", tmp->app); ast_hangup(tmp->chan); ast_string_field_free_memory(tmp); ast_free(tmp); return NULL; } int ast_pbx_outgoing_app(const char *type, format_t format, void *data, int timeout, const char *app, const char *appdata, int *reason, int synchronous, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **locked_channel) { struct ast_channel *chan; struct app_tmp *tmp; int res = -1, cdr_res = -1; struct outgoing_helper oh; memset(&oh, 0, sizeof(oh)); oh.vars = vars; oh.account = account; if (locked_channel) *locked_channel = NULL; if (ast_strlen_zero(app)) { res = -1; goto outgoing_app_cleanup; } if (synchronous) { chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh); if (chan) { ast_set_variables(chan, vars); if (account) ast_cdr_setaccount(chan, account); if (chan->_state == AST_STATE_UP) { res = 0; ast_verb(4, "Channel %s was answered.\n", chan->name); tmp = ast_calloc(1, sizeof(*tmp)); if (!tmp || ast_string_field_init(tmp, 252)) { if (tmp) { ast_free(tmp); } res = -1; } else { ast_string_field_set(tmp, app, app); ast_string_field_set(tmp, data, appdata); tmp->chan = chan; if (synchronous > 1) { if (locked_channel) ast_channel_unlock(chan); ast_pbx_run_app(tmp); } else { if (locked_channel) ast_channel_lock(chan); if (ast_pthread_create_detached(&tmp->t, NULL, ast_pbx_run_app, tmp)) { ast_log(LOG_WARNING, "Unable to spawn execute thread on %s: %s\n", chan->name, strerror(errno)); ast_string_field_free_memory(tmp); ast_free(tmp); if (locked_channel) ast_channel_unlock(chan); ast_hangup(chan); res = -1; } else { if (locked_channel) *locked_channel = chan; } } } } else { ast_verb(4, "Channel %s was never answered.\n", chan->name); if (chan->cdr) { /* update the cdr */ /* here we update the status of the call, which sould be busy. * if that fails then we set the status to failed */ if (ast_cdr_disposition(chan->cdr, chan->hangupcause)) ast_cdr_failed(chan->cdr); } ast_hangup(chan); } } if (res < 0) { /* the call failed for some reason */ if (*reason == 0) { /* if the call failed (not busy or no answer) * update the cdr with the failed message */ cdr_res = ast_pbx_outgoing_cdr_failed(); if (cdr_res != 0) { res = cdr_res; goto outgoing_app_cleanup; } } } } else { struct async_stat *as; if (!(as = ast_calloc(1, sizeof(*as)))) { res = -1; goto outgoing_app_cleanup; } chan = __ast_request_and_dial(type, format, NULL, data, timeout, reason, cid_num, cid_name, &oh); if (!chan) { ast_free(as); res = -1; goto outgoing_app_cleanup; } as->chan = chan; ast_copy_string(as->app, app, sizeof(as->app)); if (appdata) ast_copy_string(as->appdata, appdata, sizeof(as->appdata)); as->timeout = timeout; ast_set_variables(chan, vars); if (account) ast_cdr_setaccount(chan, account); /* Start a new thread, and get something handling this channel. */ if (locked_channel) ast_channel_lock(chan); if (ast_pthread_create_detached(&as->p, NULL, async_wait, as)) { ast_log(LOG_WARNING, "Failed to start async wait\n"); ast_free(as); if (locked_channel) ast_channel_unlock(chan); ast_hangup(chan); res = -1; goto outgoing_app_cleanup; } else { if (locked_channel) *locked_channel = chan; } res = 0; } outgoing_app_cleanup: ast_variables_destroy(vars); return res; } /* this is the guts of destroying a context -- freeing up the structure, traversing and destroying the extensions, switches, ignorepats, includes, etc. etc. */ static void __ast_internal_context_destroy( struct ast_context *con) { struct ast_include *tmpi; struct ast_sw *sw; struct ast_exten *e, *el, *en; struct ast_ignorepat *ipi; struct ast_context *tmp = con; for (tmpi = tmp->includes; tmpi; ) { /* Free includes */ struct ast_include *tmpil = tmpi; tmpi = tmpi->next; ast_free(tmpil); } for (ipi = tmp->ignorepats; ipi; ) { /* Free ignorepats */ struct ast_ignorepat *ipl = ipi; ipi = ipi->next; ast_free(ipl); } if (tmp->registrar) ast_free(tmp->registrar); /* destroy the hash tabs */ if (tmp->root_table) { ast_hashtab_destroy(tmp->root_table, 0); } /* and destroy the pattern tree */ if (tmp->pattern_tree) destroy_pattern_tree(tmp->pattern_tree); while ((sw = AST_LIST_REMOVE_HEAD(&tmp->alts, list))) ast_free(sw); for (e = tmp->root; e;) { for (en = e->peer; en;) { el = en; en = en->peer; destroy_exten(el); } el = e; e = e->next; destroy_exten(el); } tmp->root = NULL; ast_rwlock_destroy(&tmp->lock); ast_mutex_destroy(&tmp->macrolock); ast_free(tmp); } void __ast_context_destroy(struct ast_context *list, struct ast_hashtab *contexttab, struct ast_context *con, const char *registrar) { struct ast_context *tmp, *tmpl=NULL; struct ast_exten *exten_item, *prio_item; for (tmp = list; tmp; ) { struct ast_context *next = NULL; /* next starting point */ /* The following code used to skip forward to the next context with matching registrar, but this didn't make sense; individual priorities registrar'd to the matching registrar could occur in any context! */ ast_debug(1, "Investigate ctx %s %s\n", tmp->name, tmp->registrar); if (con) { for (; tmp; tmpl = tmp, tmp = tmp->next) { /* skip to the matching context */ ast_debug(1, "check ctx %s %s\n", tmp->name, tmp->registrar); if ( !strcasecmp(tmp->name, con->name) ) { break; /* found it */ } } } if (!tmp) /* not found, we are done */ break; ast_wrlock_context(tmp); if (registrar) { /* then search thru and remove any extens that match registrar. */ struct ast_hashtab_iter *exten_iter; struct ast_hashtab_iter *prio_iter; struct ast_ignorepat *ip, *ipl = NULL, *ipn = NULL; struct ast_include *i, *pi = NULL, *ni = NULL; struct ast_sw *sw = NULL; /* remove any ignorepats whose registrar matches */ for (ip = tmp->ignorepats; ip; ip = ipn) { ipn = ip->next; if (!strcmp(ip->registrar, registrar)) { if (ipl) { ipl->next = ip->next; ast_free(ip); continue; /* don't change ipl */ } else { tmp->ignorepats = ip->next; ast_free(ip); continue; /* don't change ipl */ } } ipl = ip; } /* remove any includes whose registrar matches */ for (i = tmp->includes; i; i = ni) { ni = i->next; if (strcmp(i->registrar, registrar) == 0) { /* remove from list */ if (pi) { pi->next = i->next; /* free include */ ast_free(i); continue; /* don't change pi */ } else { tmp->includes = i->next; /* free include */ ast_free(i); continue; /* don't change pi */ } } pi = i; } /* remove any switches whose registrar matches */ AST_LIST_TRAVERSE_SAFE_BEGIN(&tmp->alts, sw, list) { if (strcmp(sw->registrar,registrar) == 0) { AST_LIST_REMOVE_CURRENT(list); ast_free(sw); } } AST_LIST_TRAVERSE_SAFE_END; if (tmp->root_table) { /* it is entirely possible that the context is EMPTY */ exten_iter = ast_hashtab_start_traversal(tmp->root_table); while ((exten_item=ast_hashtab_next(exten_iter))) { int end_traversal = 1; prio_iter = ast_hashtab_start_traversal(exten_item->peer_table); while ((prio_item=ast_hashtab_next(prio_iter))) { char extension[AST_MAX_EXTENSION]; char cidmatch[AST_MAX_EXTENSION]; if (!prio_item->registrar || strcmp(prio_item->registrar, registrar) != 0) { continue; } ast_verb(3, "Remove %s/%s/%d, registrar=%s; con=%s(%p); con->root=%p\n", tmp->name, prio_item->exten, prio_item->priority, registrar, con? con->name : "<nil>", con, con? con->root_table: NULL); /* set matchcid to 1 to insure we get a direct match, and NULL registrar to make sure no wildcarding is done */ ast_copy_string(extension, prio_item->exten, sizeof(extension)); if (prio_item->cidmatch) { ast_copy_string(cidmatch, prio_item->cidmatch, sizeof(cidmatch)); } end_traversal &= ast_context_remove_extension_callerid2(tmp, extension, prio_item->priority, prio_item->cidmatch ? cidmatch : NULL, 1, NULL, 1); } /* Explanation: * ast_context_remove_extension_callerid2 will destroy the extension that it comes across. This * destruction includes destroying the exten's peer_table, which we are currently traversing. If * ast_context_remove_extension_callerid2 ever should return '0' then this means we have destroyed * the hashtable which we are traversing, and thus calling ast_hashtab_end_traversal will result * in reading invalid memory. Thus, if we detect that we destroyed the hashtable, then we will simply * free the iterator */ if (end_traversal) { ast_hashtab_end_traversal(prio_iter); } else { ast_free(prio_iter); } } ast_hashtab_end_traversal(exten_iter); } /* delete the context if it's registrar matches, is empty, has refcount of 1, */ /* it's not empty, if it has includes, ignorepats, or switches that are registered from another registrar. It's not empty if there are any extensions */ if (strcmp(tmp->registrar, registrar) == 0 && tmp->refcount < 2 && !tmp->root && !tmp->ignorepats && !tmp->includes && AST_LIST_EMPTY(&tmp->alts)) { ast_debug(1, "delete ctx %s %s\n", tmp->name, tmp->registrar); ast_hashtab_remove_this_object(contexttab, tmp); next = tmp->next; if (tmpl) tmpl->next = next; else contexts = next; /* Okay, now we're safe to let it go -- in a sense, we were ready to let it go as soon as we locked it. */ ast_unlock_context(tmp); __ast_internal_context_destroy(tmp); } else { ast_debug(1,"Couldn't delete ctx %s/%s; refc=%d; tmp.root=%p\n", tmp->name, tmp->registrar, tmp->refcount, tmp->root); ast_unlock_context(tmp); next = tmp->next; tmpl = tmp; } } else if (con) { ast_verb(3, "Deleting context %s registrar=%s\n", tmp->name, tmp->registrar); ast_debug(1, "delete ctx %s %s\n", tmp->name, tmp->registrar); ast_hashtab_remove_this_object(contexttab, tmp); next = tmp->next; if (tmpl) tmpl->next = next; else contexts = next; /* Okay, now we're safe to let it go -- in a sense, we were ready to let it go as soon as we locked it. */ ast_unlock_context(tmp); __ast_internal_context_destroy(tmp); } /* if we have a specific match, we are done, otherwise continue */ tmp = con ? NULL : next; } } void ast_context_destroy(struct ast_context *con, const char *registrar) { ast_wrlock_contexts(); __ast_context_destroy(contexts, contexts_table, con,registrar); ast_unlock_contexts(); } static void wait_for_hangup(struct ast_channel *chan, const void *data) { int res; struct ast_frame *f; double waitsec; int waittime; if (ast_strlen_zero(data) || (sscanf(data, "%30lg", &waitsec) != 1) || (waitsec < 0)) waitsec = -1; if (waitsec > -1) { waittime = waitsec * 1000.0; ast_safe_sleep(chan, waittime); } else do { res = ast_waitfor(chan, -1); if (res < 0) return; f = ast_read(chan); if (f) ast_frfree(f); } while(f); } /*! * \ingroup applications */ static int pbx_builtin_proceeding(struct ast_channel *chan, const char *data) { ast_indicate(chan, AST_CONTROL_PROCEEDING); return 0; } /*! * \ingroup applications */ static int pbx_builtin_progress(struct ast_channel *chan, const char *data) { ast_indicate(chan, AST_CONTROL_PROGRESS); return 0; } /*! * \ingroup applications */ static int pbx_builtin_ringing(struct ast_channel *chan, const char *data) { ast_indicate(chan, AST_CONTROL_RINGING); return 0; } /*! * \ingroup applications */ static int pbx_builtin_busy(struct ast_channel *chan, const char *data) { ast_indicate(chan, AST_CONTROL_BUSY); /* Don't change state of an UP channel, just indicate busy in audio */ if (chan->_state != AST_STATE_UP) { ast_setstate(chan, AST_STATE_BUSY); ast_cdr_busy(chan->cdr); } wait_for_hangup(chan, data); return -1; } /*! * \ingroup applications */ static int pbx_builtin_congestion(struct ast_channel *chan, const char *data) { ast_indicate(chan, AST_CONTROL_CONGESTION); /* Don't change state of an UP channel, just indicate congestion in audio */ if (chan->_state != AST_STATE_UP) ast_setstate(chan, AST_STATE_BUSY); wait_for_hangup(chan, data); return -1; } /*! * \ingroup applications */ static int pbx_builtin_answer(struct ast_channel *chan, const char *data) { int delay = 0; int answer_cdr = 1; char *parse; AST_DECLARE_APP_ARGS(args, AST_APP_ARG(delay); AST_APP_ARG(answer_cdr); ); if (ast_strlen_zero(data)) { return __ast_answer(chan, 0, 1); } parse = ast_strdupa(data); AST_STANDARD_APP_ARGS(args, parse); if (!ast_strlen_zero(args.delay) && (chan->_state != AST_STATE_UP)) delay = atoi(data); if (delay < 0) { delay = 0; } if (!ast_strlen_zero(args.answer_cdr) && !strcasecmp(args.answer_cdr, "nocdr")) { answer_cdr = 0; } return __ast_answer(chan, delay, answer_cdr); } static int pbx_builtin_incomplete(struct ast_channel *chan, const char *data) { const char *options = data; int answer = 1; /* Some channels can receive DTMF in unanswered state; some cannot */ if (!ast_strlen_zero(options) && strchr(options, 'n')) { answer = 0; } /* If the channel is hungup, stop waiting */ if (ast_check_hangup(chan)) { return -1; } else if (chan->_state != AST_STATE_UP && answer) { __ast_answer(chan, 0, 1); } ast_indicate(chan, AST_CONTROL_INCOMPLETE); return AST_PBX_INCOMPLETE; } AST_APP_OPTIONS(resetcdr_opts, { AST_APP_OPTION('w', AST_CDR_FLAG_POSTED), AST_APP_OPTION('a', AST_CDR_FLAG_LOCKED), AST_APP_OPTION('v', AST_CDR_FLAG_KEEP_VARS), AST_APP_OPTION('e', AST_CDR_FLAG_POST_ENABLE), }); /*! * \ingroup applications */ static int pbx_builtin_resetcdr(struct ast_channel *chan, const char *data) { char *args; struct ast_flags flags = { 0 }; if (!ast_strlen_zero(data)) { args = ast_strdupa(data); ast_app_parse_options(resetcdr_opts, &flags, NULL, args); } ast_cdr_reset(chan->cdr, &flags); return 0; } /*! * \ingroup applications */ static int pbx_builtin_setamaflags(struct ast_channel *chan, const char *data) { /* Copy the AMA Flags as specified */ ast_channel_lock(chan); ast_cdr_setamaflags(chan, data ? data : ""); ast_channel_unlock(chan); return 0; } /*! * \ingroup applications */ static int pbx_builtin_hangup(struct ast_channel *chan, const char *data) { ast_set_hangupsource(chan, "dialplan/builtin", 0); if (!ast_strlen_zero(data)) { int cause; char *endptr; if ((cause = ast_str2cause(data)) > -1) { chan->hangupcause = cause; return -1; } cause = strtol((const char *) data, &endptr, 10); if (cause != 0 || (data != endptr)) { chan->hangupcause = cause; return -1; } ast_log(LOG_WARNING, "Invalid cause given to Hangup(): \"%s\"\n", (char *) data); } if (!chan->hangupcause) { chan->hangupcause = AST_CAUSE_NORMAL_CLEARING; } return -1; } /*! * \ingroup functions */ static int testtime_write(struct ast_channel *chan, const char *cmd, char *var, const char *value) { struct ast_tm tm; struct timeval tv; char *remainder, result[30], timezone[80]; /* Turn off testing? */ if (!pbx_checkcondition(value)) { pbx_builtin_setvar_helper(chan, "TESTTIME", NULL); return 0; } /* Parse specified time */ if (!(remainder = ast_strptime(value, "%Y/%m/%d %H:%M:%S", &tm))) { return -1; } sscanf(remainder, "%79s", timezone); tv = ast_mktime(&tm, S_OR(timezone, NULL)); snprintf(result, sizeof(result), "%ld", (long) tv.tv_sec); pbx_builtin_setvar_helper(chan, "__TESTTIME", result); return 0; } static struct ast_custom_function testtime_function = { .name = "TESTTIME", .write = testtime_write, }; /*! * \ingroup applications */ static int pbx_builtin_gotoiftime(struct ast_channel *chan, const char *data) { char *s, *ts, *branch1, *branch2, *branch; struct ast_timing timing; const char *ctime; struct timeval tv = ast_tvnow(); long timesecs; if (!chan) { ast_log(LOG_WARNING, "GotoIfTime requires a channel on which to operate\n"); return -1; } if (ast_strlen_zero(data)) { ast_log(LOG_WARNING, "GotoIfTime requires an argument:\n <time range>,<days of week>,<days of month>,<months>[,<timezone>]?'labeliftrue':'labeliffalse'\n"); return -1; } ts = s = ast_strdupa(data); ast_channel_lock(chan); if ((ctime = pbx_builtin_getvar_helper(chan, "TESTTIME")) && sscanf(ctime, "%ld", &timesecs) == 1) { tv.tv_sec = timesecs; } else if (ctime) { ast_log(LOG_WARNING, "Using current time to evaluate\n"); /* Reset when unparseable */ pbx_builtin_setvar_helper(chan, "TESTTIME", NULL); } ast_channel_unlock(chan); /* Separate the Goto path */ strsep(&ts, "?"); branch1 = strsep(&ts,":"); branch2 = strsep(&ts,""); /* struct ast_include include contained garbage here, fixed by zeroing it on get_timerange */ if (ast_build_timing(&timing, s) && ast_check_timing2(&timing, tv)) { branch = branch1; } else { branch = branch2; } ast_destroy_timing(&timing); if (ast_strlen_zero(branch)) { ast_debug(1, "Not taking any branch\n"); return 0; } return pbx_builtin_goto(chan, branch); } /*! * \ingroup applications */ static int pbx_builtin_execiftime(struct ast_channel *chan, const char *data) { char *s, *appname; struct ast_timing timing; struct ast_app *app; static const char * const usage = "ExecIfTime requires an argument:\n <time range>,<days of week>,<days of month>,<months>[,<timezone>]?<appname>[(<appargs>)]"; if (ast_strlen_zero(data)) { ast_log(LOG_WARNING, "%s\n", usage); return -1; } appname = ast_strdupa(data); s = strsep(&appname, "?"); /* Separate the timerange and application name/data */ if (!appname) { /* missing application */ ast_log(LOG_WARNING, "%s\n", usage); return -1; } if (!ast_build_timing(&timing, s)) { ast_log(LOG_WARNING, "Invalid Time Spec: %s\nCorrect usage: %s\n", s, usage); ast_destroy_timing(&timing); return -1; } if (!ast_check_timing(&timing)) { /* outside the valid time window, just return */ ast_destroy_timing(&timing); return 0; } ast_destroy_timing(&timing); /* now split appname(appargs) */ if ((s = strchr(appname, '('))) { char *e; *s++ = '\0'; if ((e = strrchr(s, ')'))) *e = '\0'; else ast_log(LOG_WARNING, "Failed to find closing parenthesis\n"); } if ((app = pbx_findapp(appname))) { return pbx_exec(chan, app, S_OR(s, "")); } else { ast_log(LOG_WARNING, "Cannot locate application %s\n", appname); return -1; } } /*! * \ingroup applications */ static int pbx_builtin_wait(struct ast_channel *chan, const char *data) { int ms; /* Wait for "n" seconds */ if (!ast_app_parse_timelen(data, &ms, TIMELEN_SECONDS) && ms > 0) { return ast_safe_sleep(chan, ms); } return 0; } /*! * \ingroup applications */ static int pbx_builtin_waitexten(struct ast_channel *chan, const char *data) { int ms, res; struct ast_flags flags = {0}; char *opts[1] = { NULL }; char *parse; AST_DECLARE_APP_ARGS(args, AST_APP_ARG(timeout); AST_APP_ARG(options); ); if (!ast_strlen_zero(data)) { parse = ast_strdupa(data); AST_STANDARD_APP_ARGS(args, parse); } else memset(&args, 0, sizeof(args)); if (args.options) ast_app_parse_options(waitexten_opts, &flags, opts, args.options); if (ast_test_flag(&flags, WAITEXTEN_MOH) && !opts[0] ) { ast_log(LOG_WARNING, "The 'm' option has been specified for WaitExten without a class.\n"); } else if (ast_test_flag(&flags, WAITEXTEN_MOH)) { ast_indicate_data(chan, AST_CONTROL_HOLD, S_OR(opts[0], NULL), !ast_strlen_zero(opts[0]) ? strlen(opts[0]) + 1 : 0); } else if (ast_test_flag(&flags, WAITEXTEN_DIALTONE)) { struct ast_tone_zone_sound *ts = ast_get_indication_tone(chan->zone, "dial"); if (ts) { ast_playtones_start(chan, 0, ts->data, 0); ts = ast_tone_zone_sound_unref(ts); } else { ast_tonepair_start(chan, 350, 440, 0, 0); } } /* Wait for "n" seconds */ if (!ast_app_parse_timelen(args.timeout, &ms, TIMELEN_SECONDS) && ms > 0) { /* Yay! */ } else if (chan->pbx) { ms = chan->pbx->rtimeoutms; } else { ms = 10000; } res = ast_waitfordigit(chan, ms); if (!res) { if (ast_check_hangup(chan)) { /* Call is hungup for some reason. */ res = -1; } else if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 1, S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) { ast_verb(3, "Timeout on %s, continuing...\n", chan->name); } else if (ast_exists_extension(chan, chan->context, "t", 1, S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) { ast_verb(3, "Timeout on %s, going to 't'\n", chan->name); set_ext_pri(chan, "t", 0); /* 0 will become 1, next time through the loop */ } else if (ast_exists_extension(chan, chan->context, "e", 1, S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) { raise_exception(chan, "RESPONSETIMEOUT", 0); /* 0 will become 1, next time through the loop */ } else { ast_log(LOG_WARNING, "Timeout but no rule 't' or 'e' in context '%s'\n", chan->context); res = -1; } } if (ast_test_flag(&flags, WAITEXTEN_MOH)) ast_indicate(chan, AST_CONTROL_UNHOLD); else if (ast_test_flag(&flags, WAITEXTEN_DIALTONE)) ast_playtones_stop(chan); return res; } /*! * \ingroup applications */ static int pbx_builtin_background(struct ast_channel *chan, const char *data) { int res = 0; int mres = 0; struct ast_flags flags = {0}; char *parse, exten[2] = ""; AST_DECLARE_APP_ARGS(args, AST_APP_ARG(filename); AST_APP_ARG(options); AST_APP_ARG(lang); AST_APP_ARG(context); ); if (ast_strlen_zero(data)) { ast_log(LOG_WARNING, "Background requires an argument (filename)\n"); return -1; } parse = ast_strdupa(data); AST_STANDARD_APP_ARGS(args, parse); if (ast_strlen_zero(args.lang)) args.lang = (char *)chan->language; /* XXX this is const */ if (ast_strlen_zero(args.context)) { const char *context; ast_channel_lock(chan); if ((context = pbx_builtin_getvar_helper(chan, "MACRO_CONTEXT"))) { args.context = ast_strdupa(context); } else { args.context = chan->context; } ast_channel_unlock(chan); } if (args.options) { if (!strcasecmp(args.options, "skip")) flags.flags = BACKGROUND_SKIP; else if (!strcasecmp(args.options, "noanswer")) flags.flags = BACKGROUND_NOANSWER; else ast_app_parse_options(background_opts, &flags, NULL, args.options); } /* Answer if need be */ if (chan->_state != AST_STATE_UP) { if (ast_test_flag(&flags, BACKGROUND_SKIP)) { goto done; } else if (!ast_test_flag(&flags, BACKGROUND_NOANSWER)) { res = ast_answer(chan); } } if (!res) { char *back = ast_strip(args.filename); char *front; ast_stopstream(chan); /* Stop anything playing */ /* Stream the list of files */ while (!res && (front = strsep(&back, "&")) ) { if ( (res = ast_streamfile(chan, front, args.lang)) ) { ast_log(LOG_WARNING, "ast_streamfile failed on %s for %s\n", chan->name, (char*)data); res = 0; mres = 1; break; } if (ast_test_flag(&flags, BACKGROUND_PLAYBACK)) { res = ast_waitstream(chan, ""); } else if (ast_test_flag(&flags, BACKGROUND_MATCHEXTEN)) { res = ast_waitstream_exten(chan, args.context); } else { res = ast_waitstream(chan, AST_DIGIT_ANY); } ast_stopstream(chan); } } /* * If the single digit DTMF is an extension in the specified context, then * go there and signal no DTMF. Otherwise, we should exit with that DTMF. * If we're in Macro, we'll exit and seek that DTMF as the beginning of an * extension in the Macro's calling context. If we're not in Macro, then * we'll simply seek that extension in the calling context. Previously, * someone complained about the behavior as it related to the interior of a * Gosub routine, and the fix (#14011) inadvertently broke FreePBX * (#14940). This change should fix both of these situations, but with the * possible incompatibility that if a single digit extension does not exist * (but a longer extension COULD have matched), it would have previously * gone immediately to the "i" extension, but will now need to wait for a * timeout. * * Later, we had to add a flag to disable this workaround, because AGI * users can EXEC Background and reasonably expect that the DTMF code will * be returned (see #16434). */ if (!ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS) && (exten[0] = res) && ast_canmatch_extension(chan, args.context, exten, 1, S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)) && !ast_matchmore_extension(chan, args.context, exten, 1, S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) { snprintf(chan->exten, sizeof(chan->exten), "%c", res); ast_copy_string(chan->context, args.context, sizeof(chan->context)); chan->priority = 0; res = 0; } done: pbx_builtin_setvar_helper(chan, "BACKGROUNDSTATUS", mres ? "FAILED" : "SUCCESS"); return res; } /*! Goto * \ingroup applications */ static int pbx_builtin_goto(struct ast_channel *chan, const char *data) { int res = ast_parseable_goto(chan, data); if (!res) ast_verb(3, "Goto (%s,%s,%d)\n", chan->context, chan->exten, chan->priority + 1); return res; } int pbx_builtin_serialize_variables(struct ast_channel *chan, struct ast_str **buf) { struct ast_var_t *variables; const char *var, *val; int total = 0; if (!chan) return 0; ast_str_reset(*buf); ast_channel_lock(chan); AST_LIST_TRAVERSE(&chan->varshead, variables, entries) { if ((var = ast_var_name(variables)) && (val = ast_var_value(variables)) /* && !ast_strlen_zero(var) && !ast_strlen_zero(val) */ ) { if (ast_str_append(buf, 0, "%s=%s\n", var, val) < 0) { ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n"); break; } else total++; } else break; } ast_channel_unlock(chan); return total; } const char *pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name) { struct ast_var_t *variables; const char *ret = NULL; int i; struct varshead *places[2] = { NULL, &globals }; if (!name) return NULL; if (chan) { ast_channel_lock(chan); places[0] = &chan->varshead; } for (i = 0; i < 2; i++) { if (!places[i]) continue; if (places[i] == &globals) ast_rwlock_rdlock(&globalslock); AST_LIST_TRAVERSE(places[i], variables, entries) { if (!strcmp(name, ast_var_name(variables))) { ret = ast_var_value(variables); break; } } if (places[i] == &globals) ast_rwlock_unlock(&globalslock); if (ret) break; } if (chan) ast_channel_unlock(chan); return ret; } void pbx_builtin_pushvar_helper(struct ast_channel *chan, const char *name, const char *value) { struct ast_var_t *newvariable; struct varshead *headp; if (name[strlen(name)-1] == ')') { char *function = ast_strdupa(name); ast_log(LOG_WARNING, "Cannot push a value onto a function\n"); ast_func_write(chan, function, value); return; } if (chan) { ast_channel_lock(chan); headp = &chan->varshead; } else { ast_rwlock_wrlock(&globalslock); headp = &globals; } if (value) { if (headp == &globals) ast_verb(2, "Setting global variable '%s' to '%s'\n", name, value); newvariable = ast_var_assign(name, value); AST_LIST_INSERT_HEAD(headp, newvariable, entries); } if (chan) ast_channel_unlock(chan); else ast_rwlock_unlock(&globalslock); } int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value) { struct ast_var_t *newvariable; struct varshead *headp; const char *nametail = name; if (name[strlen(name) - 1] == ')') { char *function = ast_strdupa(name); return ast_func_write(chan, function, value); } if (chan) { ast_channel_lock(chan); headp = &chan->varshead; } else { ast_rwlock_wrlock(&globalslock); headp = &globals; } /* For comparison purposes, we have to strip leading underscores */ if (*nametail == '_') { nametail++; if (*nametail == '_') nametail++; } AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) { if (strcmp(ast_var_name(newvariable), nametail) == 0) { /* there is already such a variable, delete it */ AST_LIST_REMOVE_CURRENT(entries); ast_var_delete(newvariable); break; } } AST_LIST_TRAVERSE_SAFE_END; if (value) { if (headp == &globals) ast_verb(2, "Setting global variable '%s' to '%s'\n", name, value); newvariable = ast_var_assign(name, value); AST_LIST_INSERT_HEAD(headp, newvariable, entries); manager_event(EVENT_FLAG_DIALPLAN, "VarSet", "Channel: %s\r\n" "Variable: %s\r\n" "Value: %s\r\n" "Uniqueid: %s\r\n", chan ? chan->name : "none", name, value, chan ? chan->uniqueid : "none"); } if (chan) ast_channel_unlock(chan); else ast_rwlock_unlock(&globalslock); return 0; } int pbx_builtin_setvar(struct ast_channel *chan, const char *data) { char *name, *value, *mydata; if (ast_compat_app_set) { return pbx_builtin_setvar_multiple(chan, data); } if (ast_strlen_zero(data)) { ast_log(LOG_WARNING, "Set requires one variable name/value pair.\n"); return 0; } mydata = ast_strdupa(data); name = strsep(&mydata, "="); value = mydata; if (!value) { ast_log(LOG_WARNING, "Set requires an '=' to be a valid assignment.\n"); return 0; } if (strchr(name, ' ')) { ast_log(LOG_WARNING, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", name, mydata); } pbx_builtin_setvar_helper(chan, name, value); return 0; } int pbx_builtin_setvar_multiple(struct ast_channel *chan, const char *vdata) { char *data; int x; AST_DECLARE_APP_ARGS(args, AST_APP_ARG(pair)[24]; ); AST_DECLARE_APP_ARGS(pair, AST_APP_ARG(name); AST_APP_ARG(value); ); if (ast_strlen_zero(vdata)) { ast_log(LOG_WARNING, "MSet requires at least one variable name/value pair.\n"); return 0; } data = ast_strdupa(vdata); AST_STANDARD_APP_ARGS(args, data); for (x = 0; x < args.argc; x++) { AST_NONSTANDARD_APP_ARGS(pair, args.pair[x], '='); if (pair.argc == 2) { pbx_builtin_setvar_helper(chan, pair.name, pair.value); if (strchr(pair.name, ' ')) ast_log(LOG_WARNING, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", pair.name, pair.value); } else if (!chan) { ast_log(LOG_WARNING, "MSet: ignoring entry '%s' with no '='\n", pair.name); } else { ast_log(LOG_WARNING, "MSet: ignoring entry '%s' with no '=' (in %s@%s:%d\n", pair.name, chan->exten, chan->context, chan->priority); } } return 0; } int pbx_builtin_importvar(struct ast_channel *chan, const char *data) { char *name; char *value; char *channel; char tmp[VAR_BUF_SIZE]; static int deprecation_warning = 0; if (ast_strlen_zero(data)) { ast_log(LOG_WARNING, "Ignoring, since there is no variable to set\n"); return 0; } tmp[0] = 0; if (!deprecation_warning) { ast_log(LOG_WARNING, "ImportVar is deprecated. Please use Set(varname=${IMPORT(channel,variable)}) instead.\n"); deprecation_warning = 1; } value = ast_strdupa(data); name = strsep(&value,"="); channel = strsep(&value,","); if (channel && value && name) { /*! \todo XXX should do !ast_strlen_zero(..) of the args ? */ struct ast_channel *chan2 = ast_channel_get_by_name(channel); if (chan2) { char *s = ast_alloca(strlen(value) + 4); sprintf(s, "${%s}", value); pbx_substitute_variables_helper(chan2, s, tmp, sizeof(tmp) - 1); chan2 = ast_channel_unref(chan2); } pbx_builtin_setvar_helper(chan, name, tmp); } return(0); } static int pbx_builtin_noop(struct ast_channel *chan, const char *data) { return 0; } void pbx_builtin_clear_globals(void) { struct ast_var_t *vardata; ast_rwlock_wrlock(&globalslock); while ((vardata = AST_LIST_REMOVE_HEAD(&globals, entries))) ast_var_delete(vardata); ast_rwlock_unlock(&globalslock); } int pbx_checkcondition(const char *condition) { int res; if (ast_strlen_zero(condition)) { /* NULL or empty strings are false */ return 0; } else if (sscanf(condition, "%30d", &res) == 1) { /* Numbers are evaluated for truth */ return res; } else { /* Strings are true */ return 1; } } static int pbx_builtin_gotoif(struct ast_channel *chan, const char *data) { char *condition, *branch1, *branch2, *branch; char *stringp; if (ast_strlen_zero(data)) { ast_log(LOG_WARNING, "Ignoring, since there is no variable to check\n"); return 0; } stringp = ast_strdupa(data); condition = strsep(&stringp,"?"); branch1 = strsep(&stringp,":"); branch2 = strsep(&stringp,""); branch = pbx_checkcondition(condition) ? branch1 : branch2; if (ast_strlen_zero(branch)) { ast_debug(1, "Not taking any branch\n"); return 0; } return pbx_builtin_goto(chan, branch); } static int pbx_builtin_saynumber(struct ast_channel *chan, const char *data) { char tmp[256]; char *number = tmp; char *options; if (ast_strlen_zero(data)) { ast_log(LOG_WARNING, "SayNumber requires an argument (number)\n"); return -1; } ast_copy_string(tmp, data, sizeof(tmp)); strsep(&number, ","); options = strsep(&number, ","); if (options) { if ( strcasecmp(options, "f") && strcasecmp(options, "m") && strcasecmp(options, "c") && strcasecmp(options, "n") ) { ast_log(LOG_WARNING, "SayNumber gender option is either 'f', 'm', 'c' or 'n'\n"); return -1; } } if (ast_say_number(chan, atoi(tmp), "", chan->language, options)) { ast_log(LOG_WARNING, "We were unable to say the number %s, is it too large?\n", tmp); } return 0; } static int pbx_builtin_saydigits(struct ast_channel *chan, const char *data) { int res = 0; if (data) res = ast_say_digit_str(chan, data, "", chan->language); return res; } static int pbx_builtin_saycharacters(struct ast_channel *chan, const char *data) { int res = 0; if (data) res = ast_say_character_str(chan, data, "", chan->language); return res; } static int pbx_builtin_sayphonetic(struct ast_channel *chan, const char *data) { int res = 0; if (data) res = ast_say_phonetic_str(chan, data, "", chan->language); return res; } static void device_state_cb(const struct ast_event *event, void *unused) { const char *device; struct statechange *sc; device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE); if (ast_strlen_zero(device)) { ast_log(LOG_ERROR, "Received invalid event that had no device IE\n"); return; } if (!(sc = ast_calloc(1, sizeof(*sc) + strlen(device) + 1))) return; strcpy(sc->dev, device); if (ast_taskprocessor_push(device_state_tps, handle_statechange, sc) < 0) { ast_free(sc); } } /*! * \internal * \brief Implements the hints data provider. */ static int hints_data_provider_get(const struct ast_data_search *search, struct ast_data *data_root) { struct ast_data *data_hint; struct ast_hint *hint; int watchers; struct ao2_iterator i; if (ao2_container_count(hints) == 0) { return 0; } i = ao2_iterator_init(hints, 0); for (; (hint = ao2_iterator_next(&i)); ao2_ref(hint, -1)) { watchers = ao2_container_count(hint->callbacks); data_hint = ast_data_add_node(data_root, "hint"); if (!data_hint) { continue; } ast_data_add_str(data_hint, "extension", ast_get_extension_name(hint->exten)); ast_data_add_str(data_hint, "context", ast_get_context_name(ast_get_extension_context(hint->exten))); ast_data_add_str(data_hint, "application", ast_get_extension_app(hint->exten)); ast_data_add_str(data_hint, "state", ast_extension_state2str(hint->laststate)); ast_data_add_int(data_hint, "watchers", watchers); if (!ast_data_search_match(search, data_hint)) { ast_data_remove_node(data_root, data_hint); } } ao2_iterator_destroy(&i); return 0; } static const struct ast_data_handler hints_data_provider = { .version = AST_DATA_HANDLER_VERSION, .get = hints_data_provider_get }; static const struct ast_data_entry pbx_data_providers[] = { AST_DATA_ENTRY("asterisk/core/hints", &hints_data_provider), }; /*! \internal \brief Clean up resources on Asterisk shutdown. * \note Cleans up resources allocated in load_pbx */ static void unload_pbx(void) { int x; if (device_state_sub) { device_state_sub = ast_event_unsubscribe(device_state_sub); } if (device_state_tps) { ast_taskprocessor_unreference(device_state_tps); device_state_tps = NULL; } /* Unregister builtin applications */ for (x = 0; x < ARRAY_LEN(builtins); x++) { ast_unregister_application(builtins[x].name); } ast_manager_unregister("ShowDialPlan"); ast_cli_unregister_multiple(pbx_cli, ARRAY_LEN(pbx_cli)); ast_custom_function_unregister(&exception_function); ast_custom_function_unregister(&testtime_function); ast_data_unregister(NULL); } int load_pbx(void) { int x; ast_register_atexit(unload_pbx); /* Initialize the PBX */ ast_verb(1, "Asterisk PBX Core Initializing\n"); if (!(device_state_tps = ast_taskprocessor_get("pbx-core", 0))) { ast_log(LOG_WARNING, "failed to create pbx-core taskprocessor\n"); } ast_verb(1, "Registering builtin applications:\n"); ast_cli_register_multiple(pbx_cli, ARRAY_LEN(pbx_cli)); ast_data_register_multiple_core(pbx_data_providers, ARRAY_LEN(pbx_data_providers)); __ast_custom_function_register(&exception_function, NULL); __ast_custom_function_register(&testtime_function, NULL); /* Register builtin applications */ for (x = 0; x < ARRAY_LEN(builtins); x++) { ast_verb(1, "[%s]\n", builtins[x].name); if (ast_register_application2(builtins[x].name, builtins[x].execute, NULL, NULL, NULL)) { ast_log(LOG_ERROR, "Unable to register builtin application '%s'\n", builtins[x].name); return -1; } } /* Register manager application */ ast_manager_register_xml("ShowDialPlan", EVENT_FLAG_CONFIG | EVENT_FLAG_REPORTING, manager_show_dialplan); if (!(device_state_sub = ast_event_subscribe(AST_EVENT_DEVICE_STATE, device_state_cb, "pbx Device State Change", NULL, AST_EVENT_IE_END))) { return -1; } return 0; } /* * Lock context list functions ... */ int ast_wrlock_contexts(void) { return ast_mutex_lock(&conlock); } int ast_rdlock_contexts(void) { return ast_mutex_lock(&conlock); } int ast_unlock_contexts(void) { return ast_mutex_unlock(&conlock); } /* * Lock context ... */ int ast_wrlock_context(struct ast_context *con) { return ast_rwlock_wrlock(&con->lock); } int ast_rdlock_context(struct ast_context *con) { return ast_rwlock_rdlock(&con->lock); } int ast_unlock_context(struct ast_context *con) { return ast_rwlock_unlock(&con->lock); } /* * Name functions ... */ const char *ast_get_context_name(struct ast_context *con) { return con ? con->name : NULL; } struct ast_context *ast_get_extension_context(struct ast_exten *exten) { return exten ? exten->parent : NULL; } const char *ast_get_extension_name(struct ast_exten *exten) { return exten ? exten->exten : NULL; } const char *ast_get_extension_label(struct ast_exten *exten) { return exten ? exten->label : NULL; } const char *ast_get_include_name(struct ast_include *inc) { return inc ? inc->name : NULL; } const char *ast_get_ignorepat_name(struct ast_ignorepat *ip) { return ip ? ip->pattern : NULL; } int ast_get_extension_priority(struct ast_exten *exten) { return exten ? exten->priority : -1; } /* * Registrar info functions ... */ const char *ast_get_context_registrar(struct ast_context *c) { return c ? c->registrar : NULL; } const char *ast_get_extension_registrar(struct ast_exten *e) { return e ? e->registrar : NULL; } const char *ast_get_include_registrar(struct ast_include *i) { return i ? i->registrar : NULL; } const char *ast_get_ignorepat_registrar(struct ast_ignorepat *ip) { return ip ? ip->registrar : NULL; } int ast_get_extension_matchcid(struct ast_exten *e) { return e ? e->matchcid : 0; } const char *ast_get_extension_cidmatch(struct ast_exten *e) { return e ? e->cidmatch : NULL; } const char *ast_get_extension_app(struct ast_exten *e) { return e ? e->app : NULL; } void *ast_get_extension_app_data(struct ast_exten *e) { return e ? e->data : NULL; } const char *ast_get_switch_name(struct ast_sw *sw) { return sw ? sw->name : NULL; } const char *ast_get_switch_data(struct ast_sw *sw) { return sw ? sw->data : NULL; } int ast_get_switch_eval(struct ast_sw *sw) { return sw->eval; } const char *ast_get_switch_registrar(struct ast_sw *sw) { return sw ? sw->registrar : NULL; } /* * Walking functions ... */ struct ast_context *ast_walk_contexts(struct ast_context *con) { return con ? con->next : contexts; } struct ast_exten *ast_walk_context_extensions(struct ast_context *con, struct ast_exten *exten) { if (!exten) return con ? con->root : NULL; else return exten->next; } struct ast_sw *ast_walk_context_switches(struct ast_context *con, struct ast_sw *sw) { if (!sw) return con ? AST_LIST_FIRST(&con->alts) : NULL; else return AST_LIST_NEXT(sw, list); } struct ast_exten *ast_walk_extension_priorities(struct ast_exten *exten, struct ast_exten *priority) { return priority ? priority->peer : exten; } struct ast_include *ast_walk_context_includes(struct ast_context *con, struct ast_include *inc) { if (!inc) return con ? con->includes : NULL; else return inc->next; } struct ast_ignorepat *ast_walk_context_ignorepats(struct ast_context *con, struct ast_ignorepat *ip) { if (!ip) return con ? con->ignorepats : NULL; else return ip->next; } int ast_context_verify_includes(struct ast_context *con) { struct ast_include *inc = NULL; int res = 0; while ( (inc = ast_walk_context_includes(con, inc)) ) { if (ast_context_find(inc->rname)) continue; res = -1; ast_log(LOG_WARNING, "Context '%s' tries to include nonexistent context '%s'\n", ast_get_context_name(con), inc->rname); break; } return res; } static int __ast_goto_if_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, int async) { int (*goto_func)(struct ast_channel *chan, const char *context, const char *exten, int priority); if (!chan) return -2; if (context == NULL) context = chan->context; if (exten == NULL) exten = chan->exten; goto_func = (async) ? ast_async_goto : ast_explicit_goto; if (ast_exists_extension(chan, context, exten, priority, S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) return goto_func(chan, context, exten, priority); else { return AST_PBX_GOTO_FAILED; } } int ast_goto_if_exists(struct ast_channel *chan, const char* context, const char *exten, int priority) { return __ast_goto_if_exists(chan, context, exten, priority, 0); } int ast_async_goto_if_exists(struct ast_channel *chan, const char * context, const char *exten, int priority) { return __ast_goto_if_exists(chan, context, exten, priority, 1); } static int pbx_parseable_goto(struct ast_channel *chan, const char *goto_string, int async) { char *exten, *pri, *context; char *stringp; int ipri; int mode = 0; if (ast_strlen_zero(goto_string)) { ast_log(LOG_WARNING, "Goto requires an argument ([[context,]extension,]priority)\n"); return -1; } stringp = ast_strdupa(goto_string); context = strsep(&stringp, ","); /* guaranteed non-null */ exten = strsep(&stringp, ","); pri = strsep(&stringp, ","); if (!exten) { /* Only a priority in this one */ pri = context; exten = NULL; context = NULL; } else if (!pri) { /* Only an extension and priority in this one */ pri = exten; exten = context; context = NULL; } if (*pri == '+') { mode = 1; pri++; } else if (*pri == '-') { mode = -1; pri++; } if (sscanf(pri, "%30d", &ipri) != 1) { ipri = ast_findlabel_extension(chan, context ? context : chan->context, exten ? exten : chan->exten, pri, S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)); if (ipri < 1) { ast_log(LOG_WARNING, "Priority '%s' must be a number > 0, or valid label\n", pri); return -1; } else mode = 0; } /* At this point we have a priority and maybe an extension and a context */ if (mode) ipri = chan->priority + (ipri * mode); if (async) ast_async_goto(chan, context, exten, ipri); else ast_explicit_goto(chan, context, exten, ipri); return 0; } int ast_parseable_goto(struct ast_channel *chan, const char *goto_string) { return pbx_parseable_goto(chan, goto_string, 0); } int ast_async_parseable_goto(struct ast_channel *chan, const char *goto_string) { return pbx_parseable_goto(chan, goto_string, 1); } char *ast_complete_applications(const char *line, const char *word, int state) { struct ast_app *app = NULL; int which = 0; char *ret = NULL; size_t wordlen = strlen(word); AST_RWLIST_RDLOCK(&apps); AST_RWLIST_TRAVERSE(&apps, app, list) { if (!strncasecmp(word, app->name, wordlen) && ++which > state) { ret = ast_strdup(app->name); break; } } AST_RWLIST_UNLOCK(&apps); return ret; } static int hint_hash(const void *obj, const int flags) { const struct ast_hint *hint = obj; const char *exten_name; int res; exten_name = ast_get_extension_name(hint->exten); if (ast_strlen_zero(exten_name)) { /* * If the exten or extension name isn't set, return 0 so that * the ao2_find() search will start in the first bucket. */ res = 0; } else { res = ast_str_case_hash(exten_name); } return res; } static int hint_cmp(void *obj, void *arg, int flags) { const struct ast_hint *hint = obj; const struct ast_exten *exten = arg; return (hint->exten == exten) ? CMP_MATCH | CMP_STOP : 0; } static int statecbs_cmp(void *obj, void *arg, int flags) { const struct ast_state_cb *state_cb = obj; ast_state_cb_type change_cb = arg; return (state_cb->change_cb == change_cb) ? CMP_MATCH | CMP_STOP : 0; } static void pbx_shutdown(void) { if (hints) { ao2_ref(hints, -1); hints = NULL; } if (statecbs) { ao2_ref(statecbs, -1); statecbs = NULL; } if (contexts_table) { ast_hashtab_destroy(contexts_table, NULL); } pbx_builtin_clear_globals(); } int ast_pbx_init(void) { hints = ao2_container_alloc(HASH_EXTENHINT_SIZE, hint_hash, hint_cmp); statecbs = ao2_container_alloc(1, NULL, statecbs_cmp); ast_register_atexit(pbx_shutdown); return (hints && statecbs) ? 0 : -1; }
Evangileon/asterisk
main/pbx.c
C
gpl-2.0
337,861
/*jshint strict: false */ /*global chrome */ var merge = require('./merge'); exports.extend = require('pouchdb-extend'); exports.ajax = require('./deps/ajax'); exports.createBlob = require('./deps/blob'); exports.uuid = require('./deps/uuid'); exports.getArguments = require('argsarray'); var buffer = require('./deps/buffer'); var errors = require('./deps/errors'); var EventEmitter = require('events').EventEmitter; var collections = require('./deps/collections'); exports.Map = collections.Map; exports.Set = collections.Set; if (typeof global.Promise === 'function') { exports.Promise = global.Promise; } else { exports.Promise = require('bluebird'); } var Promise = exports.Promise; function toObject(array) { var obj = {}; array.forEach(function (item) { obj[item] = true; }); return obj; } // List of top level reserved words for doc var reservedWords = toObject([ '_id', '_rev', '_attachments', '_deleted', '_revisions', '_revs_info', '_conflicts', '_deleted_conflicts', '_local_seq', '_rev_tree', //replication documents '_replication_id', '_replication_state', '_replication_state_time', '_replication_state_reason', '_replication_stats' ]); // List of reserved words that should end up the document var dataWords = toObject([ '_attachments', //replication documents '_replication_id', '_replication_state', '_replication_state_time', '_replication_state_reason', '_replication_stats' ]); exports.lastIndexOf = function (str, char) { for (var i = str.length - 1; i >= 0; i--) { if (str.charAt(i) === char) { return i; } } return -1; }; exports.clone = function (obj) { return exports.extend(true, {}, obj); }; exports.inherits = require('inherits'); // Determine id an ID is valid // - invalid IDs begin with an underescore that does not begin '_design' or // '_local' // - any other string value is a valid id // Returns the specific error object for each case exports.invalidIdError = function (id) { var err; if (!id) { err = new TypeError(errors.MISSING_ID.message); err.status = 412; } else if (typeof id !== 'string') { err = new TypeError(errors.INVALID_ID.message); err.status = 400; } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) { err = new TypeError(errors.RESERVED_ID.message); err.status = 400; } if (err) { throw err; } }; function isChromeApp() { return (typeof chrome !== "undefined" && typeof chrome.storage !== "undefined" && typeof chrome.storage.local !== "undefined"); } // Pretty dumb name for a function, just wraps callback calls so we dont // to if (callback) callback() everywhere exports.call = exports.getArguments(function (args) { if (!args.length) { return; } var fun = args.shift(); if (typeof fun === 'function') { fun.apply(this, args); } }); exports.isLocalId = function (id) { return (/^_local/).test(id); }; // check if a specific revision of a doc has been deleted // - metadata: the metadata object from the doc store // - rev: (optional) the revision to check. defaults to winning revision exports.isDeleted = function (metadata, rev) { if (!rev) { rev = merge.winningRev(metadata); } var dashIndex = rev.indexOf('-'); if (dashIndex !== -1) { rev = rev.substring(dashIndex + 1); } var deleted = false; merge.traverseRevTree(metadata.rev_tree, function (isLeaf, pos, id, acc, opts) { if (id === rev) { deleted = !!opts.deleted; } }); return deleted; }; exports.revExists = function (metadata, rev) { var found = false; merge.traverseRevTree(metadata.rev_tree, function (leaf, pos, id, acc, opts) { if ((pos + '-' + id) === rev) { found = true; } }); return found; }; exports.filterChange = function (opts) { return function (change) { var req = {}; var hasFilter = opts.filter && typeof opts.filter === 'function'; req.query = opts.query_params; if (opts.filter && hasFilter && !opts.filter.call(this, change.doc, req)) { return false; } if (opts.doc_ids && opts.doc_ids.indexOf(change.id) === -1) { return false; } if (!opts.include_docs) { delete change.doc; } else { for (var att in change.doc._attachments) { if (change.doc._attachments.hasOwnProperty(att)) { change.doc._attachments[att].stub = true; } } } return true; }; }; // Preprocess documents, parse their revisions, assign an id and a // revision for new writes that are missing them, etc exports.parseDoc = function (doc, newEdits) { var nRevNum; var newRevId; var revInfo; var error; var opts = {status: 'available'}; if (doc._deleted) { opts.deleted = true; } if (newEdits) { if (!doc._id) { doc._id = exports.uuid(); } newRevId = exports.uuid(32, 16).toLowerCase(); if (doc._rev) { revInfo = /^(\d+)-(.+)$/.exec(doc._rev); if (!revInfo) { var err = new TypeError("invalid value for property '_rev'"); err.status = 400; } doc._rev_tree = [{ pos: parseInt(revInfo[1], 10), ids: [revInfo[2], {status: 'missing'}, [[newRevId, opts, []]]] }]; nRevNum = parseInt(revInfo[1], 10) + 1; } else { doc._rev_tree = [{ pos: 1, ids : [newRevId, opts, []] }]; nRevNum = 1; } } else { if (doc._revisions) { doc._rev_tree = [{ pos: doc._revisions.start - doc._revisions.ids.length + 1, ids: doc._revisions.ids.reduce(function (acc, x) { if (acc === null) { return [x, opts, []]; } else { return [x, {status: 'missing'}, [acc]]; } }, null) }]; nRevNum = doc._revisions.start; newRevId = doc._revisions.ids[0]; } if (!doc._rev_tree) { revInfo = /^(\d+)-(.+)$/.exec(doc._rev); if (!revInfo) { error = new TypeError(errors.BAD_ARG.message); error.status = errors.BAD_ARG.status; throw error; } nRevNum = parseInt(revInfo[1], 10); newRevId = revInfo[2]; doc._rev_tree = [{ pos: parseInt(revInfo[1], 10), ids: [revInfo[2], opts, []] }]; } } exports.invalidIdError(doc._id); doc._rev = [nRevNum, newRevId].join('-'); var result = {metadata : {}, data : {}}; for (var key in doc) { if (doc.hasOwnProperty(key)) { var specialKey = key[0] === '_'; if (specialKey && !reservedWords[key]) { error = new Error(errors.DOC_VALIDATION.message + ': ' + key); error.status = errors.DOC_VALIDATION.status; throw error; } else if (specialKey && !dataWords[key]) { result.metadata[key.slice(1)] = doc[key]; } else { result.data[key] = doc[key]; } } } return result; }; exports.isCordova = function () { return (typeof cordova !== "undefined" || typeof PhoneGap !== "undefined" || typeof phonegap !== "undefined"); }; exports.hasLocalStorage = function () { if (isChromeApp()) { return false; } try { return global.localStorage; } catch (e) { return false; } }; exports.Changes = Changes; exports.inherits(Changes, EventEmitter); function Changes() { if (!(this instanceof Changes)) { return new Changes(); } var self = this; EventEmitter.call(this); this.isChrome = isChromeApp(); this.listeners = {}; this.hasLocal = false; if (!this.isChrome) { this.hasLocal = exports.hasLocalStorage(); } if (this.isChrome) { chrome.storage.onChanged.addListener(function (e) { // make sure it's event addressed to us if (e.db_name != null) { //object only has oldValue, newValue members self.emit(e.dbName.newValue); } }); } else if (this.hasLocal) { if (global.addEventListener) { global.addEventListener("storage", function (e) { self.emit(e.key); }); } else { global.attachEvent("storage", function (e) { self.emit(e.key); }); } } } Changes.prototype.addListener = function (dbName, id, db, opts) { if (this.listeners[id]) { return; } function eventFunction() { db.changes({ include_docs: opts.include_docs, conflicts: opts.conflicts, continuous: false, descending: false, filter: opts.filter, view: opts.view, since: opts.since, query_params: opts.query_params, onChange: function (c) { if (c.seq > opts.since && !opts.cancelled) { opts.since = c.seq; exports.call(opts.onChange, c); } } }); } this.listeners[id] = eventFunction; this.on(dbName, eventFunction); }; Changes.prototype.removeListener = function (dbName, id) { if (!(id in this.listeners)) { return; } EventEmitter.prototype.removeListener.call(this, dbName, this.listeners[id]); }; Changes.prototype.notifyLocalWindows = function (dbName) { //do a useless change on a storage thing //in order to get other windows's listeners to activate if (this.isChrome) { chrome.storage.local.set({dbName: dbName}); } else if (this.hasLocal) { localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a"; } }; Changes.prototype.notify = function (dbName) { this.emit(dbName); this.notifyLocalWindows(dbName); }; if (!process.browser || !('atob' in global)) { exports.atob = function (str) { var base64 = new buffer(str, 'base64'); // Node.js will just skip the characters it can't encode instead of // throwing and exception if (base64.toString('base64') !== str) { throw ("Cannot base64 encode full string"); } return base64.toString('binary'); }; } else { exports.atob = function (str) { return atob(str); }; } if (!process.browser || !('btoa' in global)) { exports.btoa = function (str) { return new buffer(str, 'binary').toString('base64'); }; } else { exports.btoa = function (str) { return btoa(str); }; } // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) exports.fixBinary = function (bin) { if (!process.browser) { // don't need to do this in Node return bin; } var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; }; // shim for browsers that don't support it exports.readAsBinaryString = function (blob, callback) { var reader = new FileReader(); var hasBinaryString = typeof reader.readAsBinaryString === 'function'; reader.onloadend = function (e) { var result = e.target.result || ''; if (hasBinaryString) { return callback(result); } callback(exports.arrayBufferToBinaryString(result)); }; if (hasBinaryString) { reader.readAsBinaryString(blob); } else { reader.readAsArrayBuffer(blob); } }; exports.once = function (fun) { var called = false; return exports.getArguments(function (args) { if (called) { throw new Error('once called more than once'); } else { called = true; fun.apply(this, args); } }); }; exports.toPromise = function (func) { //create the function we will be returning return exports.getArguments(function (args) { var self = this; var tempCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false; // if the last argument is a function, assume its a callback var usedCB; if (tempCB) { // if it was a callback, create a new callback which calls it, // but do so async so we don't trap any errors usedCB = function (err, resp) { process.nextTick(function () { tempCB(err, resp); }); }; } var promise = new Promise(function (fulfill, reject) { var resp; try { var callback = exports.once(function (err, mesg) { if (err) { reject(err); } else { fulfill(mesg); } }); // create a callback for this invocation // apply the function in the orig context args.push(callback); resp = func.apply(self, args); if (resp && typeof resp.then === 'function') { fulfill(resp); } } catch (e) { reject(e); } }); // if there is a callback, call it back if (usedCB) { promise.then(function (result) { usedCB(null, result); }, usedCB); } promise.cancel = function () { return this; }; return promise; }); }; exports.adapterFun = function (name, callback) { return exports.toPromise(exports.getArguments(function (args) { if (this._closed) { return Promise.reject(new Error('database is closed')); } var self = this; if (!this.taskqueue.isReady) { return new exports.Promise(function (fulfill, reject) { self.taskqueue.addTask(function (failed) { if (failed) { reject(failed); } else { fulfill(self[name].apply(self, args)); } }); }); } return callback.apply(this, args); })); }; //Can't find original post, but this is close //http://stackoverflow.com/questions/6965107/ (continues on next line) //converting-between-strings-and-arraybuffers exports.arrayBufferToBinaryString = function (buffer) { var binary = ""; var bytes = new Uint8Array(buffer); var length = bytes.byteLength; for (var i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]); } return binary; }; exports.cancellableFun = function (fun, self, opts) { opts = opts ? exports.clone(true, {}, opts) : {}; var emitter = new EventEmitter(); var oldComplete = opts.complete || function () { }; var complete = opts.complete = exports.once(function (err, resp) { if (err) { oldComplete(err); } else { emitter.emit('end', resp); oldComplete(null, resp); } emitter.removeAllListeners(); }); var oldOnChange = opts.onChange || function () {}; var lastChange = 0; self.on('destroyed', function () { emitter.removeAllListeners(); }); opts.onChange = function (change) { oldOnChange(change); if (change.seq <= lastChange) { return; } lastChange = change.seq; emitter.emit('change', change); if (change.deleted) { emitter.emit('delete', change); } else if (change.changes.length === 1 && change.changes[0].rev.slice(0, 1) === '1-') { emitter.emit('create', change); } else { emitter.emit('update', change); } }; var promise = new Promise(function (fulfill, reject) { opts.complete = function (err, res) { if (err) { reject(err); } else { fulfill(res); } }; }); promise.then(function (result) { complete(null, result); }, complete); // this needs to be overwridden by caller, dont fire complete until // the task is ready promise.cancel = function () { promise.isCancelled = true; if (self.taskqueue.isReady) { opts.complete(null, {status: 'cancelled'}); } }; if (!self.taskqueue.isReady) { self.taskqueue.addTask(function () { if (promise.isCancelled) { opts.complete(null, {status: 'cancelled'}); } else { fun(self, opts, promise); } }); } else { fun(self, opts, promise); } promise.on = emitter.on.bind(emitter); promise.once = emitter.once.bind(emitter); promise.addListener = emitter.addListener.bind(emitter); promise.removeListener = emitter.removeListener.bind(emitter); promise.removeAllListeners = emitter.removeAllListeners.bind(emitter); promise.setMaxListeners = emitter.setMaxListeners.bind(emitter); promise.listeners = emitter.listeners.bind(emitter); promise.emit = emitter.emit.bind(emitter); return promise; }; exports.MD5 = exports.toPromise(require('./deps/md5')); // designed to give info to browser users, who are disturbed // when they see 404s in the console exports.explain404 = function (str) { if (process.browser && 'console' in global && 'info' in console) { console.info('The above 404 is totally normal. ' + str + '\n\u2665 the PouchDB team'); } }; exports.parseUri = require('./deps/parse-uri'); exports.compare = function (left, right) { return left < right ? -1 : left > right ? 1 : 0; };
mrded/wikijob
www/lib/pouchdb/lib/utils.js
JavaScript
gpl-2.0
16,505
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark 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. * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest01168") public class BenchmarkTest01168 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = ""; boolean flag = true; java.util.Enumeration<String> names = request.getHeaderNames(); while (names.hasMoreElements() && flag) { String name = (String) names.nextElement(); java.util.Enumeration<String> values = request.getHeaders(name); if (values != null) { while (values.hasMoreElements() && flag) { String value = (String) values.nextElement(); if (value.equals("vector")) { param = name; flag = false; } } } } String bar = new Test().doSomething(param); try { java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG"); double rand = getNextNumber(numGen); String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front. String user = "SafeDonatella"; String fullClassName = this.getClass().getName(); String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length()); user+= testCaseNumber; String cookieName = "rememberMe" + testCaseNumber; boolean foundUser = false; javax.servlet.http.Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) { javax.servlet.http.Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) { if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) { foundUser = true; } } } if (foundUser) { response.getWriter().println("Welcome back: " + user + "<br/>"); } else { javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey); rememberMe.setSecure(true); request.getSession().setAttribute(cookieName, rememberMeKey); response.addCookie(rememberMe); response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName() + " whose value is: " + rememberMe.getValue() + "<br/>"); } } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing SecureRandom.nextDouble() - TestCase"); throw new ServletException(e); } response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed"); } double getNextNumber(java.util.Random generator) { return generator.nextDouble(); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { String bar; // Simple if statement that assigns constant to bar on true condition int num = 86; if ( (7*42) - num > 200 ) bar = "This_should_always_happen"; else bar = param; return bar; } } // end innerclass Test } // end DataflowThruInnerClass
marylinh/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01168.java
Java
gpl-2.0
4,339
# axios [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![build status](https://img.shields.io/travis/mzabriskie/axios.svg?style=flat-square)](https://travis-ci.org/mzabriskie/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) Promise based HTTP client for the browser and node.js ## Features - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser - Make [http](http://nodejs.org/api/http.html) requests from node.js - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API - Intercept request and response - Transform request and response data - Automatic transforms for JSON data - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) ## Browser Support ![Chrome](https://raw.github.com/alrra/browser-logos/master/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/internet-explorer/internet-explorer_48x48.png) | --- | --- | --- | --- | --- | --- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 8+ ✔ | [![Browser Matrix](https://saucelabs.com/browser-matrix/axios.svg)](https://saucelabs.com/u/axios) ## Installing Using cdn: ```html <script src="https://npmcdn.com/axios/dist/axios.min.js"></script> ``` Using npm: ```bash $ npm install axios ``` Using bower: ```bash $ bower install axios ``` ## Example Performing a `GET` request ```js // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); ``` Performing a `POST` request ```js axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); ``` Performing multiple concurrent requests ```js function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete })); ``` ## axios API Requests can be made by passing the relevant config to `axios`. ##### axios(config) ```js // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ##### axios(url[, config]) ```js // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience aliases have been provided for all supported request methods. ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. ### Concurrency Helper functions for dealing with concurrent requests. ##### axios.all(iterable) ##### axios.spread(callback) ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ```js var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ## Request Config These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ```js { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', and 'PATCH' // The last function in the array must return a string, an ArrayBuffer, or a Stream transformRequest: [function (data) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be a string, an ArrayBuffer, a hash, or a Stream data: { firstName: 'Fred' }, // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)). adapter: function (resolve, reject, config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. auth: { username: 'janedoe', password: 's00pers3cret' } // `responseType` indicates the type of data that the server will respond with // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `progress` allows handling of progress events for 'POST' and 'PUT uploads' // as well as 'GET' downloads progress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default } } ``` ## Response Schema The response for a request contains the following information. ```js { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with headers: {}, // `config` is the config that was provided to `axios` for the request config: {} } ``` When using `then` or `catch`, you will receive the response as follows: ```js axios.get('/user/12345') .then(function(response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` ## Config Defaults You can specify config defaults that will be applied to every request. ### Global axios defaults ```js axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ```js // Set config defaults when creating the instance var instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in `lib/defaults.js`, then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ```js // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library var instance = axios.create(); // Override timeout default for the library // Now all requests will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` ## Interceptors You can intercept requests or responses before they are handled by `then` or `catch`. ```js // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Do something with response data return response; }, function (error) { // Do something with response error return Promise.reject(error); }); ``` If you may need to remove an interceptor later you can. ```js var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ```js var instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` ## Handling Errors ```js axios.get('/user/12345') .catch(function (response) { if (response instanceof Error) { // Something happened in setting up the request that triggered an Error console.log('Error', response.message); } else { // The request was made, but the server responded with a status code // that falls out of the range of 2xx console.log(response.data); console.log(response.status); console.log(response.headers); console.log(response.config); } }); ``` You can define a custom HTTP status code error range using the `validateStatus` config option. ```js axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } }) ``` ## Semver Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. ## Promises axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). ## TypeScript axios includes a [TypeScript](http://typescriptlang.org) definition. ```typescript /// <reference path="axios.d.ts" /> import * as axios from 'axios'; axios.get('/user?ID=12345'); ``` ## Resources * [Changelog](https://github.com/mzabriskie/axios/blob/master/CHANGELOG.md) * [Ecosystem](https://github.com/mzabriskie/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/mzabriskie/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/mzabriskie/axios/blob/master/CODE_OF_CONDUCT.md) ## Credits axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. ## License MIT
Alex-Shilman/Drupal8Node
node_modules/axios/README.md
Markdown
gpl-2.0
13,939
/* Minimal malloc implementation for interposition tests. Copyright (C) 2016-2017 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; see the file COPYING.LIB. If not, see <http://www.gnu.org/licenses/>. */ #include "tst-interpose-aux.h" #include <errno.h> #include <stdarg.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/uio.h> #include <unistd.h> #if INTERPOSE_THREADS #include <pthread.h> #endif /* Print the error message and terminate the process with status 1. */ __attribute__ ((noreturn)) __attribute__ ((format (printf, 1, 2))) static void * fail (const char *format, ...) { /* This assumes that vsnprintf will not call malloc. It does not do so for the format strings we use. */ char message[4096]; va_list ap; va_start (ap, format); vsnprintf (message, sizeof (message), format, ap); va_end (ap); enum { count = 3 }; struct iovec iov[count]; iov[0].iov_base = (char *) "error: "; iov[1].iov_base = (char *) message; iov[2].iov_base = (char *) "\n"; for (int i = 0; i < count; ++i) iov[i].iov_len = strlen (iov[i].iov_base); int unused __attribute__ ((unused)); unused = writev (STDOUT_FILENO, iov, count); _exit (1); } #if INTERPOSE_THREADS static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; #endif static void lock (void) { #if INTERPOSE_THREADS int ret = pthread_mutex_lock (&mutex); if (ret != 0) { errno = ret; fail ("pthread_mutex_lock: %m"); } #endif } static void unlock (void) { #if INTERPOSE_THREADS int ret = pthread_mutex_unlock (&mutex); if (ret != 0) { errno = ret; fail ("pthread_mutex_unlock: %m"); } #endif } struct __attribute__ ((aligned (__alignof__ (max_align_t)))) allocation_header { size_t allocation_index; size_t allocation_size; }; /* Array of known allocations, to track invalid frees. */ enum { max_allocations = 65536 }; static struct allocation_header *allocations[max_allocations]; static size_t allocation_index; static size_t deallocation_count; /* Sanity check for successful malloc interposition. */ __attribute__ ((destructor)) static void check_for_allocations (void) { if (allocation_index == 0) { /* Make sure that malloc is called at least once from libc. */ void *volatile ptr = strdup ("ptr"); /* Compiler barrier. The strdup function calls malloc, which updates allocation_index, but strdup is marked __THROW, so the compiler could optimize away the reload. */ __asm__ volatile ("" ::: "memory"); free (ptr); /* If the allocation count is still zero, it means we did not interpose malloc successfully. */ if (allocation_index == 0) fail ("malloc does not seem to have been interposed"); } } static struct allocation_header *get_header (const char *op, void *ptr) { struct allocation_header *header = ((struct allocation_header *) ptr) - 1; if (header->allocation_index >= allocation_index) fail ("%s: %p: invalid allocation index: %zu (not less than %zu)", op, ptr, header->allocation_index, allocation_index); if (allocations[header->allocation_index] != header) fail ("%s: %p: allocation pointer does not point to header, but %p", op, ptr, allocations[header->allocation_index]); return header; } /* Internal helper functions. Those must be called while the lock is acquired. */ static void * malloc_internal (size_t size) { if (allocation_index == max_allocations) { errno = ENOMEM; return NULL; } size_t allocation_size = size + sizeof (struct allocation_header); if (allocation_size < size) { errno = ENOMEM; return NULL; } size_t index = allocation_index++; void *result = mmap (NULL, allocation_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (result == MAP_FAILED) return NULL; allocations[index] = result; *allocations[index] = (struct allocation_header) { .allocation_index = index, .allocation_size = allocation_size }; return allocations[index] + 1; } static void free_internal (const char *op, struct allocation_header *header) { size_t index = header->allocation_index; int result = mprotect (header, header->allocation_size, PROT_NONE); if (result != 0) fail ("%s: mprotect (%p, %zu): %m", op, header, header->allocation_size); /* Catch double-free issues. */ allocations[index] = NULL; ++deallocation_count; } static void * realloc_internal (void *ptr, size_t new_size) { struct allocation_header *header = get_header ("realloc", ptr); size_t old_size = header->allocation_size - sizeof (struct allocation_header); if (old_size >= new_size) return ptr; void *newptr = malloc_internal (new_size); if (newptr == NULL) return NULL; memcpy (newptr, ptr, old_size); free_internal ("realloc", header); return newptr; } /* Public interfaces. These functions must perform locking. */ size_t malloc_allocation_count (void) { lock (); size_t count = allocation_index; unlock (); return count; } size_t malloc_deallocation_count (void) { lock (); size_t count = deallocation_count; unlock (); return count; } void * malloc (size_t size) { lock (); void *result = malloc_internal (size); unlock (); return result; } void free (void *ptr) { if (ptr == NULL) return; lock (); struct allocation_header *header = get_header ("free", ptr); free_internal ("free", header); unlock (); } void * calloc (size_t a, size_t b) { if (b > 0 && a > SIZE_MAX / b) { errno = ENOMEM; return NULL; } lock (); /* malloc_internal uses mmap, so the memory is zeroed. */ void *result = malloc_internal (a * b); unlock (); return result; } void * realloc (void *ptr, size_t n) { if (n ==0) { free (ptr); return NULL; } else if (ptr == NULL) return malloc (n); else { lock (); void *result = realloc_internal (ptr, n); unlock (); return result; } }
ctyler/spo600-glibc
malloc/tst-interpose-aux.c
C
gpl-2.0
6,803
/* Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved. Contact: SYSTAP, LLC 2501 Calvert ST NW #106 Washington, DC 20008 licenses@systap.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. 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 */ /* * Created on Apr 18, 2009 */ package com.bigdata.relation.accesspath; import junit.framework.TestCase2; import com.bigdata.striterator.IChunkedIterator; /** * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> * @version $Id$ */ public class TestUnsynchronizedUnboundedChunkBuffer extends TestCase2 { /** * */ public TestUnsynchronizedUnboundedChunkBuffer() { } /** * @param arg0 */ public TestUnsynchronizedUnboundedChunkBuffer(String arg0) { super(arg0); } /** * Test empty iterator. */ public void test_emptyIterator() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); // the iterator is initially empty. assertFalse(buffer.iterator().hasNext()); } /** * Verify that elements are flushed when an iterator is requested so * that they will be visited by the iterator. */ public void test_bufferFlushedByIterator() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); buffer.add("a"); assertSameIterator(new String[] { "a" }, buffer.iterator()); } /** * Verify that the iterator has snapshot semantics. */ public void test_snapshotIterator() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); buffer.add("a"); buffer.add("b"); buffer.add("c"); // visit once. assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator()); // will visit again. assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator()); } /** * Verify iterator visits chunks as placed onto the queue. */ public void test_chunkedIterator() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); buffer.add("a"); buffer.flush(); buffer.add("b"); buffer.add("c"); // visit once. assertSameChunkedIterator(new String[][] { new String[] { "a" }, new String[] { "b", "c" } }, buffer.iterator()); } /** * Test class of chunks created by the iterator (the array class should be * taken from the first visited chunk's class). */ // @SuppressWarnings("unchecked") public void test_chunkClass() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); buffer.add("a"); buffer.flush(); buffer.add("b"); buffer.add("c"); // visit once. assertSameChunkedIterator(new String[][] { new String[] { "a" }, new String[] { "b", "c" } }, buffer.iterator()); } /** * Verify that the iterator visits the expected chunks in the expected * order. * * @param <E> * @param chunks * @param itr */ protected <E> void assertSameChunkedIterator(final E[][] chunks, final IChunkedIterator<E> itr) { for(E[] chunk : chunks) { assertTrue(itr.hasNext()); final E[] actual = itr.nextChunk(); assertSameArray(chunk, actual); } assertFalse(itr.hasNext()); } }
smalyshev/blazegraph
bigdata/src/test/com/bigdata/relation/accesspath/TestUnsynchronizedUnboundedChunkBuffer.java
Java
gpl-2.0
4,863
/******************************************************************************* * Copyright (C) 2011 - 2015 Yoav Artzi, All rights reserved. * <p> * 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 any later version. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *******************************************************************************/ package edu.cornell.cs.nlp.spf.parser.ccg.rules.coordination; import edu.cornell.cs.nlp.spf.ccg.categories.Category; import edu.cornell.cs.nlp.spf.ccg.categories.syntax.ComplexSyntax; import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Slash; import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Syntax; import edu.cornell.cs.nlp.spf.parser.ccg.rules.IBinaryParseRule; import edu.cornell.cs.nlp.spf.parser.ccg.rules.ParseRuleResult; import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName; import edu.cornell.cs.nlp.spf.parser.ccg.rules.SentenceSpan; import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName.Direction; class C2Rule<MR> implements IBinaryParseRule<MR> { private static final RuleName RULE_NAME = RuleName .create("c2", Direction.FORWARD); private static final long serialVersionUID = 1876084168220307197L; private final ICoordinationServices<MR> services; public C2Rule(ICoordinationServices<MR> services) { this.services = services; } @Override public ParseRuleResult<MR> apply(Category<MR> left, Category<MR> right, SentenceSpan span) { if (left.getSyntax().equals(Syntax.C) && SyntaxCoordinationServices.isCoordinationOfType( right.getSyntax(), null)) { final MR semantics = services.expandCoordination(right .getSemantics()); if (semantics != null) { return new ParseRuleResult<MR>(RULE_NAME, Category.create( new ComplexSyntax(right.getSyntax(), SyntaxCoordinationServices .getCoordinationType(right .getSyntax()), Slash.BACKWARD), semantics)); } } return null; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("rawtypes") final C2Rule other = (C2Rule) obj; if (services == null) { if (other.services != null) { return false; } } else if (!services.equals(other.services)) { return false; } return true; } @Override public RuleName getName() { return RULE_NAME; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (RULE_NAME == null ? 0 : RULE_NAME.hashCode()); result = prime * result + (services == null ? 0 : services.hashCode()); return result; } }
ayuzhanin/cornell-spf-scala
src/main/java/edu/cornell/cs/nlp/spf/parser/ccg/rules/coordination/C2Rule.java
Java
gpl-2.0
3,328
<?php // https://raw.github.com/facebook/php-sdk/master/src/facebook.php // modified // Facebook PHP SDK (v.3.1.1) /** * Copyright 2011 Facebook, 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. */ /** * Extends the BaseFacebook class with the intent of using * PHP sessions to store user ids and access tokens. */ class Facebook extends BaseFacebook { /** * Identical to the parent constructor, except that * we start a PHP session to store the user ID and * access token if during the course of execution * we discover them. * * @param Array $config the application configuration. * @see BaseFacebook::__construct in facebook.php */ public function __construct($config) { if (!session_id()) { session_start(); } parent::__construct($config); } protected static $kSupportedKeys = array('state', 'code', 'access_token', 'user_id'); /** * Provides the implementations of the inherited abstract * methods. The implementation uses PHP sessions to maintain * a store for authorization codes, user ids, CSRF states, and * access tokens. */ protected function setPersistentData($key, $value) { if (!in_array($key, self::$kSupportedKeys)) { self::errorLog('Unsupported key passed to setPersistentData.'); return; } $session_var_name = $this->constructSessionVariableName($key); $_SESSION[$session_var_name] = $value; } protected function getPersistentData($key, $default = false) { if (!in_array($key, self::$kSupportedKeys)) { self::errorLog('Unsupported key passed to getPersistentData.'); return $default; } $session_var_name = $this->constructSessionVariableName($key); return isset($_SESSION[$session_var_name]) ? $_SESSION[$session_var_name] : $default; } protected function clearPersistentData($key) { if (!in_array($key, self::$kSupportedKeys)) { self::errorLog('Unsupported key passed to clearPersistentData.'); return; } $session_var_name = $this->constructSessionVariableName($key); unset($_SESSION[$session_var_name]); } protected function clearAllPersistentData() { foreach (self::$kSupportedKeys as $key) { $this->clearPersistentData($key); } } protected function constructSessionVariableName($key) { return implode('_', array('fb', $this->getAppId(), $key)); } }
rijojoy/MyIceBerg
mod/elgg_social_login/vendors/hybridauth/Hybrid_plugin/thirdparty/Facebook/facebook.php
PHP
gpl-2.0
2,964
/* * linux/fs/ext4/super.c * * Copyright (C) 1992, 1993, 1994, 1995 * Remy Card (card@masi.ibp.fr) * Laboratoire MASI - Institut Blaise Pascal * Universite Pierre et Marie Curie (Paris VI) * * from * * linux/fs/minix/inode.c * * Copyright (C) 1991, 1992 Linus Torvalds * * Big-endian to little-endian byte-swapping/bitmaps by * David S. Miller (davem@caip.rutgers.edu), 1995 */ #include <linux/module.h> #include <linux/string.h> #include <linux/fs.h> #include <linux/time.h> #include <linux/vmalloc.h> #include <linux/jbd2.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/blkdev.h> #include <linux/parser.h> #include <linux/buffer_head.h> #include <linux/exportfs.h> #include <linux/vfs.h> #include <linux/random.h> #include <linux/mount.h> #include <linux/namei.h> #include <linux/quotaops.h> #include <linux/seq_file.h> #include <linux/proc_fs.h> #include <linux/ctype.h> #include <linux/log2.h> #include <linux/crc16.h> #include <linux/cleancache.h> #include <asm/uaccess.h> #include <linux/kthread.h> #include <linux/freezer.h> #include "ext4.h" #include "ext4_extents.h" /* Needed for trace points definition */ #include "ext4_jbd2.h" #include "xattr.h" #include "acl.h" #include "mballoc.h" #define CREATE_TRACE_POINTS #include <trace/events/ext4.h> static struct proc_dir_entry *ext4_proc_root; static struct kset *ext4_kset; static struct ext4_lazy_init *ext4_li_info; static struct mutex ext4_li_mtx; static struct ext4_features *ext4_feat; static int ext4_load_journal(struct super_block *, struct ext4_super_block *, unsigned long journal_devnum); static int ext4_show_options(struct seq_file *seq, struct dentry *root); static int ext4_commit_super(struct super_block *sb, int sync); static void ext4_mark_recovery_complete(struct super_block *sb, struct ext4_super_block *es); static void ext4_clear_journal_err(struct super_block *sb, struct ext4_super_block *es); static int ext4_sync_fs(struct super_block *sb, int wait); static int ext4_sync_fs_nojournal(struct super_block *sb, int wait); static int ext4_remount(struct super_block *sb, int *flags, char *data); static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf); static int ext4_unfreeze(struct super_block *sb); static int ext4_freeze(struct super_block *sb); static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data); static inline int ext2_feature_set_ok(struct super_block *sb); static inline int ext3_feature_set_ok(struct super_block *sb); static int ext4_feature_set_ok(struct super_block *sb, int readonly); static void ext4_destroy_lazyinit_thread(void); static void ext4_unregister_li_request(struct super_block *sb); static void ext4_clear_request_list(void); static int ext4_reserve_clusters(struct ext4_sb_info *, ext4_fsblk_t); #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23) static struct file_system_type ext2_fs_type = { .owner = THIS_MODULE, .name = "ext2", .mount = ext4_mount, .kill_sb = kill_block_super, .fs_flags = FS_REQUIRES_DEV, }; MODULE_ALIAS_FS("ext2"); MODULE_ALIAS("ext2"); #define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type) #else #define IS_EXT2_SB(sb) (0) #endif #if !defined(CONFIG_EXT3_FS) && !defined(CONFIG_EXT3_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23) static struct file_system_type ext3_fs_type = { .owner = THIS_MODULE, .name = "ext3", .mount = ext4_mount, .kill_sb = kill_block_super, .fs_flags = FS_REQUIRES_DEV, }; MODULE_ALIAS_FS("ext3"); MODULE_ALIAS("ext3"); #define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type) #else #define IS_EXT3_SB(sb) (0) #endif static int ext4_verify_csum_type(struct super_block *sb, struct ext4_super_block *es) { if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) return 1; return es->s_checksum_type == EXT4_CRC32C_CHKSUM; } static __le32 ext4_superblock_csum(struct super_block *sb, struct ext4_super_block *es) { struct ext4_sb_info *sbi = EXT4_SB(sb); int offset = offsetof(struct ext4_super_block, s_checksum); __u32 csum; csum = ext4_chksum(sbi, ~0, (char *)es, offset); return cpu_to_le32(csum); } int ext4_superblock_csum_verify(struct super_block *sb, struct ext4_super_block *es) { if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) return 1; return es->s_checksum == ext4_superblock_csum(sb, es); } void ext4_superblock_csum_set(struct super_block *sb) { struct ext4_super_block *es = EXT4_SB(sb)->s_es; if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) return; es->s_checksum = ext4_superblock_csum(sb, es); } void *ext4_kvmalloc(size_t size, gfp_t flags) { void *ret; ret = kmalloc(size, flags); if (!ret) ret = __vmalloc(size, flags, PAGE_KERNEL); return ret; } void *ext4_kvzalloc(size_t size, gfp_t flags) { void *ret; ret = kzalloc(size, flags); if (!ret) ret = __vmalloc(size, flags | __GFP_ZERO, PAGE_KERNEL); return ret; } void ext4_kvfree(void *ptr) { if (is_vmalloc_addr(ptr)) vfree(ptr); else kfree(ptr); } ext4_fsblk_t ext4_block_bitmap(struct super_block *sb, struct ext4_group_desc *bg) { return le32_to_cpu(bg->bg_block_bitmap_lo) | (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0); } ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb, struct ext4_group_desc *bg) { return le32_to_cpu(bg->bg_inode_bitmap_lo) | (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0); } ext4_fsblk_t ext4_inode_table(struct super_block *sb, struct ext4_group_desc *bg) { return le32_to_cpu(bg->bg_inode_table_lo) | (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0); } __u32 ext4_free_group_clusters(struct super_block *sb, struct ext4_group_desc *bg) { return le16_to_cpu(bg->bg_free_blocks_count_lo) | (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0); } __u32 ext4_free_inodes_count(struct super_block *sb, struct ext4_group_desc *bg) { return le16_to_cpu(bg->bg_free_inodes_count_lo) | (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0); } __u32 ext4_used_dirs_count(struct super_block *sb, struct ext4_group_desc *bg) { return le16_to_cpu(bg->bg_used_dirs_count_lo) | (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0); } __u32 ext4_itable_unused_count(struct super_block *sb, struct ext4_group_desc *bg) { return le16_to_cpu(bg->bg_itable_unused_lo) | (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ? (__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0); } void ext4_block_bitmap_set(struct super_block *sb, struct ext4_group_desc *bg, ext4_fsblk_t blk) { bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk); if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32); } void ext4_inode_bitmap_set(struct super_block *sb, struct ext4_group_desc *bg, ext4_fsblk_t blk) { bg->bg_inode_bitmap_lo = cpu_to_le32((u32)blk); if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32); } void ext4_inode_table_set(struct super_block *sb, struct ext4_group_desc *bg, ext4_fsblk_t blk) { bg->bg_inode_table_lo = cpu_to_le32((u32)blk); if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_inode_table_hi = cpu_to_le32(blk >> 32); } void ext4_free_group_clusters_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) { bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count); if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16); } void ext4_free_inodes_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) { bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count); if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16); } void ext4_used_dirs_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) { bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count); if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16); } void ext4_itable_unused_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) { bg->bg_itable_unused_lo = cpu_to_le16((__u16)count); if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_itable_unused_hi = cpu_to_le16(count >> 16); } static void __save_error_info(struct super_block *sb, const char *func, unsigned int line) { struct ext4_super_block *es = EXT4_SB(sb)->s_es; EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS; es->s_state |= cpu_to_le16(EXT4_ERROR_FS); es->s_last_error_time = cpu_to_le32(get_seconds()); strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func)); es->s_last_error_line = cpu_to_le32(line); if (!es->s_first_error_time) { es->s_first_error_time = es->s_last_error_time; strncpy(es->s_first_error_func, func, sizeof(es->s_first_error_func)); es->s_first_error_line = cpu_to_le32(line); es->s_first_error_ino = es->s_last_error_ino; es->s_first_error_block = es->s_last_error_block; } /* * Start the daily error reporting function if it hasn't been * started already */ if (!es->s_error_count) mod_timer(&EXT4_SB(sb)->s_err_report, jiffies + 24*60*60*HZ); le32_add_cpu(&es->s_error_count, 1); } static void save_error_info(struct super_block *sb, const char *func, unsigned int line) { __save_error_info(sb, func, line); ext4_commit_super(sb, 1); } /* * The del_gendisk() function uninitializes the disk-specific data * structures, including the bdi structure, without telling anyone * else. Once this happens, any attempt to call mark_buffer_dirty() * (for example, by ext4_commit_super), will cause a kernel OOPS. * This is a kludge to prevent these oops until we can put in a proper * hook in del_gendisk() to inform the VFS and file system layers. */ static int block_device_ejected(struct super_block *sb) { struct inode *bd_inode = sb->s_bdev->bd_inode; struct backing_dev_info *bdi = bd_inode->i_mapping->backing_dev_info; return bdi->dev == NULL; } static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn) { struct super_block *sb = journal->j_private; struct ext4_sb_info *sbi = EXT4_SB(sb); int error = is_journal_aborted(journal); struct ext4_journal_cb_entry *jce; BUG_ON(txn->t_state == T_FINISHED); spin_lock(&sbi->s_md_lock); while (!list_empty(&txn->t_private_list)) { jce = list_entry(txn->t_private_list.next, struct ext4_journal_cb_entry, jce_list); list_del_init(&jce->jce_list); spin_unlock(&sbi->s_md_lock); jce->jce_func(sb, jce, error); spin_lock(&sbi->s_md_lock); } spin_unlock(&sbi->s_md_lock); } /* Deal with the reporting of failure conditions on a filesystem such as * inconsistencies detected or read IO failures. * * On ext2, we can store the error state of the filesystem in the * superblock. That is not possible on ext4, because we may have other * write ordering constraints on the superblock which prevent us from * writing it out straight away; and given that the journal is about to * be aborted, we can't rely on the current, or future, transactions to * write out the superblock safely. * * We'll just use the jbd2_journal_abort() error code to record an error in * the journal instead. On recovery, the journal will complain about * that error until we've noted it down and cleared it. */ static void ext4_handle_error(struct super_block *sb) { if (sb->s_flags & MS_RDONLY) return; if (!test_opt(sb, ERRORS_CONT)) { journal_t *journal = EXT4_SB(sb)->s_journal; EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED; if (journal) jbd2_journal_abort(journal, -EIO); } if (test_opt(sb, ERRORS_RO)) { ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only"); /* * Make sure updated value of ->s_mount_flags will be visible * before ->s_flags update */ smp_wmb(); sb->s_flags |= MS_RDONLY; } if (test_opt(sb, ERRORS_PANIC)) panic("EXT4-fs (device %s): panic forced after error\n", sb->s_id); } void __ext4_error(struct super_block *sb, const char *function, unsigned int line, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: comm %s: %pV\n", sb->s_id, function, line, current->comm, &vaf); va_end(args); save_error_info(sb, function, line); ext4_handle_error(sb); } void __ext4_error_inode(struct inode *inode, const char *function, unsigned int line, ext4_fsblk_t block, const char *fmt, ...) { va_list args; struct va_format vaf; struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es; es->s_last_error_ino = cpu_to_le32(inode->i_ino); es->s_last_error_block = cpu_to_le64(block); save_error_info(inode->i_sb, function, line); va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; if (block) printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: " "inode #%lu: block %llu: comm %s: %pV\n", inode->i_sb->s_id, function, line, inode->i_ino, block, current->comm, &vaf); else printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: " "inode #%lu: comm %s: %pV\n", inode->i_sb->s_id, function, line, inode->i_ino, current->comm, &vaf); va_end(args); ext4_handle_error(inode->i_sb); } void __ext4_error_file(struct file *file, const char *function, unsigned int line, ext4_fsblk_t block, const char *fmt, ...) { va_list args; struct va_format vaf; struct ext4_super_block *es; struct inode *inode = file_inode(file); char pathname[80], *path; es = EXT4_SB(inode->i_sb)->s_es; es->s_last_error_ino = cpu_to_le32(inode->i_ino); save_error_info(inode->i_sb, function, line); path = d_path(&(file->f_path), pathname, sizeof(pathname)); if (IS_ERR(path)) path = "(unknown)"; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; if (block) printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: inode #%lu: " "block %llu: comm %s: path %s: %pV\n", inode->i_sb->s_id, function, line, inode->i_ino, block, current->comm, path, &vaf); else printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: inode #%lu: " "comm %s: path %s: %pV\n", inode->i_sb->s_id, function, line, inode->i_ino, current->comm, path, &vaf); va_end(args); ext4_handle_error(inode->i_sb); } const char *ext4_decode_error(struct super_block *sb, int errno, char nbuf[16]) { char *errstr = NULL; switch (errno) { case -EIO: errstr = "IO failure"; break; case -ENOMEM: errstr = "Out of memory"; break; case -EROFS: if (!sb || (EXT4_SB(sb)->s_journal && EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT)) errstr = "Journal has aborted"; else errstr = "Readonly filesystem"; break; default: /* If the caller passed in an extra buffer for unknown * errors, textualise them now. Else we just return * NULL. */ if (nbuf) { /* Check for truncated error codes... */ if (snprintf(nbuf, 16, "error %d", -errno) >= 0) errstr = nbuf; } break; } return errstr; } /* __ext4_std_error decodes expected errors from journaling functions * automatically and invokes the appropriate error response. */ void __ext4_std_error(struct super_block *sb, const char *function, unsigned int line, int errno) { char nbuf[16]; const char *errstr; /* Special case: if the error is EROFS, and we're not already * inside a transaction, then there's really no point in logging * an error. */ if (errno == -EROFS && journal_current_handle() == NULL && (sb->s_flags & MS_RDONLY)) return; errstr = ext4_decode_error(sb, errno, nbuf); printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n", sb->s_id, function, line, errstr); save_error_info(sb, function, line); ext4_handle_error(sb); } /* * ext4_abort is a much stronger failure handler than ext4_error. The * abort function may be used to deal with unrecoverable failures such * as journal IO errors or ENOMEM at a critical moment in log management. * * We unconditionally force the filesystem into an ABORT|READONLY state, * unless the error response on the fs has been set to panic in which * case we take the easy way out and panic immediately. */ void __ext4_abort(struct super_block *sb, const char *function, unsigned int line, const char *fmt, ...) { va_list args; save_error_info(sb, function, line); va_start(args, fmt); printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: ", sb->s_id, function, line); vprintk(fmt, args); printk("\n"); va_end(args); if ((sb->s_flags & MS_RDONLY) == 0) { ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only"); EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED; /* * Make sure updated value of ->s_mount_flags will be visible * before ->s_flags update */ smp_wmb(); sb->s_flags |= MS_RDONLY; if (EXT4_SB(sb)->s_journal) jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO); save_error_info(sb, function, line); } if (test_opt(sb, ERRORS_PANIC)) panic("EXT4-fs panic from previous error\n"); } void __ext4_msg(struct super_block *sb, const char *prefix, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf); va_end(args); } void __ext4_warning(struct super_block *sb, const char *function, unsigned int line, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n", sb->s_id, function, line, &vaf); va_end(args); } void __ext4_grp_locked_error(const char *function, unsigned int line, struct super_block *sb, ext4_group_t grp, unsigned long ino, ext4_fsblk_t block, const char *fmt, ...) __releases(bitlock) __acquires(bitlock) { struct va_format vaf; va_list args; struct ext4_super_block *es = EXT4_SB(sb)->s_es; es->s_last_error_ino = cpu_to_le32(ino); es->s_last_error_block = cpu_to_le64(block); __save_error_info(sb, function, line); va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ", sb->s_id, function, line, grp); if (ino) printk(KERN_CONT "inode %lu: ", ino); if (block) printk(KERN_CONT "block %llu:", (unsigned long long) block); printk(KERN_CONT "%pV\n", &vaf); va_end(args); if (test_opt(sb, ERRORS_CONT)) { ext4_commit_super(sb, 0); return; } ext4_unlock_group(sb, grp); ext4_handle_error(sb); /* * We only get here in the ERRORS_RO case; relocking the group * may be dangerous, but nothing bad will happen since the * filesystem will have already been marked read/only and the * journal has been aborted. We return 1 as a hint to callers * who might what to use the return value from * ext4_grp_locked_error() to distinguish between the * ERRORS_CONT and ERRORS_RO case, and perhaps return more * aggressively from the ext4 function in question, with a * more appropriate error code. */ ext4_lock_group(sb, grp); return; } void ext4_update_dynamic_rev(struct super_block *sb) { struct ext4_super_block *es = EXT4_SB(sb)->s_es; if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV) return; ext4_warning(sb, "updating to rev %d because of new feature flag, " "running e2fsck is recommended", EXT4_DYNAMIC_REV); es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO); es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE); es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV); /* leave es->s_feature_*compat flags alone */ /* es->s_uuid will be set by e2fsck if empty */ /* * The rest of the superblock fields should be zero, and if not it * means they are likely already in use, so leave them alone. We * can leave it up to e2fsck to clean up any inconsistencies there. */ } /* * Open the external journal device */ static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb) { struct block_device *bdev; char b[BDEVNAME_SIZE]; bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb); if (IS_ERR(bdev)) goto fail; return bdev; fail: ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld", __bdevname(dev, b), PTR_ERR(bdev)); return NULL; } /* * Release the journal device */ static void ext4_blkdev_put(struct block_device *bdev) { blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL); } static void ext4_blkdev_remove(struct ext4_sb_info *sbi) { struct block_device *bdev; bdev = sbi->journal_bdev; if (bdev) { ext4_blkdev_put(bdev); sbi->journal_bdev = NULL; } } static inline struct inode *orphan_list_entry(struct list_head *l) { return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode; } static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi) { struct list_head *l; ext4_msg(sb, KERN_ERR, "sb orphan head is %d", le32_to_cpu(sbi->s_es->s_last_orphan)); printk(KERN_ERR "sb_info orphan list:\n"); list_for_each(l, &sbi->s_orphan) { struct inode *inode = orphan_list_entry(l); printk(KERN_ERR " " "inode %s:%lu at %p: mode %o, nlink %d, next %d\n", inode->i_sb->s_id, inode->i_ino, inode, inode->i_mode, inode->i_nlink, NEXT_ORPHAN(inode)); } } static void ext4_put_super(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; int i, err; ext4_unregister_li_request(sb); dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED); flush_workqueue(sbi->unrsv_conversion_wq); flush_workqueue(sbi->rsv_conversion_wq); destroy_workqueue(sbi->unrsv_conversion_wq); destroy_workqueue(sbi->rsv_conversion_wq); if (sbi->s_journal) { err = jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; if (err < 0) ext4_abort(sb, "Couldn't clean up the journal"); } ext4_es_unregister_shrinker(sbi); del_timer(&sbi->s_err_report); ext4_release_system_zone(sb); ext4_mb_release(sb); ext4_ext_release(sb); ext4_xattr_put_super(sb); if (!(sb->s_flags & MS_RDONLY)) { EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER); es->s_state = cpu_to_le16(sbi->s_mount_state); } if (!(sb->s_flags & MS_RDONLY)) ext4_commit_super(sb, 1); if (sbi->s_proc) { remove_proc_entry("options", sbi->s_proc); remove_proc_entry(sb->s_id, ext4_proc_root); } kobject_del(&sbi->s_kobj); for (i = 0; i < sbi->s_gdb_count; i++) brelse(sbi->s_group_desc[i]); ext4_kvfree(sbi->s_group_desc); ext4_kvfree(sbi->s_flex_groups); percpu_counter_destroy(&sbi->s_freeclusters_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyclusters_counter); percpu_counter_destroy(&sbi->s_extent_cache_cnt); brelse(sbi->s_sbh); #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif /* Debugging code just in case the in-memory inode orphan list * isn't empty. The on-disk one can be non-empty if we've * detected an error and taken the fs readonly, but the * in-memory list had better be clean by this point. */ if (!list_empty(&sbi->s_orphan)) dump_orphan_list(sb, sbi); J_ASSERT(list_empty(&sbi->s_orphan)); invalidate_bdev(sb->s_bdev); if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) { /* * Invalidate the journal device's buffers. We don't want them * floating about in memory - the physical journal device may * hotswapped, and it breaks the `ro-after' testing code. */ sync_blockdev(sbi->journal_bdev); invalidate_bdev(sbi->journal_bdev); ext4_blkdev_remove(sbi); } if (sbi->s_mmp_tsk) kthread_stop(sbi->s_mmp_tsk); sb->s_fs_info = NULL; /* * Now that we are completely done shutting down the * superblock, we need to actually destroy the kobject. */ kobject_put(&sbi->s_kobj); wait_for_completion(&sbi->s_kobj_unregister); if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->s_blockgroup_lock); kfree(sbi); } static struct kmem_cache *ext4_inode_cachep; /* * Called inside transaction, so use GFP_NOFS */ static struct inode *ext4_alloc_inode(struct super_block *sb) { struct ext4_inode_info *ei; ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS); if (!ei) return NULL; ei->vfs_inode.i_version = 1; INIT_LIST_HEAD(&ei->i_prealloc_list); spin_lock_init(&ei->i_prealloc_lock); ext4_es_init_tree(&ei->i_es_tree); rwlock_init(&ei->i_es_lock); INIT_LIST_HEAD(&ei->i_es_lru); ei->i_es_lru_nr = 0; ei->i_touch_when = 0; ei->i_reserved_data_blocks = 0; ei->i_reserved_meta_blocks = 0; ei->i_allocated_meta_blocks = 0; ei->i_da_metadata_calc_len = 0; ei->i_da_metadata_calc_last_lblock = 0; spin_lock_init(&(ei->i_block_reservation_lock)); #ifdef CONFIG_QUOTA ei->i_reserved_quota = 0; #endif ei->jinode = NULL; INIT_LIST_HEAD(&ei->i_rsv_conversion_list); INIT_LIST_HEAD(&ei->i_unrsv_conversion_list); spin_lock_init(&ei->i_completed_io_lock); ei->i_sync_tid = 0; ei->i_datasync_tid = 0; atomic_set(&ei->i_ioend_count, 0); atomic_set(&ei->i_unwritten, 0); INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work); INIT_WORK(&ei->i_unrsv_conversion_work, ext4_end_io_unrsv_work); return &ei->vfs_inode; } static int ext4_drop_inode(struct inode *inode) { int drop = generic_drop_inode(inode); trace_ext4_drop_inode(inode, drop); return drop; } static void ext4_i_callback(struct rcu_head *head) { struct inode *inode = container_of(head, struct inode, i_rcu); kmem_cache_free(ext4_inode_cachep, EXT4_I(inode)); } static void ext4_destroy_inode(struct inode *inode) { if (!list_empty(&(EXT4_I(inode)->i_orphan))) { ext4_msg(inode->i_sb, KERN_ERR, "Inode %lu (%p): orphan list check failed!", inode->i_ino, EXT4_I(inode)); print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4, EXT4_I(inode), sizeof(struct ext4_inode_info), true); dump_stack(); } call_rcu(&inode->i_rcu, ext4_i_callback); } static void init_once(void *foo) { struct ext4_inode_info *ei = (struct ext4_inode_info *) foo; INIT_LIST_HEAD(&ei->i_orphan); init_rwsem(&ei->xattr_sem); init_rwsem(&ei->i_data_sem); inode_init_once(&ei->vfs_inode); } static int init_inodecache(void) { ext4_inode_cachep = kmem_cache_create("ext4_inode_cache", sizeof(struct ext4_inode_info), 0, (SLAB_RECLAIM_ACCOUNT| SLAB_MEM_SPREAD), init_once); if (ext4_inode_cachep == NULL) return -ENOMEM; return 0; } static void destroy_inodecache(void) { /* * Make sure all delayed rcu free inodes are flushed before we * destroy cache. */ rcu_barrier(); kmem_cache_destroy(ext4_inode_cachep); } void ext4_clear_inode(struct inode *inode) { invalidate_inode_buffers(inode); clear_inode(inode); dquot_drop(inode); ext4_discard_preallocations(inode); ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS); ext4_es_lru_del(inode); if (EXT4_I(inode)->jinode) { jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode), EXT4_I(inode)->jinode); jbd2_free_inode(EXT4_I(inode)->jinode); EXT4_I(inode)->jinode = NULL; } } static struct inode *ext4_nfs_get_inode(struct super_block *sb, u64 ino, u32 generation) { struct inode *inode; if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) return ERR_PTR(-ESTALE); if (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count)) return ERR_PTR(-ESTALE); /* iget isn't really right if the inode is currently unallocated!! * * ext4_read_inode will return a bad_inode if the inode had been * deleted, so we should be safe. * * Currently we don't know the generation for parent directory, so * a generation of 0 means "accept any" */ inode = ext4_iget(sb, ino); if (IS_ERR(inode)) return ERR_CAST(inode); if (generation && inode->i_generation != generation) { iput(inode); return ERR_PTR(-ESTALE); } return inode; } static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { return generic_fh_to_dentry(sb, fid, fh_len, fh_type, ext4_nfs_get_inode); } static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { return generic_fh_to_parent(sb, fid, fh_len, fh_type, ext4_nfs_get_inode); } /* * Try to release metadata pages (indirect blocks, directories) which are * mapped via the block device. Since these pages could have journal heads * which would prevent try_to_free_buffers() from freeing them, we must use * jbd2 layer's try_to_free_buffers() function to release them. */ static int bdev_try_to_free_page(struct super_block *sb, struct page *page, gfp_t wait) { journal_t *journal = EXT4_SB(sb)->s_journal; WARN_ON(PageChecked(page)); if (!page_has_buffers(page)) return 0; if (journal) return jbd2_journal_try_to_free_buffers(journal, page, wait & ~__GFP_WAIT); return try_to_free_buffers(page); } #ifdef CONFIG_QUOTA #define QTYPE2NAME(t) ((t) == USRQUOTA ? "user" : "group") #define QTYPE2MOPT(on, t) ((t) == USRQUOTA?((on)##USRJQUOTA):((on)##GRPJQUOTA)) static int ext4_write_dquot(struct dquot *dquot); static int ext4_acquire_dquot(struct dquot *dquot); static int ext4_release_dquot(struct dquot *dquot); static int ext4_mark_dquot_dirty(struct dquot *dquot); static int ext4_write_info(struct super_block *sb, int type); static int ext4_quota_on(struct super_block *sb, int type, int format_id, struct path *path); static int ext4_quota_on_sysfile(struct super_block *sb, int type, int format_id); static int ext4_quota_off(struct super_block *sb, int type); static int ext4_quota_off_sysfile(struct super_block *sb, int type); static int ext4_quota_on_mount(struct super_block *sb, int type); static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data, size_t len, loff_t off); static ssize_t ext4_quota_write(struct super_block *sb, int type, const char *data, size_t len, loff_t off); static int ext4_quota_enable(struct super_block *sb, int type, int format_id, unsigned int flags); static int ext4_enable_quotas(struct super_block *sb); static const struct dquot_operations ext4_quota_operations = { .get_reserved_space = ext4_get_reserved_space, .write_dquot = ext4_write_dquot, .acquire_dquot = ext4_acquire_dquot, .release_dquot = ext4_release_dquot, .mark_dirty = ext4_mark_dquot_dirty, .write_info = ext4_write_info, .alloc_dquot = dquot_alloc, .destroy_dquot = dquot_destroy, }; static const struct quotactl_ops ext4_qctl_operations = { .quota_on = ext4_quota_on, .quota_off = ext4_quota_off, .quota_sync = dquot_quota_sync, .get_info = dquot_get_dqinfo, .set_info = dquot_set_dqinfo, .get_dqblk = dquot_get_dqblk, .set_dqblk = dquot_set_dqblk }; static const struct quotactl_ops ext4_qctl_sysfile_operations = { .quota_on_meta = ext4_quota_on_sysfile, .quota_off = ext4_quota_off_sysfile, .quota_sync = dquot_quota_sync, .get_info = dquot_get_dqinfo, .set_info = dquot_set_dqinfo, .get_dqblk = dquot_get_dqblk, .set_dqblk = dquot_set_dqblk }; #endif static const struct super_operations ext4_sops = { .alloc_inode = ext4_alloc_inode, .destroy_inode = ext4_destroy_inode, .write_inode = ext4_write_inode, .dirty_inode = ext4_dirty_inode, .drop_inode = ext4_drop_inode, .evict_inode = ext4_evict_inode, .put_super = ext4_put_super, .sync_fs = ext4_sync_fs, .freeze_fs = ext4_freeze, .unfreeze_fs = ext4_unfreeze, .statfs = ext4_statfs, .remount_fs = ext4_remount, .show_options = ext4_show_options, #ifdef CONFIG_QUOTA .quota_read = ext4_quota_read, .quota_write = ext4_quota_write, #endif .bdev_try_to_free_page = bdev_try_to_free_page, }; static const struct super_operations ext4_nojournal_sops = { .alloc_inode = ext4_alloc_inode, .destroy_inode = ext4_destroy_inode, .write_inode = ext4_write_inode, .dirty_inode = ext4_dirty_inode, .drop_inode = ext4_drop_inode, .evict_inode = ext4_evict_inode, .sync_fs = ext4_sync_fs_nojournal, .put_super = ext4_put_super, .statfs = ext4_statfs, .remount_fs = ext4_remount, .show_options = ext4_show_options, #ifdef CONFIG_QUOTA .quota_read = ext4_quota_read, .quota_write = ext4_quota_write, #endif .bdev_try_to_free_page = bdev_try_to_free_page, }; static const struct export_operations ext4_export_ops = { .fh_to_dentry = ext4_fh_to_dentry, .fh_to_parent = ext4_fh_to_parent, .get_parent = ext4_get_parent, }; enum { Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid, Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro, Opt_nouid32, Opt_debug, Opt_removed, Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl, Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload, Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev, Opt_journal_checksum, Opt_journal_async_commit, Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback, Opt_data_err_abort, Opt_data_err_ignore, Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota, Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota, Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err, Opt_usrquota, Opt_grpquota, Opt_i_version, Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_mblk_io_submit, Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity, Opt_inode_readahead_blks, Opt_journal_ioprio, Opt_dioread_nolock, Opt_dioread_lock, Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable, Opt_max_dir_size_kb, }; static const match_table_t tokens = { {Opt_bsd_df, "bsddf"}, {Opt_minix_df, "minixdf"}, {Opt_grpid, "grpid"}, {Opt_grpid, "bsdgroups"}, {Opt_nogrpid, "nogrpid"}, {Opt_nogrpid, "sysvgroups"}, {Opt_resgid, "resgid=%u"}, {Opt_resuid, "resuid=%u"}, {Opt_sb, "sb=%u"}, {Opt_err_cont, "errors=continue"}, {Opt_err_panic, "errors=panic"}, {Opt_err_ro, "errors=remount-ro"}, {Opt_nouid32, "nouid32"}, {Opt_debug, "debug"}, {Opt_removed, "oldalloc"}, {Opt_removed, "orlov"}, {Opt_user_xattr, "user_xattr"}, {Opt_nouser_xattr, "nouser_xattr"}, {Opt_acl, "acl"}, {Opt_noacl, "noacl"}, {Opt_noload, "norecovery"}, {Opt_noload, "noload"}, {Opt_removed, "nobh"}, {Opt_removed, "bh"}, {Opt_commit, "commit=%u"}, {Opt_min_batch_time, "min_batch_time=%u"}, {Opt_max_batch_time, "max_batch_time=%u"}, {Opt_journal_dev, "journal_dev=%u"}, {Opt_journal_checksum, "journal_checksum"}, {Opt_journal_async_commit, "journal_async_commit"}, {Opt_abort, "abort"}, {Opt_data_journal, "data=journal"}, {Opt_data_ordered, "data=ordered"}, {Opt_data_writeback, "data=writeback"}, {Opt_data_err_abort, "data_err=abort"}, {Opt_data_err_ignore, "data_err=ignore"}, {Opt_offusrjquota, "usrjquota="}, {Opt_usrjquota, "usrjquota=%s"}, {Opt_offgrpjquota, "grpjquota="}, {Opt_grpjquota, "grpjquota=%s"}, {Opt_jqfmt_vfsold, "jqfmt=vfsold"}, {Opt_jqfmt_vfsv0, "jqfmt=vfsv0"}, {Opt_jqfmt_vfsv1, "jqfmt=vfsv1"}, {Opt_grpquota, "grpquota"}, {Opt_noquota, "noquota"}, {Opt_quota, "quota"}, {Opt_usrquota, "usrquota"}, {Opt_barrier, "barrier=%u"}, {Opt_barrier, "barrier"}, {Opt_nobarrier, "nobarrier"}, {Opt_i_version, "i_version"}, {Opt_stripe, "stripe=%u"}, {Opt_delalloc, "delalloc"}, {Opt_nodelalloc, "nodelalloc"}, {Opt_removed, "mblk_io_submit"}, {Opt_removed, "nomblk_io_submit"}, {Opt_block_validity, "block_validity"}, {Opt_noblock_validity, "noblock_validity"}, {Opt_inode_readahead_blks, "inode_readahead_blks=%u"}, {Opt_journal_ioprio, "journal_ioprio=%u"}, {Opt_auto_da_alloc, "auto_da_alloc=%u"}, {Opt_auto_da_alloc, "auto_da_alloc"}, {Opt_noauto_da_alloc, "noauto_da_alloc"}, {Opt_dioread_nolock, "dioread_nolock"}, {Opt_dioread_lock, "dioread_lock"}, {Opt_discard, "discard"}, {Opt_nodiscard, "nodiscard"}, {Opt_init_itable, "init_itable=%u"}, {Opt_init_itable, "init_itable"}, {Opt_noinit_itable, "noinit_itable"}, {Opt_max_dir_size_kb, "max_dir_size_kb=%u"}, {Opt_removed, "check=none"}, /* mount option from ext2/3 */ {Opt_removed, "nocheck"}, /* mount option from ext2/3 */ {Opt_removed, "reservation"}, /* mount option from ext2/3 */ {Opt_removed, "noreservation"}, /* mount option from ext2/3 */ {Opt_removed, "journal=%u"}, /* mount option from ext2/3 */ {Opt_err, NULL}, }; static ext4_fsblk_t get_sb_block(void **data) { ext4_fsblk_t sb_block; char *options = (char *) *data; if (!options || strncmp(options, "sb=", 3) != 0) return 1; /* Default location */ options += 3; /* TODO: use simple_strtoll with >32bit ext4 */ sb_block = simple_strtoul(options, &options, 0); if (*options && *options != ',') { printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n", (char *) *data); return 1; } if (*options == ',') options++; *data = (void *) options; return sb_block; } #define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3)) static char deprecated_msg[] = "Mount option \"%s\" will be removed by %s\n" "Contact linux-ext4@vger.kernel.org if you think we should keep it.\n"; #ifdef CONFIG_QUOTA static int set_qf_name(struct super_block *sb, int qtype, substring_t *args) { struct ext4_sb_info *sbi = EXT4_SB(sb); char *qname; int ret = -1; if (sb_any_quota_loaded(sb) && !sbi->s_qf_names[qtype]) { ext4_msg(sb, KERN_ERR, "Cannot change journaled " "quota options when quota turned on"); return -1; } if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA)) { ext4_msg(sb, KERN_ERR, "Cannot set journaled quota options " "when QUOTA feature is enabled"); return -1; } qname = match_strdup(args); if (!qname) { ext4_msg(sb, KERN_ERR, "Not enough memory for storing quotafile name"); return -1; } if (sbi->s_qf_names[qtype]) { if (strcmp(sbi->s_qf_names[qtype], qname) == 0) ret = 1; else ext4_msg(sb, KERN_ERR, "%s quota file already specified", QTYPE2NAME(qtype)); goto errout; } if (strchr(qname, '/')) { ext4_msg(sb, KERN_ERR, "quotafile must be on filesystem root"); goto errout; } sbi->s_qf_names[qtype] = qname; set_opt(sb, QUOTA); return 1; errout: kfree(qname); return ret; } static int clear_qf_name(struct super_block *sb, int qtype) { struct ext4_sb_info *sbi = EXT4_SB(sb); if (sb_any_quota_loaded(sb) && sbi->s_qf_names[qtype]) { ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options" " when quota turned on"); return -1; } kfree(sbi->s_qf_names[qtype]); sbi->s_qf_names[qtype] = NULL; return 1; } #endif #define MOPT_SET 0x0001 #define MOPT_CLEAR 0x0002 #define MOPT_NOSUPPORT 0x0004 #define MOPT_EXPLICIT 0x0008 #define MOPT_CLEAR_ERR 0x0010 #define MOPT_GTE0 0x0020 #ifdef CONFIG_QUOTA #define MOPT_Q 0 #define MOPT_QFMT 0x0040 #else #define MOPT_Q MOPT_NOSUPPORT #define MOPT_QFMT MOPT_NOSUPPORT #endif #define MOPT_DATAJ 0x0080 #define MOPT_NO_EXT2 0x0100 #define MOPT_NO_EXT3 0x0200 #define MOPT_EXT4_ONLY (MOPT_NO_EXT2 | MOPT_NO_EXT3) static const struct mount_opts { int token; int mount_opt; int flags; } ext4_mount_opts[] = { {Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET}, {Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR}, {Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET}, {Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR}, {Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET}, {Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR}, {Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK, MOPT_EXT4_ONLY | MOPT_SET}, {Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK, MOPT_EXT4_ONLY | MOPT_CLEAR}, {Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET}, {Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR}, {Opt_delalloc, EXT4_MOUNT_DELALLOC, MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT}, {Opt_nodelalloc, EXT4_MOUNT_DELALLOC, MOPT_EXT4_ONLY | MOPT_CLEAR | MOPT_EXPLICIT}, {Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM, MOPT_EXT4_ONLY | MOPT_SET}, {Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT | EXT4_MOUNT_JOURNAL_CHECKSUM), MOPT_EXT4_ONLY | MOPT_SET}, {Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET}, {Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR}, {Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR}, {Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR}, {Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT, MOPT_NO_EXT2 | MOPT_SET}, {Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT, MOPT_NO_EXT2 | MOPT_CLEAR}, {Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET}, {Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR}, {Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET}, {Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR}, {Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR}, {Opt_commit, 0, MOPT_GTE0}, {Opt_max_batch_time, 0, MOPT_GTE0}, {Opt_min_batch_time, 0, MOPT_GTE0}, {Opt_inode_readahead_blks, 0, MOPT_GTE0}, {Opt_init_itable, 0, MOPT_GTE0}, {Opt_stripe, 0, MOPT_GTE0}, {Opt_resuid, 0, MOPT_GTE0}, {Opt_resgid, 0, MOPT_GTE0}, {Opt_journal_dev, 0, MOPT_GTE0}, {Opt_journal_ioprio, 0, MOPT_GTE0}, {Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ}, {Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ}, {Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA, MOPT_NO_EXT2 | MOPT_DATAJ}, {Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET}, {Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR}, #ifdef CONFIG_EXT4_FS_POSIX_ACL {Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET}, {Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR}, #else {Opt_acl, 0, MOPT_NOSUPPORT}, {Opt_noacl, 0, MOPT_NOSUPPORT}, #endif {Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET}, {Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET}, {Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q}, {Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q}, {Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA, MOPT_SET | MOPT_Q}, {Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA | EXT4_MOUNT_GRPQUOTA), MOPT_CLEAR | MOPT_Q}, {Opt_usrjquota, 0, MOPT_Q}, {Opt_grpjquota, 0, MOPT_Q}, {Opt_offusrjquota, 0, MOPT_Q}, {Opt_offgrpjquota, 0, MOPT_Q}, {Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT}, {Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT}, {Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT}, {Opt_max_dir_size_kb, 0, MOPT_GTE0}, {Opt_err, 0, 0} }; static int handle_mount_opt(struct super_block *sb, char *opt, int token, substring_t *args, unsigned long *journal_devnum, unsigned int *journal_ioprio, int is_remount) { struct ext4_sb_info *sbi = EXT4_SB(sb); const struct mount_opts *m; kuid_t uid; kgid_t gid; int arg = 0; #ifdef CONFIG_QUOTA if (token == Opt_usrjquota) return set_qf_name(sb, USRQUOTA, &args[0]); else if (token == Opt_grpjquota) return set_qf_name(sb, GRPQUOTA, &args[0]); else if (token == Opt_offusrjquota) return clear_qf_name(sb, USRQUOTA); else if (token == Opt_offgrpjquota) return clear_qf_name(sb, GRPQUOTA); #endif switch (token) { case Opt_noacl: case Opt_nouser_xattr: ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5"); break; case Opt_sb: return 1; /* handled by get_sb_block() */ case Opt_removed: ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt); return 1; case Opt_abort: sbi->s_mount_flags |= EXT4_MF_FS_ABORTED; return 1; case Opt_i_version: sb->s_flags |= MS_I_VERSION; return 1; } for (m = ext4_mount_opts; m->token != Opt_err; m++) if (token == m->token) break; if (m->token == Opt_err) { ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" " "or missing value", opt); return -1; } if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) { ext4_msg(sb, KERN_ERR, "Mount option \"%s\" incompatible with ext2", opt); return -1; } if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) { ext4_msg(sb, KERN_ERR, "Mount option \"%s\" incompatible with ext3", opt); return -1; } if (args->from && match_int(args, &arg)) return -1; if (args->from && (m->flags & MOPT_GTE0) && (arg < 0)) return -1; if (m->flags & MOPT_EXPLICIT) set_opt2(sb, EXPLICIT_DELALLOC); if (m->flags & MOPT_CLEAR_ERR) clear_opt(sb, ERRORS_MASK); if (token == Opt_noquota && sb_any_quota_loaded(sb)) { ext4_msg(sb, KERN_ERR, "Cannot change quota " "options when quota turned on"); return -1; } if (m->flags & MOPT_NOSUPPORT) { ext4_msg(sb, KERN_ERR, "%s option not supported", opt); } else if (token == Opt_commit) { if (arg == 0) arg = JBD2_DEFAULT_MAX_COMMIT_AGE; sbi->s_commit_interval = HZ * arg; } else if (token == Opt_max_batch_time) { if (arg == 0) arg = EXT4_DEF_MAX_BATCH_TIME; sbi->s_max_batch_time = arg; } else if (token == Opt_min_batch_time) { sbi->s_min_batch_time = arg; } else if (token == Opt_inode_readahead_blks) { if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) { ext4_msg(sb, KERN_ERR, "EXT4-fs: inode_readahead_blks must be " "0 or a power of 2 smaller than 2^31"); return -1; } sbi->s_inode_readahead_blks = arg; } else if (token == Opt_init_itable) { set_opt(sb, INIT_INODE_TABLE); if (!args->from) arg = EXT4_DEF_LI_WAIT_MULT; sbi->s_li_wait_mult = arg; } else if (token == Opt_max_dir_size_kb) { sbi->s_max_dir_size_kb = arg; } else if (token == Opt_stripe) { sbi->s_stripe = arg; } else if (token == Opt_resuid) { uid = make_kuid(current_user_ns(), arg); if (!uid_valid(uid)) { ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg); return -1; } sbi->s_resuid = uid; } else if (token == Opt_resgid) { gid = make_kgid(current_user_ns(), arg); if (!gid_valid(gid)) { ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg); return -1; } sbi->s_resgid = gid; } else if (token == Opt_journal_dev) { if (is_remount) { ext4_msg(sb, KERN_ERR, "Cannot specify journal on remount"); return -1; } *journal_devnum = arg; } else if (token == Opt_journal_ioprio) { if (arg > 7) { ext4_msg(sb, KERN_ERR, "Invalid journal IO priority" " (must be 0-7)"); return -1; } *journal_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg); } else if (m->flags & MOPT_DATAJ) { if (is_remount) { if (!sbi->s_journal) ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option"); else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) { ext4_msg(sb, KERN_ERR, "Cannot change data mode on remount"); return -1; } } else { clear_opt(sb, DATA_FLAGS); sbi->s_mount_opt |= m->mount_opt; } #ifdef CONFIG_QUOTA } else if (m->flags & MOPT_QFMT) { if (sb_any_quota_loaded(sb) && sbi->s_jquota_fmt != m->mount_opt) { ext4_msg(sb, KERN_ERR, "Cannot change journaled " "quota options when quota turned on"); return -1; } if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA)) { ext4_msg(sb, KERN_ERR, "Cannot set journaled quota options " "when QUOTA feature is enabled"); return -1; } sbi->s_jquota_fmt = m->mount_opt; #endif } else { if (!args->from) arg = 1; if (m->flags & MOPT_CLEAR) arg = !arg; else if (unlikely(!(m->flags & MOPT_SET))) { ext4_msg(sb, KERN_WARNING, "buggy handling of option %s", opt); WARN_ON(1); return -1; } if (arg != 0) sbi->s_mount_opt |= m->mount_opt; else sbi->s_mount_opt &= ~m->mount_opt; } return 1; } static int parse_options(char *options, struct super_block *sb, unsigned long *journal_devnum, unsigned int *journal_ioprio, int is_remount) { struct ext4_sb_info *sbi = EXT4_SB(sb); char *p; substring_t args[MAX_OPT_ARGS]; int token; if (!options) return 1; while ((p = strsep(&options, ",")) != NULL) { if (!*p) continue; /* * Initialize args struct so we know whether arg was * found; some options take optional arguments. */ args[0].to = args[0].from = NULL; token = match_token(p, tokens, args); if (handle_mount_opt(sb, p, token, args, journal_devnum, journal_ioprio, is_remount) < 0) return 0; } #ifdef CONFIG_QUOTA if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) && (test_opt(sb, USRQUOTA) || test_opt(sb, GRPQUOTA))) { ext4_msg(sb, KERN_ERR, "Cannot set quota options when QUOTA " "feature is enabled"); return 0; } if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) { if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA]) clear_opt(sb, USRQUOTA); if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA]) clear_opt(sb, GRPQUOTA); if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) { ext4_msg(sb, KERN_ERR, "old and new quota " "format mixing"); return 0; } if (!sbi->s_jquota_fmt) { ext4_msg(sb, KERN_ERR, "journaled quota format " "not specified"); return 0; } } else { if (sbi->s_jquota_fmt) { ext4_msg(sb, KERN_ERR, "journaled quota format " "specified with no journaling " "enabled"); return 0; } } #endif if (test_opt(sb, DIOREAD_NOLOCK)) { int blocksize = BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size); if (blocksize < PAGE_CACHE_SIZE) { ext4_msg(sb, KERN_ERR, "can't mount with " "dioread_nolock if block size != PAGE_SIZE"); return 0; } } return 1; } static inline void ext4_show_quota_options(struct seq_file *seq, struct super_block *sb) { #if defined(CONFIG_QUOTA) struct ext4_sb_info *sbi = EXT4_SB(sb); if (sbi->s_jquota_fmt) { char *fmtname = ""; switch (sbi->s_jquota_fmt) { case QFMT_VFS_OLD: fmtname = "vfsold"; break; case QFMT_VFS_V0: fmtname = "vfsv0"; break; case QFMT_VFS_V1: fmtname = "vfsv1"; break; } seq_printf(seq, ",jqfmt=%s", fmtname); } if (sbi->s_qf_names[USRQUOTA]) seq_printf(seq, ",usrjquota=%s", sbi->s_qf_names[USRQUOTA]); if (sbi->s_qf_names[GRPQUOTA]) seq_printf(seq, ",grpjquota=%s", sbi->s_qf_names[GRPQUOTA]); #endif } static const char *token2str(int token) { const struct match_token *t; for (t = tokens; t->token != Opt_err; t++) if (t->token == token && !strchr(t->pattern, '=')) break; return t->pattern; } /* * Show an option if * - it's set to a non-default value OR * - if the per-sb default is different from the global default */ static int _ext4_show_options(struct seq_file *seq, struct super_block *sb, int nodefs) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; int def_errors, def_mount_opt = nodefs ? 0 : sbi->s_def_mount_opt; const struct mount_opts *m; char sep = nodefs ? '\n' : ','; #define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep) #define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg) if (sbi->s_sb_block != 1) SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block); for (m = ext4_mount_opts; m->token != Opt_err; m++) { int want_set = m->flags & MOPT_SET; if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) || (m->flags & MOPT_CLEAR_ERR)) continue; if (!(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt))) continue; /* skip if same as the default */ if ((want_set && (sbi->s_mount_opt & m->mount_opt) != m->mount_opt) || (!want_set && (sbi->s_mount_opt & m->mount_opt))) continue; /* select Opt_noFoo vs Opt_Foo */ SEQ_OPTS_PRINT("%s", token2str(m->token)); } if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) || le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID) SEQ_OPTS_PRINT("resuid=%u", from_kuid_munged(&init_user_ns, sbi->s_resuid)); if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) || le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID) SEQ_OPTS_PRINT("resgid=%u", from_kgid_munged(&init_user_ns, sbi->s_resgid)); def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors); if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO) SEQ_OPTS_PUTS("errors=remount-ro"); if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE) SEQ_OPTS_PUTS("errors=continue"); if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC) SEQ_OPTS_PUTS("errors=panic"); if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ); if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME) SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time); if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME) SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time); if (sb->s_flags & MS_I_VERSION) SEQ_OPTS_PUTS("i_version"); if (nodefs || sbi->s_stripe) SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe); if (EXT4_MOUNT_DATA_FLAGS & (sbi->s_mount_opt ^ def_mount_opt)) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) SEQ_OPTS_PUTS("data=journal"); else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) SEQ_OPTS_PUTS("data=ordered"); else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA) SEQ_OPTS_PUTS("data=writeback"); } if (nodefs || sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS) SEQ_OPTS_PRINT("inode_readahead_blks=%u", sbi->s_inode_readahead_blks); if (nodefs || (test_opt(sb, INIT_INODE_TABLE) && (sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT))) SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult); if (nodefs || sbi->s_max_dir_size_kb) SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb); ext4_show_quota_options(seq, sb); return 0; } static int ext4_show_options(struct seq_file *seq, struct dentry *root) { return _ext4_show_options(seq, root->d_sb, 0); } static int options_seq_show(struct seq_file *seq, void *offset) { struct super_block *sb = seq->private; int rc; seq_puts(seq, (sb->s_flags & MS_RDONLY) ? "ro" : "rw"); rc = _ext4_show_options(seq, sb, 1); seq_puts(seq, "\n"); return rc; } static int options_open_fs(struct inode *inode, struct file *file) { return single_open(file, options_seq_show, PDE_DATA(inode)); } static const struct file_operations ext4_seq_options_fops = { .owner = THIS_MODULE, .open = options_open_fs, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es, int read_only) { struct ext4_sb_info *sbi = EXT4_SB(sb); int res = 0; if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) { ext4_msg(sb, KERN_ERR, "revision level too high, " "forcing read-only mode"); res = MS_RDONLY; } if (read_only) goto done; if (!(sbi->s_mount_state & EXT4_VALID_FS)) ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, " "running e2fsck is recommended"); else if ((sbi->s_mount_state & EXT4_ERROR_FS)) ext4_msg(sb, KERN_WARNING, "warning: mounting fs with errors, " "running e2fsck is recommended"); else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 && le16_to_cpu(es->s_mnt_count) >= (unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count)) ext4_msg(sb, KERN_WARNING, "warning: maximal mount count reached, " "running e2fsck is recommended"); else if (le32_to_cpu(es->s_checkinterval) && (le32_to_cpu(es->s_lastcheck) + le32_to_cpu(es->s_checkinterval) <= get_seconds())) ext4_msg(sb, KERN_WARNING, "warning: checktime reached, " "running e2fsck is recommended"); if (!sbi->s_journal) es->s_state &= cpu_to_le16(~EXT4_VALID_FS); if (!(__s16) le16_to_cpu(es->s_max_mnt_count)) es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT); le16_add_cpu(&es->s_mnt_count, 1); es->s_mtime = cpu_to_le32(get_seconds()); ext4_update_dynamic_rev(sb); if (sbi->s_journal) EXT4_SET_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER); ext4_commit_super(sb, 1); done: if (test_opt(sb, DEBUG)) printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, " "bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n", sb->s_blocksize, sbi->s_groups_count, EXT4_BLOCKS_PER_GROUP(sb), EXT4_INODES_PER_GROUP(sb), sbi->s_mount_opt, sbi->s_mount_opt2); cleancache_init_fs(sb); return res; } int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct flex_groups *new_groups; int size; if (!sbi->s_log_groups_per_flex) return 0; size = ext4_flex_group(sbi, ngroup - 1) + 1; if (size <= sbi->s_flex_groups_allocated) return 0; size = roundup_pow_of_two(size * sizeof(struct flex_groups)); new_groups = ext4_kvzalloc(size, GFP_KERNEL); if (!new_groups) { ext4_msg(sb, KERN_ERR, "not enough memory for %d flex groups", size / (int) sizeof(struct flex_groups)); return -ENOMEM; } if (sbi->s_flex_groups) { memcpy(new_groups, sbi->s_flex_groups, (sbi->s_flex_groups_allocated * sizeof(struct flex_groups))); ext4_kvfree(sbi->s_flex_groups); } sbi->s_flex_groups = new_groups; sbi->s_flex_groups_allocated = size / sizeof(struct flex_groups); return 0; } static int ext4_fill_flex_info(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_group_desc *gdp = NULL; ext4_group_t flex_group; int i, err; sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) { sbi->s_log_groups_per_flex = 0; return 1; } err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count); if (err) goto failed; for (i = 0; i < sbi->s_groups_count; i++) { gdp = ext4_get_group_desc(sb, i, NULL); flex_group = ext4_flex_group(sbi, i); atomic_add(ext4_free_inodes_count(sb, gdp), &sbi->s_flex_groups[flex_group].free_inodes); atomic64_add(ext4_free_group_clusters(sb, gdp), &sbi->s_flex_groups[flex_group].free_clusters); atomic_add(ext4_used_dirs_count(sb, gdp), &sbi->s_flex_groups[flex_group].used_dirs); } return 1; failed: return 0; } static __le16 ext4_group_desc_csum(struct ext4_sb_info *sbi, __u32 block_group, struct ext4_group_desc *gdp) { int offset; __u16 crc = 0; __le32 le_group = cpu_to_le32(block_group); if ((sbi->s_es->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))) { /* Use new metadata_csum algorithm */ __le16 save_csum; __u32 csum32; save_csum = gdp->bg_checksum; gdp->bg_checksum = 0; csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group, sizeof(le_group)); csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp, sbi->s_desc_size); gdp->bg_checksum = save_csum; crc = csum32 & 0xFFFF; goto out; } /* old crc16 code */ offset = offsetof(struct ext4_group_desc, bg_checksum); crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid)); crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group)); crc = crc16(crc, (__u8 *)gdp, offset); offset += sizeof(gdp->bg_checksum); /* skip checksum */ /* for checksum of struct ext4_group_desc do the rest...*/ if ((sbi->s_es->s_feature_incompat & cpu_to_le32(EXT4_FEATURE_INCOMPAT_64BIT)) && offset < le16_to_cpu(sbi->s_es->s_desc_size)) crc = crc16(crc, (__u8 *)gdp + offset, le16_to_cpu(sbi->s_es->s_desc_size) - offset); out: return cpu_to_le16(crc); } int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group, struct ext4_group_desc *gdp) { if (ext4_has_group_desc_csum(sb) && (gdp->bg_checksum != ext4_group_desc_csum(EXT4_SB(sb), block_group, gdp))) return 0; return 1; } void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group, struct ext4_group_desc *gdp) { if (!ext4_has_group_desc_csum(sb)) return; gdp->bg_checksum = ext4_group_desc_csum(EXT4_SB(sb), block_group, gdp); } /* Called at mount-time, super-block is locked */ static int ext4_check_descriptors(struct super_block *sb, ext4_group_t *first_not_zeroed) { struct ext4_sb_info *sbi = EXT4_SB(sb); ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block); ext4_fsblk_t last_block; ext4_fsblk_t block_bitmap; ext4_fsblk_t inode_bitmap; ext4_fsblk_t inode_table; int flexbg_flag = 0; ext4_group_t i, grp = sbi->s_groups_count; if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) flexbg_flag = 1; ext4_debug("Checking group descriptors"); for (i = 0; i < sbi->s_groups_count; i++) { struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL); if (i == sbi->s_groups_count - 1 || flexbg_flag) last_block = ext4_blocks_count(sbi->s_es) - 1; else last_block = first_block + (EXT4_BLOCKS_PER_GROUP(sb) - 1); if ((grp == sbi->s_groups_count) && !(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))) grp = i; block_bitmap = ext4_block_bitmap(sb, gdp); if (block_bitmap < first_block || block_bitmap > last_block) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Block bitmap for group %u not in group " "(block %llu)!", i, block_bitmap); return 0; } inode_bitmap = ext4_inode_bitmap(sb, gdp); if (inode_bitmap < first_block || inode_bitmap > last_block) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Inode bitmap for group %u not in group " "(block %llu)!", i, inode_bitmap); return 0; } inode_table = ext4_inode_table(sb, gdp); if (inode_table < first_block || inode_table + sbi->s_itb_per_group - 1 > last_block) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Inode table for group %u not in group " "(block %llu)!", i, inode_table); return 0; } ext4_lock_group(sb, i); if (!ext4_group_desc_csum_verify(sb, i, gdp)) { ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: " "Checksum for group %u failed (%u!=%u)", i, le16_to_cpu(ext4_group_desc_csum(sbi, i, gdp)), le16_to_cpu(gdp->bg_checksum)); if (!(sb->s_flags & MS_RDONLY)) { ext4_unlock_group(sb, i); return 0; } } ext4_unlock_group(sb, i); if (!flexbg_flag) first_block += EXT4_BLOCKS_PER_GROUP(sb); } if (NULL != first_not_zeroed) *first_not_zeroed = grp; ext4_free_blocks_count_set(sbi->s_es, EXT4_C2B(sbi, ext4_count_free_clusters(sb))); sbi->s_es->s_free_inodes_count =cpu_to_le32(ext4_count_free_inodes(sb)); return 1; } /* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at * the superblock) which were deleted from all directories, but held open by * a process at the time of a crash. We walk the list and try to delete these * inodes at recovery time (only with a read-write filesystem). * * In order to keep the orphan inode chain consistent during traversal (in * case of crash during recovery), we link each inode into the superblock * orphan list_head and handle it the same way as an inode deletion during * normal operation (which journals the operations for us). * * We only do an iget() and an iput() on each inode, which is very safe if we * accidentally point at an in-use or already deleted inode. The worst that * can happen in this case is that we get a "bit already cleared" message from * ext4_free_inode(). The only reason we would point at a wrong inode is if * e2fsck was run on this filesystem, and it must have already done the orphan * inode cleanup for us, so we can safely abort without any further action. */ static void ext4_orphan_cleanup(struct super_block *sb, struct ext4_super_block *es) { unsigned int s_flags = sb->s_flags; int nr_orphans = 0, nr_truncates = 0; #ifdef CONFIG_QUOTA int i; #endif if (!es->s_last_orphan) { jbd_debug(4, "no orphan inodes to clean up\n"); return; } if (bdev_read_only(sb->s_bdev)) { ext4_msg(sb, KERN_ERR, "write access " "unavailable, skipping orphan cleanup"); return; } /* Check if feature set would not allow a r/w mount */ if (!ext4_feature_set_ok(sb, 0)) { ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to " "unknown ROCOMPAT features"); return; } if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) { /* don't clear list on RO mount w/ errors */ if (es->s_last_orphan && !(s_flags & MS_RDONLY)) { jbd_debug(1, "Errors on filesystem, " "clearing orphan list.\n"); es->s_last_orphan = 0; } jbd_debug(1, "Skipping orphan recovery on fs with errors.\n"); return; } if (s_flags & MS_RDONLY) { ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs"); sb->s_flags &= ~MS_RDONLY; } #ifdef CONFIG_QUOTA /* Needed for iput() to work correctly and not trash data */ sb->s_flags |= MS_ACTIVE; /* Turn on quotas so that they are updated correctly */ for (i = 0; i < MAXQUOTAS; i++) { if (EXT4_SB(sb)->s_qf_names[i]) { int ret = ext4_quota_on_mount(sb, i); if (ret < 0) ext4_msg(sb, KERN_ERR, "Cannot turn on journaled " "quota: error %d", ret); } } #endif while (es->s_last_orphan) { struct inode *inode; inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan)); if (IS_ERR(inode)) { es->s_last_orphan = 0; break; } list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan); dquot_initialize(inode); if (inode->i_nlink) { if (test_opt(sb, DEBUG)) ext4_msg(sb, KERN_DEBUG, "%s: truncating inode %lu to %lld bytes", __func__, inode->i_ino, inode->i_size); jbd_debug(2, "truncating inode %lu to %lld bytes\n", inode->i_ino, inode->i_size); mutex_lock(&inode->i_mutex); truncate_inode_pages(inode->i_mapping, inode->i_size); ext4_truncate(inode); mutex_unlock(&inode->i_mutex); nr_truncates++; } else { if (test_opt(sb, DEBUG)) ext4_msg(sb, KERN_DEBUG, "%s: deleting unreferenced inode %lu", __func__, inode->i_ino); jbd_debug(2, "deleting unreferenced inode %lu\n", inode->i_ino); nr_orphans++; } iput(inode); /* The delete magic happens here! */ } #define PLURAL(x) (x), ((x) == 1) ? "" : "s" if (nr_orphans) ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted", PLURAL(nr_orphans)); if (nr_truncates) ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up", PLURAL(nr_truncates)); #ifdef CONFIG_QUOTA /* Turn quotas off */ for (i = 0; i < MAXQUOTAS; i++) { if (sb_dqopt(sb)->files[i]) dquot_quota_off(sb, i); } #endif sb->s_flags = s_flags; /* Restore MS_RDONLY status */ } /* * Maximal extent format file size. * Resulting logical blkno at s_maxbytes must fit in our on-disk * extent format containers, within a sector_t, and within i_blocks * in the vfs. ext4 inode has 48 bits of i_block in fsblock units, * so that won't be a limiting factor. * * However there is other limiting factor. We do store extents in the form * of starting block and length, hence the resulting length of the extent * covering maximum file size must fit into on-disk format containers as * well. Given that length is always by 1 unit bigger than max unit (because * we count 0 as well) we have to lower the s_maxbytes by one fs block. * * Note, this does *not* consider any metadata overhead for vfs i_blocks. */ static loff_t ext4_max_size(int blkbits, int has_huge_files) { loff_t res; loff_t upper_limit = MAX_LFS_FILESIZE; /* small i_blocks in vfs inode? */ if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) { /* * CONFIG_LBDAF is not enabled implies the inode * i_block represent total blocks in 512 bytes * 32 == size of vfs inode i_blocks * 8 */ upper_limit = (1LL << 32) - 1; /* total blocks in file system block size */ upper_limit >>= (blkbits - 9); upper_limit <<= blkbits; } /* * 32-bit extent-start container, ee_block. We lower the maxbytes * by one fs block, so ee_len can cover the extent of maximum file * size */ res = (1LL << 32) - 1; res <<= blkbits; /* Sanity check against vm- & vfs- imposed limits */ if (res > upper_limit) res = upper_limit; return res; } /* * Maximal bitmap file size. There is a direct, and {,double-,triple-}indirect * block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks. * We need to be 1 filesystem block less than the 2^48 sector limit. */ static loff_t ext4_max_bitmap_size(int bits, int has_huge_files) { loff_t res = EXT4_NDIR_BLOCKS; int meta_blocks; loff_t upper_limit; /* This is calculated to be the largest file size for a dense, block * mapped file such that the file's total number of 512-byte sectors, * including data and all indirect blocks, does not exceed (2^48 - 1). * * __u32 i_blocks_lo and _u16 i_blocks_high represent the total * number of 512-byte sectors of the file. */ if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) { /* * !has_huge_files or CONFIG_LBDAF not enabled implies that * the inode i_block field represents total file blocks in * 2^32 512-byte sectors == size of vfs inode i_blocks * 8 */ upper_limit = (1LL << 32) - 1; /* total blocks in file system block size */ upper_limit >>= (bits - 9); } else { /* * We use 48 bit ext4_inode i_blocks * With EXT4_HUGE_FILE_FL set the i_blocks * represent total number of blocks in * file system block size */ upper_limit = (1LL << 48) - 1; } /* indirect blocks */ meta_blocks = 1; /* double indirect blocks */ meta_blocks += 1 + (1LL << (bits-2)); /* tripple indirect blocks */ meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2))); upper_limit -= meta_blocks; upper_limit <<= bits; res += 1LL << (bits-2); res += 1LL << (2*(bits-2)); res += 1LL << (3*(bits-2)); res <<= bits; if (res > upper_limit) res = upper_limit; if (res > MAX_LFS_FILESIZE) res = MAX_LFS_FILESIZE; return res; } static ext4_fsblk_t descriptor_loc(struct super_block *sb, ext4_fsblk_t logical_sb_block, int nr) { struct ext4_sb_info *sbi = EXT4_SB(sb); ext4_group_t bg, first_meta_bg; int has_super = 0; first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg); if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_META_BG) || nr < first_meta_bg) return logical_sb_block + nr + 1; bg = sbi->s_desc_per_block * nr; if (ext4_bg_has_super(sb, bg)) has_super = 1; return (has_super + ext4_group_first_block_no(sb, bg)); } /** * ext4_get_stripe_size: Get the stripe size. * @sbi: In memory super block info * * If we have specified it via mount option, then * use the mount option value. If the value specified at mount time is * greater than the blocks per group use the super block value. * If the super block value is greater than blocks per group return 0. * Allocator needs it be less than blocks per group. * */ static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi) { unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride); unsigned long stripe_width = le32_to_cpu(sbi->s_es->s_raid_stripe_width); int ret; if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group) ret = sbi->s_stripe; else if (stripe_width <= sbi->s_blocks_per_group) ret = stripe_width; else if (stride <= sbi->s_blocks_per_group) ret = stride; else ret = 0; /* * If the stripe width is 1, this makes no sense and * we set it to 0 to turn off stripe handling code. */ if (ret <= 1) ret = 0; return ret; } /* sysfs supprt */ struct ext4_attr { struct attribute attr; ssize_t (*show)(struct ext4_attr *, struct ext4_sb_info *, char *); ssize_t (*store)(struct ext4_attr *, struct ext4_sb_info *, const char *, size_t); union { int offset; int deprecated_val; } u; }; static int parse_strtoull(const char *buf, unsigned long long max, unsigned long long *value) { int ret; ret = kstrtoull(skip_spaces(buf), 0, value); if (!ret && *value > max) ret = -EINVAL; return ret; } static ssize_t delayed_allocation_blocks_show(struct ext4_attr *a, struct ext4_sb_info *sbi, char *buf) { return snprintf(buf, PAGE_SIZE, "%llu\n", (s64) EXT4_C2B(sbi, percpu_counter_sum(&sbi->s_dirtyclusters_counter))); } static ssize_t session_write_kbytes_show(struct ext4_attr *a, struct ext4_sb_info *sbi, char *buf) { struct super_block *sb = sbi->s_buddy_cache->i_sb; if (!sb->s_bdev->bd_part) return snprintf(buf, PAGE_SIZE, "0\n"); return snprintf(buf, PAGE_SIZE, "%lu\n", (part_stat_read(sb->s_bdev->bd_part, sectors[1]) - sbi->s_sectors_written_start) >> 1); } static ssize_t lifetime_write_kbytes_show(struct ext4_attr *a, struct ext4_sb_info *sbi, char *buf) { struct super_block *sb = sbi->s_buddy_cache->i_sb; if (!sb->s_bdev->bd_part) return snprintf(buf, PAGE_SIZE, "0\n"); return snprintf(buf, PAGE_SIZE, "%llu\n", (unsigned long long)(sbi->s_kbytes_written + ((part_stat_read(sb->s_bdev->bd_part, sectors[1]) - EXT4_SB(sb)->s_sectors_written_start) >> 1))); } static ssize_t inode_readahead_blks_store(struct ext4_attr *a, struct ext4_sb_info *sbi, const char *buf, size_t count) { unsigned long t; int ret; ret = kstrtoul(skip_spaces(buf), 0, &t); if (ret) return ret; if (t && (!is_power_of_2(t) || t > 0x40000000)) return -EINVAL; sbi->s_inode_readahead_blks = t; return count; } static ssize_t sbi_ui_show(struct ext4_attr *a, struct ext4_sb_info *sbi, char *buf) { unsigned int *ui = (unsigned int *) (((char *) sbi) + a->u.offset); return snprintf(buf, PAGE_SIZE, "%u\n", *ui); } static ssize_t sbi_ui_store(struct ext4_attr *a, struct ext4_sb_info *sbi, const char *buf, size_t count) { unsigned int *ui = (unsigned int *) (((char *) sbi) + a->u.offset); unsigned long t; int ret; ret = kstrtoul(skip_spaces(buf), 0, &t); if (ret) return ret; *ui = t; return count; } static ssize_t reserved_clusters_show(struct ext4_attr *a, struct ext4_sb_info *sbi, char *buf) { return snprintf(buf, PAGE_SIZE, "%llu\n", (unsigned long long) atomic64_read(&sbi->s_resv_clusters)); } static ssize_t reserved_clusters_store(struct ext4_attr *a, struct ext4_sb_info *sbi, const char *buf, size_t count) { unsigned long long val; int ret; if (parse_strtoull(buf, -1ULL, &val)) return -EINVAL; ret = ext4_reserve_clusters(sbi, val); return ret ? ret : count; } static ssize_t trigger_test_error(struct ext4_attr *a, struct ext4_sb_info *sbi, const char *buf, size_t count) { int len = count; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (len && buf[len-1] == '\n') len--; if (len) ext4_error(sbi->s_sb, "%.*s", len, buf); return count; } static ssize_t sbi_deprecated_show(struct ext4_attr *a, struct ext4_sb_info *sbi, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", a->u.deprecated_val); } #define EXT4_ATTR_OFFSET(_name,_mode,_show,_store,_elname) \ static struct ext4_attr ext4_attr_##_name = { \ .attr = {.name = __stringify(_name), .mode = _mode }, \ .show = _show, \ .store = _store, \ .u = { \ .offset = offsetof(struct ext4_sb_info, _elname),\ }, \ } #define EXT4_ATTR(name, mode, show, store) \ static struct ext4_attr ext4_attr_##name = __ATTR(name, mode, show, store) #define EXT4_INFO_ATTR(name) EXT4_ATTR(name, 0444, NULL, NULL) #define EXT4_RO_ATTR(name) EXT4_ATTR(name, 0444, name##_show, NULL) #define EXT4_RW_ATTR(name) EXT4_ATTR(name, 0644, name##_show, name##_store) #define EXT4_RW_ATTR_SBI_UI(name, elname) \ EXT4_ATTR_OFFSET(name, 0644, sbi_ui_show, sbi_ui_store, elname) #define ATTR_LIST(name) &ext4_attr_##name.attr #define EXT4_DEPRECATED_ATTR(_name, _val) \ static struct ext4_attr ext4_attr_##_name = { \ .attr = {.name = __stringify(_name), .mode = 0444 }, \ .show = sbi_deprecated_show, \ .u = { \ .deprecated_val = _val, \ }, \ } EXT4_RO_ATTR(delayed_allocation_blocks); EXT4_RO_ATTR(session_write_kbytes); EXT4_RO_ATTR(lifetime_write_kbytes); EXT4_RW_ATTR(reserved_clusters); EXT4_ATTR_OFFSET(inode_readahead_blks, 0644, sbi_ui_show, inode_readahead_blks_store, s_inode_readahead_blks); EXT4_RW_ATTR_SBI_UI(inode_goal, s_inode_goal); EXT4_RW_ATTR_SBI_UI(mb_stats, s_mb_stats); EXT4_RW_ATTR_SBI_UI(mb_max_to_scan, s_mb_max_to_scan); EXT4_RW_ATTR_SBI_UI(mb_min_to_scan, s_mb_min_to_scan); EXT4_RW_ATTR_SBI_UI(mb_order2_req, s_mb_order2_reqs); EXT4_RW_ATTR_SBI_UI(mb_stream_req, s_mb_stream_request); EXT4_RW_ATTR_SBI_UI(mb_group_prealloc, s_mb_group_prealloc); EXT4_DEPRECATED_ATTR(max_writeback_mb_bump, 128); EXT4_RW_ATTR_SBI_UI(extent_max_zeroout_kb, s_extent_max_zeroout_kb); EXT4_ATTR(trigger_fs_error, 0200, NULL, trigger_test_error); static struct attribute *ext4_attrs[] = { ATTR_LIST(delayed_allocation_blocks), ATTR_LIST(session_write_kbytes), ATTR_LIST(lifetime_write_kbytes), ATTR_LIST(reserved_clusters), ATTR_LIST(inode_readahead_blks), ATTR_LIST(inode_goal), ATTR_LIST(mb_stats), ATTR_LIST(mb_max_to_scan), ATTR_LIST(mb_min_to_scan), ATTR_LIST(mb_order2_req), ATTR_LIST(mb_stream_req), ATTR_LIST(mb_group_prealloc), ATTR_LIST(max_writeback_mb_bump), ATTR_LIST(extent_max_zeroout_kb), ATTR_LIST(trigger_fs_error), NULL, }; /* Features this copy of ext4 supports */ EXT4_INFO_ATTR(lazy_itable_init); EXT4_INFO_ATTR(batched_discard); EXT4_INFO_ATTR(meta_bg_resize); static struct attribute *ext4_feat_attrs[] = { ATTR_LIST(lazy_itable_init), ATTR_LIST(batched_discard), ATTR_LIST(meta_bg_resize), NULL, }; static ssize_t ext4_attr_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info, s_kobj); struct ext4_attr *a = container_of(attr, struct ext4_attr, attr); return a->show ? a->show(a, sbi, buf) : 0; } static ssize_t ext4_attr_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t len) { struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info, s_kobj); struct ext4_attr *a = container_of(attr, struct ext4_attr, attr); return a->store ? a->store(a, sbi, buf, len) : 0; } static void ext4_sb_release(struct kobject *kobj) { struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info, s_kobj); complete(&sbi->s_kobj_unregister); } static const struct sysfs_ops ext4_attr_ops = { .show = ext4_attr_show, .store = ext4_attr_store, }; static struct kobj_type ext4_ktype = { .default_attrs = ext4_attrs, .sysfs_ops = &ext4_attr_ops, .release = ext4_sb_release, }; static void ext4_feat_release(struct kobject *kobj) { complete(&ext4_feat->f_kobj_unregister); } static struct kobj_type ext4_feat_ktype = { .default_attrs = ext4_feat_attrs, .sysfs_ops = &ext4_attr_ops, .release = ext4_feat_release, }; /* * Check whether this filesystem can be mounted based on * the features present and the RDONLY/RDWR mount requested. * Returns 1 if this filesystem can be mounted as requested, * 0 if it cannot be. */ static int ext4_feature_set_ok(struct super_block *sb, int readonly) { if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT4_FEATURE_INCOMPAT_SUPP)) { ext4_msg(sb, KERN_ERR, "Couldn't mount because of " "unsupported optional features (%x)", (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) & ~EXT4_FEATURE_INCOMPAT_SUPP)); return 0; } if (readonly) return 1; /* Check that feature set is OK for a read-write mount */ if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT4_FEATURE_RO_COMPAT_SUPP)) { ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of " "unsupported optional features (%x)", (le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) & ~EXT4_FEATURE_RO_COMPAT_SUPP)); return 0; } /* * Large file size enabled file system can only be mounted * read-write on 32-bit systems if kernel is built with CONFIG_LBDAF */ if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) { if (sizeof(blkcnt_t) < sizeof(u64)) { ext4_msg(sb, KERN_ERR, "Filesystem with huge files " "cannot be mounted RDWR without " "CONFIG_LBDAF"); return 0; } } if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_BIGALLOC) && !EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) { ext4_msg(sb, KERN_ERR, "Can't support bigalloc feature without " "extents feature\n"); return 0; } #ifndef CONFIG_QUOTA if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) && !readonly) { ext4_msg(sb, KERN_ERR, "Filesystem with quota feature cannot be mounted RDWR " "without CONFIG_QUOTA"); return 0; } #endif /* CONFIG_QUOTA */ return 1; } /* * This function is called once a day if we have errors logged * on the file system */ static void print_daily_error_info(unsigned long arg) { struct super_block *sb = (struct super_block *) arg; struct ext4_sb_info *sbi; struct ext4_super_block *es; sbi = EXT4_SB(sb); es = sbi->s_es; if (es->s_error_count) ext4_msg(sb, KERN_NOTICE, "error count: %u", le32_to_cpu(es->s_error_count)); if (es->s_first_error_time) { printk(KERN_NOTICE "EXT4-fs (%s): initial error at %u: %.*s:%d", sb->s_id, le32_to_cpu(es->s_first_error_time), (int) sizeof(es->s_first_error_func), es->s_first_error_func, le32_to_cpu(es->s_first_error_line)); if (es->s_first_error_ino) printk(": inode %u", le32_to_cpu(es->s_first_error_ino)); if (es->s_first_error_block) printk(": block %llu", (unsigned long long) le64_to_cpu(es->s_first_error_block)); printk("\n"); } if (es->s_last_error_time) { printk(KERN_NOTICE "EXT4-fs (%s): last error at %u: %.*s:%d", sb->s_id, le32_to_cpu(es->s_last_error_time), (int) sizeof(es->s_last_error_func), es->s_last_error_func, le32_to_cpu(es->s_last_error_line)); if (es->s_last_error_ino) printk(": inode %u", le32_to_cpu(es->s_last_error_ino)); if (es->s_last_error_block) printk(": block %llu", (unsigned long long) le64_to_cpu(es->s_last_error_block)); printk("\n"); } mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ); /* Once a day */ } /* Find next suitable group and run ext4_init_inode_table */ static int ext4_run_li_request(struct ext4_li_request *elr) { struct ext4_group_desc *gdp = NULL; ext4_group_t group, ngroups; struct super_block *sb; unsigned long timeout = 0; int ret = 0; sb = elr->lr_super; ngroups = EXT4_SB(sb)->s_groups_count; sb_start_write(sb); for (group = elr->lr_next_group; group < ngroups; group++) { gdp = ext4_get_group_desc(sb, group, NULL); if (!gdp) { ret = 1; break; } if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))) break; } if (group >= ngroups) ret = 1; if (!ret) { timeout = jiffies; ret = ext4_init_inode_table(sb, group, elr->lr_timeout ? 0 : 1); if (elr->lr_timeout == 0) { timeout = (jiffies - timeout) * elr->lr_sbi->s_li_wait_mult; elr->lr_timeout = timeout; } elr->lr_next_sched = jiffies + elr->lr_timeout; elr->lr_next_group = group + 1; } sb_end_write(sb); return ret; } /* * Remove lr_request from the list_request and free the * request structure. Should be called with li_list_mtx held */ static void ext4_remove_li_request(struct ext4_li_request *elr) { struct ext4_sb_info *sbi; if (!elr) return; sbi = elr->lr_sbi; list_del(&elr->lr_request); sbi->s_li_request = NULL; kfree(elr); } static void ext4_unregister_li_request(struct super_block *sb) { mutex_lock(&ext4_li_mtx); if (!ext4_li_info) { mutex_unlock(&ext4_li_mtx); return; } mutex_lock(&ext4_li_info->li_list_mtx); ext4_remove_li_request(EXT4_SB(sb)->s_li_request); mutex_unlock(&ext4_li_info->li_list_mtx); mutex_unlock(&ext4_li_mtx); } static struct task_struct *ext4_lazyinit_task; /* * This is the function where ext4lazyinit thread lives. It walks * through the request list searching for next scheduled filesystem. * When such a fs is found, run the lazy initialization request * (ext4_rn_li_request) and keep track of the time spend in this * function. Based on that time we compute next schedule time of * the request. When walking through the list is complete, compute * next waking time and put itself into sleep. */ static int ext4_lazyinit_thread(void *arg) { struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg; struct list_head *pos, *n; struct ext4_li_request *elr; unsigned long next_wakeup, cur; BUG_ON(NULL == eli); cont_thread: while (true) { next_wakeup = MAX_JIFFY_OFFSET; mutex_lock(&eli->li_list_mtx); if (list_empty(&eli->li_request_list)) { mutex_unlock(&eli->li_list_mtx); goto exit_thread; } list_for_each_safe(pos, n, &eli->li_request_list) { elr = list_entry(pos, struct ext4_li_request, lr_request); if (time_after_eq(jiffies, elr->lr_next_sched)) { if (ext4_run_li_request(elr) != 0) { /* error, remove the lazy_init job */ ext4_remove_li_request(elr); continue; } } if (time_before(elr->lr_next_sched, next_wakeup)) next_wakeup = elr->lr_next_sched; } mutex_unlock(&eli->li_list_mtx); try_to_freeze(); cur = jiffies; if ((time_after_eq(cur, next_wakeup)) || (MAX_JIFFY_OFFSET == next_wakeup)) { cond_resched(); continue; } schedule_timeout_interruptible(next_wakeup - cur); if (kthread_should_stop()) { ext4_clear_request_list(); goto exit_thread; } } exit_thread: /* * It looks like the request list is empty, but we need * to check it under the li_list_mtx lock, to prevent any * additions into it, and of course we should lock ext4_li_mtx * to atomically free the list and ext4_li_info, because at * this point another ext4 filesystem could be registering * new one. */ mutex_lock(&ext4_li_mtx); mutex_lock(&eli->li_list_mtx); if (!list_empty(&eli->li_request_list)) { mutex_unlock(&eli->li_list_mtx); mutex_unlock(&ext4_li_mtx); goto cont_thread; } mutex_unlock(&eli->li_list_mtx); kfree(ext4_li_info); ext4_li_info = NULL; mutex_unlock(&ext4_li_mtx); return 0; } static void ext4_clear_request_list(void) { struct list_head *pos, *n; struct ext4_li_request *elr; mutex_lock(&ext4_li_info->li_list_mtx); list_for_each_safe(pos, n, &ext4_li_info->li_request_list) { elr = list_entry(pos, struct ext4_li_request, lr_request); ext4_remove_li_request(elr); } mutex_unlock(&ext4_li_info->li_list_mtx); } static int ext4_run_lazyinit_thread(void) { ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread, ext4_li_info, "ext4lazyinit"); if (IS_ERR(ext4_lazyinit_task)) { int err = PTR_ERR(ext4_lazyinit_task); ext4_clear_request_list(); kfree(ext4_li_info); ext4_li_info = NULL; printk(KERN_CRIT "EXT4-fs: error %d creating inode table " "initialization thread\n", err); return err; } ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING; return 0; } /* * Check whether it make sense to run itable init. thread or not. * If there is at least one uninitialized inode table, return * corresponding group number, else the loop goes through all * groups and return total number of groups. */ static ext4_group_t ext4_has_uninit_itable(struct super_block *sb) { ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count; struct ext4_group_desc *gdp = NULL; for (group = 0; group < ngroups; group++) { gdp = ext4_get_group_desc(sb, group, NULL); if (!gdp) continue; if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED))) break; } return group; } static int ext4_li_info_new(void) { struct ext4_lazy_init *eli = NULL; eli = kzalloc(sizeof(*eli), GFP_KERNEL); if (!eli) return -ENOMEM; INIT_LIST_HEAD(&eli->li_request_list); mutex_init(&eli->li_list_mtx); eli->li_state |= EXT4_LAZYINIT_QUIT; ext4_li_info = eli; return 0; } static struct ext4_li_request *ext4_li_request_new(struct super_block *sb, ext4_group_t start) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_li_request *elr; unsigned long rnd; elr = kzalloc(sizeof(*elr), GFP_KERNEL); if (!elr) return NULL; elr->lr_super = sb; elr->lr_sbi = sbi; elr->lr_next_group = start; /* * Randomize first schedule time of the request to * spread the inode table initialization requests * better. */ get_random_bytes(&rnd, sizeof(rnd)); elr->lr_next_sched = jiffies + (unsigned long)rnd % (EXT4_DEF_LI_MAX_START_DELAY * HZ); return elr; } int ext4_register_li_request(struct super_block *sb, ext4_group_t first_not_zeroed) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_li_request *elr = NULL; ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count; int ret = 0; mutex_lock(&ext4_li_mtx); if (sbi->s_li_request != NULL) { /* * Reset timeout so it can be computed again, because * s_li_wait_mult might have changed. */ sbi->s_li_request->lr_timeout = 0; goto out; } if (first_not_zeroed == ngroups || (sb->s_flags & MS_RDONLY) || !test_opt(sb, INIT_INODE_TABLE)) goto out; elr = ext4_li_request_new(sb, first_not_zeroed); if (!elr) { ret = -ENOMEM; goto out; } if (NULL == ext4_li_info) { ret = ext4_li_info_new(); if (ret) goto out; } mutex_lock(&ext4_li_info->li_list_mtx); list_add(&elr->lr_request, &ext4_li_info->li_request_list); mutex_unlock(&ext4_li_info->li_list_mtx); sbi->s_li_request = elr; /* * set elr to NULL here since it has been inserted to * the request_list and the removal and free of it is * handled by ext4_clear_request_list from now on. */ elr = NULL; if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) { ret = ext4_run_lazyinit_thread(); if (ret) goto out; } out: mutex_unlock(&ext4_li_mtx); if (ret) kfree(elr); return ret; } /* * We do not need to lock anything since this is called on * module unload. */ static void ext4_destroy_lazyinit_thread(void) { /* * If thread exited earlier * there's nothing to be done. */ if (!ext4_li_info || !ext4_lazyinit_task) return; kthread_stop(ext4_lazyinit_task); } static int set_journal_csum_feature_set(struct super_block *sb) { int ret = 1; int compat, incompat; struct ext4_sb_info *sbi = EXT4_SB(sb); if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) { /* journal checksum v2 */ compat = 0; incompat = JBD2_FEATURE_INCOMPAT_CSUM_V2; } else { /* journal checksum v1 */ compat = JBD2_FEATURE_COMPAT_CHECKSUM; incompat = 0; } if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) { ret = jbd2_journal_set_features(sbi->s_journal, compat, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT | incompat); } else if (test_opt(sb, JOURNAL_CHECKSUM)) { ret = jbd2_journal_set_features(sbi->s_journal, compat, 0, incompat); jbd2_journal_clear_features(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else { jbd2_journal_clear_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT | JBD2_FEATURE_INCOMPAT_CSUM_V2); } return ret; } /* * Note: calculating the overhead so we can be compatible with * historical BSD practice is quite difficult in the face of * clusters/bigalloc. This is because multiple metadata blocks from * different block group can end up in the same allocation cluster. * Calculating the exact overhead in the face of clustered allocation * requires either O(all block bitmaps) in memory or O(number of block * groups**2) in time. We will still calculate the superblock for * older file systems --- and if we come across with a bigalloc file * system with zero in s_overhead_clusters the estimate will be close to * correct especially for very large cluster sizes --- but for newer * file systems, it's better to calculate this figure once at mkfs * time, and store it in the superblock. If the superblock value is * present (even for non-bigalloc file systems), we will use it. */ static int count_overhead(struct super_block *sb, ext4_group_t grp, char *buf) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_group_desc *gdp; ext4_fsblk_t first_block, last_block, b; ext4_group_t i, ngroups = ext4_get_groups_count(sb); int s, j, count = 0; if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_BIGALLOC)) return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) + sbi->s_itb_per_group + 2); first_block = le32_to_cpu(sbi->s_es->s_first_data_block) + (grp * EXT4_BLOCKS_PER_GROUP(sb)); last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1; for (i = 0; i < ngroups; i++) { gdp = ext4_get_group_desc(sb, i, NULL); b = ext4_block_bitmap(sb, gdp); if (b >= first_block && b <= last_block) { ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf); count++; } b = ext4_inode_bitmap(sb, gdp); if (b >= first_block && b <= last_block) { ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf); count++; } b = ext4_inode_table(sb, gdp); if (b >= first_block && b + sbi->s_itb_per_group <= last_block) for (j = 0; j < sbi->s_itb_per_group; j++, b++) { int c = EXT4_B2C(sbi, b - first_block); ext4_set_bit(c, buf); count++; } if (i != grp) continue; s = 0; if (ext4_bg_has_super(sb, grp)) { ext4_set_bit(s++, buf); count++; } for (j = ext4_bg_num_gdb(sb, grp); j > 0; j--) { ext4_set_bit(EXT4_B2C(sbi, s++), buf); count++; } } if (!count) return 0; return EXT4_CLUSTERS_PER_GROUP(sb) - ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8); } /* * Compute the overhead and stash it in sbi->s_overhead */ int ext4_calculate_overhead(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; ext4_group_t i, ngroups = ext4_get_groups_count(sb); ext4_fsblk_t overhead = 0; char *buf = (char *) get_zeroed_page(GFP_KERNEL); if (!buf) return -ENOMEM; /* * Compute the overhead (FS structures). This is constant * for a given filesystem unless the number of block groups * changes so we cache the previous value until it does. */ /* * All of the blocks before first_data_block are overhead */ overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block)); /* * Add the overhead found in each block group */ for (i = 0; i < ngroups; i++) { int blks; blks = count_overhead(sb, i, buf); overhead += blks; if (blks) memset(buf, 0, PAGE_SIZE); cond_resched(); } /* Add the journal blocks as well */ if (sbi->s_journal) overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_maxlen); sbi->s_overhead = overhead; smp_wmb(); free_page((unsigned long) buf); return 0; } static ext4_fsblk_t ext4_calculate_resv_clusters(struct ext4_sb_info *sbi) { ext4_fsblk_t resv_clusters; /* * By default we reserve 2% or 4096 clusters, whichever is smaller. * This should cover the situations where we can not afford to run * out of space like for example punch hole, or converting * uninitialized extents in delalloc path. In most cases such * allocation would require 1, or 2 blocks, higher numbers are * very rare. */ resv_clusters = ext4_blocks_count(sbi->s_es) >> sbi->s_cluster_bits; do_div(resv_clusters, 50); resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096); return resv_clusters; } static int ext4_reserve_clusters(struct ext4_sb_info *sbi, ext4_fsblk_t count) { ext4_fsblk_t clusters = ext4_blocks_count(sbi->s_es) >> sbi->s_cluster_bits; if (count >= clusters) return -EINVAL; atomic64_set(&sbi->s_resv_clusters, count); return 0; } static int ext4_fill_super(struct super_block *sb, void *data, int silent) { char *orig_data = kstrdup(data, GFP_KERNEL); struct buffer_head *bh; struct ext4_super_block *es = NULL; struct ext4_sb_info *sbi; ext4_fsblk_t block; ext4_fsblk_t sb_block = get_sb_block(&data); ext4_fsblk_t logical_sb_block; unsigned long offset = 0; unsigned long journal_devnum = 0; unsigned long def_mount_opts; struct inode *root; char *cp; const char *descr; int ret = -ENOMEM; int blocksize, clustersize; unsigned int db_count; unsigned int i; int needs_recovery, has_huge_files, has_bigalloc; __u64 blocks_count; int err = 0; unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO; ext4_group_t first_not_zeroed; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) goto out_free_orig; sbi->s_blockgroup_lock = kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL); if (!sbi->s_blockgroup_lock) { kfree(sbi); goto out_free_orig; } sb->s_fs_info = sbi; sbi->s_sb = sb; sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; sbi->s_sb_block = sb_block; if (sb->s_bdev->bd_part) sbi->s_sectors_written_start = part_stat_read(sb->s_bdev->bd_part, sectors[1]); /* Cleanup superblock name */ for (cp = sb->s_id; (cp = strchr(cp, '/'));) *cp = '!'; /* -EINVAL is default */ ret = -EINVAL; blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE); if (!blocksize) { ext4_msg(sb, KERN_ERR, "unable to set blocksize"); goto out_fail; } /* * The ext4 superblock will not be buffer aligned for other than 1kB * block sizes. We need to calculate the offset from buffer start. */ if (blocksize != EXT4_MIN_BLOCK_SIZE) { logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); } else { logical_sb_block = sb_block; } if (!(bh = sb_bread(sb, logical_sb_block))) { ext4_msg(sb, KERN_ERR, "unable to read superblock"); goto out_fail; } /* * Note: s_es must be initialized as soon as possible because * some ext4 macro-instructions depend on its value */ es = (struct ext4_super_block *) (bh->b_data + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT4_SUPER_MAGIC) goto cantfind_ext4; sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written); /* Warn if metadata_csum and gdt_csum are both set. */ if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) && EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM)) ext4_warning(sb, KERN_INFO "metadata_csum and uninit_bg are " "redundant flags; please run fsck."); /* Check for a known checksum algorithm */ if (!ext4_verify_csum_type(sb, es)) { ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with " "unknown checksum algorithm."); silent = 1; goto cantfind_ext4; } /* Load the checksum driver */ if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) { sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0); if (IS_ERR(sbi->s_chksum_driver)) { ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver."); ret = PTR_ERR(sbi->s_chksum_driver); sbi->s_chksum_driver = NULL; goto failed_mount; } } /* Check superblock checksum */ if (!ext4_superblock_csum_verify(sb, es)) { ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with " "invalid superblock checksum. Run e2fsck?"); silent = 1; goto cantfind_ext4; } /* Precompute checksum seed for all metadata */ if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid, sizeof(es->s_uuid)); /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); set_opt(sb, INIT_INODE_TABLE); if (def_mount_opts & EXT4_DEFM_DEBUG) set_opt(sb, DEBUG); if (def_mount_opts & EXT4_DEFM_BSDGROUPS) set_opt(sb, GRPID); if (def_mount_opts & EXT4_DEFM_UID16) set_opt(sb, NO_UID32); /* xattr user namespace & acls are now defaulted on */ set_opt(sb, XATTR_USER); #ifdef CONFIG_EXT4_FS_POSIX_ACL set_opt(sb, POSIX_ACL); #endif if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA) set_opt(sb, JOURNAL_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED) set_opt(sb, ORDERED_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK) set_opt(sb, WRITEBACK_DATA); if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC) set_opt(sb, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE) set_opt(sb, ERRORS_CONT); else set_opt(sb, ERRORS_RO); if (def_mount_opts & EXT4_DEFM_BLOCK_VALIDITY) set_opt(sb, BLOCK_VALIDITY); if (def_mount_opts & EXT4_DEFM_DISCARD) set_opt(sb, DISCARD); sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid)); sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid)); sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0) set_opt(sb, BARRIER); /* * enable delayed allocation by default * Use -o nodelalloc to turn it off */ if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) && ((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0)) set_opt(sb, DELALLOC); /* * set default s_li_wait_mult for lazyinit, for the case there is * no mount option specified. */ sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT; if (!parse_options((char *) sbi->s_es->s_mount_opts, sb, &journal_devnum, &journal_ioprio, 0)) { ext4_msg(sb, KERN_WARNING, "failed to parse options in superblock: %s", sbi->s_es->s_mount_opts); } sbi->s_def_mount_opt = sbi->s_mount_opt; if (!parse_options((char *) data, sb, &journal_devnum, &journal_ioprio, 0)) goto failed_mount; if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) { printk_once(KERN_WARNING "EXT4-fs: Warning: mounting " "with data=journal disables delayed " "allocation and O_DIRECT support!\n"); if (test_opt2(sb, EXPLICIT_DELALLOC)) { ext4_msg(sb, KERN_ERR, "can't mount with " "both data=journal and delalloc"); goto failed_mount; } if (test_opt(sb, DIOREAD_NOLOCK)) { ext4_msg(sb, KERN_ERR, "can't mount with " "both data=journal and delalloc"); goto failed_mount; } if (test_opt(sb, DELALLOC)) clear_opt(sb, DELALLOC); } sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV && (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U))) ext4_msg(sb, KERN_WARNING, "feature flags set on rev 0 fs, " "running e2fsck is recommended"); if (IS_EXT2_SB(sb)) { if (ext2_feature_set_ok(sb)) ext4_msg(sb, KERN_INFO, "mounting ext2 file system " "using the ext4 subsystem"); else { ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due " "to feature incompatibilities"); goto failed_mount; } } if (IS_EXT3_SB(sb)) { if (ext3_feature_set_ok(sb)) ext4_msg(sb, KERN_INFO, "mounting ext3 file system " "using the ext4 subsystem"); else { ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due " "to feature incompatibilities"); goto failed_mount; } } /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY))) goto failed_mount; blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size); if (blocksize < EXT4_MIN_BLOCK_SIZE || blocksize > EXT4_MAX_BLOCK_SIZE) { ext4_msg(sb, KERN_ERR, "Unsupported filesystem blocksize %d", blocksize); goto failed_mount; } if (sb->s_blocksize != blocksize) { /* Validate the filesystem blocksize */ if (!sb_set_blocksize(sb, blocksize)) { ext4_msg(sb, KERN_ERR, "bad block size %d", blocksize); goto failed_mount; } brelse(bh); logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); bh = sb_bread(sb, logical_sb_block); if (!bh) { ext4_msg(sb, KERN_ERR, "Can't read superblock on 2nd try"); goto failed_mount; } es = (struct ext4_super_block *)(bh->b_data + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) { ext4_msg(sb, KERN_ERR, "Magic mismatch, very weird!"); goto failed_mount; } } has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE); sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits, has_huge_files); sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) { sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) || (!is_power_of_2(sbi->s_inode_size)) || (sbi->s_inode_size > blocksize)) { ext4_msg(sb, KERN_ERR, "unsupported inode size: %d", sbi->s_inode_size); goto failed_mount; } if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2); } sbi->s_desc_size = le16_to_cpu(es->s_desc_size); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) { if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT || sbi->s_desc_size > EXT4_MAX_DESC_SIZE || !is_power_of_2(sbi->s_desc_size)) { ext4_msg(sb, KERN_ERR, "unsupported descriptor size %lu", sbi->s_desc_size); goto failed_mount; } } else sbi->s_desc_size = EXT4_MIN_DESC_SIZE; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0) goto cantfind_ext4; sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0) goto cantfind_ext4; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb)); for (i = 0; i < 4; i++) sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]); sbi->s_def_hash_version = es->s_def_hash_version; i = le32_to_cpu(es->s_flags); if (i & EXT2_FLAGS_UNSIGNED_HASH) sbi->s_hash_unsigned = 3; else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) { #ifdef __CHAR_UNSIGNED__ es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); sbi->s_hash_unsigned = 3; #else es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH); #endif } /* Handle clustersize */ clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size); has_bigalloc = EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_BIGALLOC); if (has_bigalloc) { if (clustersize < blocksize) { ext4_msg(sb, KERN_ERR, "cluster size (%d) smaller than " "block size (%d)", clustersize, blocksize); goto failed_mount; } sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) - le32_to_cpu(es->s_log_block_size); sbi->s_clusters_per_group = le32_to_cpu(es->s_clusters_per_group); if (sbi->s_clusters_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#clusters per group too big: %lu", sbi->s_clusters_per_group); goto failed_mount; } if (sbi->s_blocks_per_group != (sbi->s_clusters_per_group * (clustersize / blocksize))) { ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and " "clusters per group (%lu) inconsistent", sbi->s_blocks_per_group, sbi->s_clusters_per_group); goto failed_mount; } } else { if (clustersize != blocksize) { ext4_warning(sb, "fragment/cluster size (%d) != " "block size (%d)", clustersize, blocksize); clustersize = blocksize; } if (sbi->s_blocks_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#blocks per group too big: %lu", sbi->s_blocks_per_group); goto failed_mount; } sbi->s_clusters_per_group = sbi->s_blocks_per_group; sbi->s_cluster_bits = 0; } sbi->s_cluster_ratio = clustersize / blocksize; if (sbi->s_inodes_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#inodes per group too big: %lu", sbi->s_inodes_per_group); goto failed_mount; } /* Do we have standard group size of clustersize * 8 blocks ? */ if (sbi->s_blocks_per_group == clustersize << 3) set_opt2(sb, STD_GROUP_SIZE); /* * Test whether we have more sectors than will fit in sector_t, * and whether the max offset is addressable by the page cache. */ err = generic_check_addressable(sb->s_blocksize_bits, ext4_blocks_count(es)); if (err) { ext4_msg(sb, KERN_ERR, "filesystem" " too large to mount safely on this system"); if (sizeof(sector_t) < 8) ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled"); goto failed_mount; } if (EXT4_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext4; /* check blocks count against device size */ blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits; if (blocks_count && ext4_blocks_count(es) > blocks_count) { ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu " "exceeds size of device (%llu blocks)", ext4_blocks_count(es), blocks_count); goto failed_mount; } /* * It makes no sense for the first data block to be beyond the end * of the filesystem. */ if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) { ext4_msg(sb, KERN_WARNING, "bad geometry: first data " "block %u is beyond end of filesystem (%llu)", le32_to_cpu(es->s_first_data_block), ext4_blocks_count(es)); goto failed_mount; } blocks_count = (ext4_blocks_count(es) - le32_to_cpu(es->s_first_data_block) + EXT4_BLOCKS_PER_GROUP(sb) - 1); do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb)); if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) { ext4_msg(sb, KERN_WARNING, "groups count too large: %u " "(block count %llu, first data block %u, " "blocks per group %lu)", sbi->s_groups_count, ext4_blocks_count(es), le32_to_cpu(es->s_first_data_block), EXT4_BLOCKS_PER_GROUP(sb)); goto failed_mount; } sbi->s_groups_count = blocks_count; sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count, (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb))); db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb); sbi->s_group_desc = ext4_kvmalloc(db_count * sizeof(struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { ext4_msg(sb, KERN_ERR, "not enough memory"); ret = -ENOMEM; goto failed_mount; } if (ext4_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root); if (sbi->s_proc) proc_create_data("options", S_IRUGO, sbi->s_proc, &ext4_seq_options_fops, sb); bgl_lock_init(sbi->s_blockgroup_lock); for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logical_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { ext4_msg(sb, KERN_ERR, "can't read group descriptor %d", i); db_count = i; goto failed_mount2; } } if (!ext4_check_descriptors(sb, &first_not_zeroed)) { ext4_msg(sb, KERN_ERR, "group descriptors corrupted!"); goto failed_mount2; } if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) if (!ext4_fill_flex_info(sb)) { ext4_msg(sb, KERN_ERR, "unable to initialize " "flex_bg meta info!"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); init_timer(&sbi->s_err_report); sbi->s_err_report.function = print_daily_error_info; sbi->s_err_report.data = (unsigned long) sb; /* Register extent status tree shrinker */ ext4_es_register_shrinker(sbi); err = percpu_counter_init(&sbi->s_freeclusters_counter, ext4_count_free_clusters(sb)); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext4_count_dirs(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0); } if (!err) { err = percpu_counter_init(&sbi->s_extent_cache_cnt, 0); } if (err) { ext4_msg(sb, KERN_ERR, "insufficient memory"); goto failed_mount3; } sbi->s_stripe = ext4_get_stripe_size(sbi); sbi->s_extent_max_zeroout_kb = 32; /* * set up enough so that it can read an inode */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) sb->s_op = &ext4_sops; else sb->s_op = &ext4_nojournal_sops; sb->s_export_op = &ext4_export_ops; sb->s_xattr = ext4_xattr_handlers; #ifdef CONFIG_QUOTA sb->dq_op = &ext4_quota_operations; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA)) sb->s_qcop = &ext4_qctl_sysfile_operations; else sb->s_qcop = &ext4_qctl_operations; #endif memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid)); INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */ mutex_init(&sbi->s_orphan_lock); sb->s_root = NULL; needs_recovery = (es->s_last_orphan != 0 || EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_MMP) && !(sb->s_flags & MS_RDONLY)) if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block))) goto failed_mount3; /* * The first inode we look at is the journal inode. Don't try * root first: it may be modified in the journal! */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) { if (ext4_load_journal(sb, es, journal_devnum)) goto failed_mount3; } else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) && EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { ext4_msg(sb, KERN_ERR, "required journal recovery " "suppressed and not mounted read-only"); goto failed_mount_wq; } else { clear_opt(sb, DATA_FLAGS); sbi->s_journal = NULL; needs_recovery = 0; goto no_journal; } if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT) && !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_64BIT)) { ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature"); goto failed_mount_wq; } if (!set_journal_csum_feature_set(sb)) { ext4_msg(sb, KERN_ERR, "Failed to set journal checksum " "feature set"); goto failed_mount_wq; } /* We have now updated the journal if required, so we can * validate the data journaling mode. */ switch (test_opt(sb, DATA_FLAGS)) { case 0: /* No mode set, assume a default based on the journal * capabilities: ORDERED_DATA if the journal can * cope, else JOURNAL_DATA */ if (jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) set_opt(sb, ORDERED_DATA); else set_opt(sb, JOURNAL_DATA); break; case EXT4_MOUNT_ORDERED_DATA: case EXT4_MOUNT_WRITEBACK_DATA: if (!jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) { ext4_msg(sb, KERN_ERR, "Journal does not support " "requested data journaling mode"); goto failed_mount_wq; } default: break; } set_task_ioprio(sbi->s_journal->j_task, journal_ioprio); sbi->s_journal->j_commit_callback = ext4_journal_commit_callback; /* * The journal may have updated the bg summary counts, so we * need to update the global counters. */ percpu_counter_set(&sbi->s_freeclusters_counter, ext4_count_free_clusters(sb)); percpu_counter_set(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); percpu_counter_set(&sbi->s_dirs_counter, ext4_count_dirs(sb)); percpu_counter_set(&sbi->s_dirtyclusters_counter, 0); no_journal: /* * Get the # of file system overhead blocks from the * superblock if present. */ if (es->s_overhead_clusters) sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters); else { err = ext4_calculate_overhead(sb); if (err) goto failed_mount_wq; } /* * The maximum number of concurrent works can be high and * concurrency isn't really necessary. Limit it to 1. */ EXT4_SB(sb)->rsv_conversion_wq = alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1); if (!EXT4_SB(sb)->rsv_conversion_wq) { printk(KERN_ERR "EXT4-fs: failed to create workqueue\n"); ret = -ENOMEM; goto failed_mount4; } EXT4_SB(sb)->unrsv_conversion_wq = alloc_workqueue("ext4-unrsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1); if (!EXT4_SB(sb)->unrsv_conversion_wq) { printk(KERN_ERR "EXT4-fs: failed to create workqueue\n"); ret = -ENOMEM; goto failed_mount4; } /* * The jbd2_journal_load will have done any necessary log recovery, * so we can safely mount the rest of the filesystem now. */ root = ext4_iget(sb, EXT4_ROOT_INO); if (IS_ERR(root)) { ext4_msg(sb, KERN_ERR, "get root inode failed"); ret = PTR_ERR(root); root = NULL; goto failed_mount4; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck"); iput(root); goto failed_mount4; } sb->s_root = d_make_root(root); if (!sb->s_root) { ext4_msg(sb, KERN_ERR, "get root dentry failed"); ret = -ENOMEM; goto failed_mount4; } if (ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY)) sb->s_flags |= MS_RDONLY; /* determine the minimum size of new large inodes, if present */ if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) { if (sbi->s_want_extra_isize < le16_to_cpu(es->s_want_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_want_extra_isize); if (sbi->s_want_extra_isize < le16_to_cpu(es->s_min_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_min_extra_isize); } } /* Check if enough inode space is available */ if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize > sbi->s_inode_size) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; ext4_msg(sb, KERN_INFO, "required extra inode space not" "available"); } err = ext4_reserve_clusters(sbi, ext4_calculate_resv_clusters(sbi)); if (err) { ext4_msg(sb, KERN_ERR, "failed to reserve %llu clusters for " "reserved pool", ext4_calculate_resv_clusters(sbi)); goto failed_mount4a; } err = ext4_setup_system_zone(sb); if (err) { ext4_msg(sb, KERN_ERR, "failed to initialize system " "zone (%d)", err); goto failed_mount4a; } ext4_ext_init(sb); err = ext4_mb_init(sb); if (err) { ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)", err); goto failed_mount5; } err = ext4_register_li_request(sb, first_not_zeroed); if (err) goto failed_mount6; sbi->s_kobj.kset = ext4_kset; init_completion(&sbi->s_kobj_unregister); err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL, "%s", sb->s_id); if (err) goto failed_mount7; #ifdef CONFIG_QUOTA /* Enable quota usage during mount. */ if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) && !(sb->s_flags & MS_RDONLY)) { err = ext4_enable_quotas(sb); if (err) goto failed_mount8; } #endif /* CONFIG_QUOTA */ EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS; ext4_orphan_cleanup(sb, es); EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS; if (needs_recovery) { ext4_msg(sb, KERN_INFO, "recovery complete"); ext4_mark_recovery_complete(sb, es); } if (EXT4_SB(sb)->s_journal) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) descr = " journalled data mode"; else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) descr = " ordered data mode"; else descr = " writeback data mode"; } else descr = "out journal"; if (test_opt(sb, DISCARD)) { struct request_queue *q = bdev_get_queue(sb->s_bdev); if (!blk_queue_discard(q)) ext4_msg(sb, KERN_WARNING, "mounting with \"discard\" option, but " "the device does not support discard"); } ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. " "Opts: %s%s%s", descr, sbi->s_es->s_mount_opts, *sbi->s_es->s_mount_opts ? "; " : "", orig_data); if (es->s_error_count) mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */ kfree(orig_data); return 0; cantfind_ext4: if (!silent) ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem"); goto failed_mount; #ifdef CONFIG_QUOTA failed_mount8: kobject_del(&sbi->s_kobj); #endif failed_mount7: ext4_unregister_li_request(sb); failed_mount6: ext4_mb_release(sb); failed_mount5: ext4_ext_release(sb); ext4_release_system_zone(sb); failed_mount4a: dput(sb->s_root); sb->s_root = NULL; failed_mount4: ext4_msg(sb, KERN_ERR, "mount failed"); if (EXT4_SB(sb)->rsv_conversion_wq) destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq); if (EXT4_SB(sb)->unrsv_conversion_wq) destroy_workqueue(EXT4_SB(sb)->unrsv_conversion_wq); failed_mount_wq: if (sbi->s_journal) { jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; } failed_mount3: ext4_es_unregister_shrinker(sbi); del_timer(&sbi->s_err_report); if (sbi->s_flex_groups) ext4_kvfree(sbi->s_flex_groups); percpu_counter_destroy(&sbi->s_freeclusters_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyclusters_counter); percpu_counter_destroy(&sbi->s_extent_cache_cnt); if (sbi->s_mmp_tsk) kthread_stop(sbi->s_mmp_tsk); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); ext4_kvfree(sbi->s_group_desc); failed_mount: if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); if (sbi->s_proc) { remove_proc_entry("options", sbi->s_proc); remove_proc_entry(sb->s_id, ext4_proc_root); } #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif ext4_blkdev_remove(sbi); brelse(bh); out_fail: sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); out_free_orig: kfree(orig_data); return err ? err : ret; } /* * Setup any per-fs journal parameters now. We'll do this both on * initial mount, once the journal has been initialised but before we've * done any recovery; and again on any subsequent remount. */ static void ext4_init_journal_params(struct super_block *sb, journal_t *journal) { struct ext4_sb_info *sbi = EXT4_SB(sb); journal->j_commit_interval = sbi->s_commit_interval; journal->j_min_batch_time = sbi->s_min_batch_time; journal->j_max_batch_time = sbi->s_max_batch_time; write_lock(&journal->j_state_lock); if (test_opt(sb, BARRIER)) journal->j_flags |= JBD2_BARRIER; else journal->j_flags &= ~JBD2_BARRIER; if (test_opt(sb, DATA_ERR_ABORT)) journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR; else journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR; write_unlock(&journal->j_state_lock); } static journal_t *ext4_get_journal(struct super_block *sb, unsigned int journal_inum) { struct inode *journal_inode; journal_t *journal; BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)); /* First, test for the existence of a valid inode on disk. Bad * things happen if we iget() an unused inode, as the subsequent * iput() will try to delete it. */ journal_inode = ext4_iget(sb, journal_inum); if (IS_ERR(journal_inode)) { ext4_msg(sb, KERN_ERR, "no journal found"); return NULL; } if (!journal_inode->i_nlink) { make_bad_inode(journal_inode); iput(journal_inode); ext4_msg(sb, KERN_ERR, "journal inode is deleted"); return NULL; } jbd_debug(2, "Journal inode found at %p: %lld bytes\n", journal_inode, journal_inode->i_size); if (!S_ISREG(journal_inode->i_mode)) { ext4_msg(sb, KERN_ERR, "invalid journal inode"); iput(journal_inode); return NULL; } journal = jbd2_journal_init_inode(journal_inode); if (!journal) { ext4_msg(sb, KERN_ERR, "Could not load journal inode"); iput(journal_inode); return NULL; } journal->j_private = sb; ext4_init_journal_params(sb, journal); return journal; } static journal_t *ext4_get_dev_journal(struct super_block *sb, dev_t j_dev) { struct buffer_head *bh; journal_t *journal; ext4_fsblk_t start; ext4_fsblk_t len; int hblock, blocksize; ext4_fsblk_t sb_block; unsigned long offset; struct ext4_super_block *es; struct block_device *bdev; BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)); bdev = ext4_blkdev_get(j_dev, sb); if (bdev == NULL) return NULL; blocksize = sb->s_blocksize; hblock = bdev_logical_block_size(bdev); if (blocksize < hblock) { ext4_msg(sb, KERN_ERR, "blocksize too small for journal device"); goto out_bdev; } sb_block = EXT4_MIN_BLOCK_SIZE / blocksize; offset = EXT4_MIN_BLOCK_SIZE % blocksize; set_blocksize(bdev, blocksize); if (!(bh = __bread(bdev, sb_block, blocksize))) { ext4_msg(sb, KERN_ERR, "couldn't read superblock of " "external journal"); goto out_bdev; } es = (struct ext4_super_block *) (bh->b_data + offset); if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) || !(le32_to_cpu(es->s_feature_incompat) & EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) { ext4_msg(sb, KERN_ERR, "external journal has " "bad superblock"); brelse(bh); goto out_bdev; } if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) { ext4_msg(sb, KERN_ERR, "journal UUID does not match"); brelse(bh); goto out_bdev; } len = ext4_blocks_count(es); start = sb_block + 1; brelse(bh); /* we're done with the superblock */ journal = jbd2_journal_init_dev(bdev, sb->s_bdev, start, len, blocksize); if (!journal) { ext4_msg(sb, KERN_ERR, "failed to create device journal"); goto out_bdev; } journal->j_private = sb; ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &journal->j_sb_buffer); wait_on_buffer(journal->j_sb_buffer); if (!buffer_uptodate(journal->j_sb_buffer)) { ext4_msg(sb, KERN_ERR, "I/O error on journal device"); goto out_journal; } if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) { ext4_msg(sb, KERN_ERR, "External journal has more than one " "user (unsupported) - %d", be32_to_cpu(journal->j_superblock->s_nr_users)); goto out_journal; } EXT4_SB(sb)->journal_bdev = bdev; ext4_init_journal_params(sb, journal); return journal; out_journal: jbd2_journal_destroy(journal); out_bdev: ext4_blkdev_put(bdev); return NULL; } static int ext4_load_journal(struct super_block *sb, struct ext4_super_block *es, unsigned long journal_devnum) { journal_t *journal; unsigned int journal_inum = le32_to_cpu(es->s_journal_inum); dev_t journal_dev; int err = 0; int really_read_only; BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)); if (journal_devnum && journal_devnum != le32_to_cpu(es->s_journal_dev)) { ext4_msg(sb, KERN_INFO, "external journal device major/minor " "numbers have changed"); journal_dev = new_decode_dev(journal_devnum); } else journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev)); really_read_only = bdev_read_only(sb->s_bdev); /* * Are we loading a blank journal or performing recovery after a * crash? For recovery, we need to check in advance whether we * can get read-write access to the device. */ if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { if (sb->s_flags & MS_RDONLY) { ext4_msg(sb, KERN_INFO, "INFO: recovery " "required on readonly filesystem"); if (really_read_only) { ext4_msg(sb, KERN_ERR, "write access " "unavailable, cannot proceed"); return -EROFS; } ext4_msg(sb, KERN_INFO, "write access will " "be enabled during recovery"); } } if (journal_inum && journal_dev) { ext4_msg(sb, KERN_ERR, "filesystem has both journal " "and inode journals!"); return -EINVAL; } if (journal_inum) { if (!(journal = ext4_get_journal(sb, journal_inum))) return -EINVAL; } else { if (!(journal = ext4_get_dev_journal(sb, journal_dev))) return -EINVAL; } if (!(journal->j_flags & JBD2_BARRIER)) ext4_msg(sb, KERN_INFO, "barriers disabled"); if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) err = jbd2_journal_wipe(journal, !really_read_only); if (!err) { char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL); if (save) memcpy(save, ((char *) es) + EXT4_S_ERR_START, EXT4_S_ERR_LEN); err = jbd2_journal_load(journal); if (save) memcpy(((char *) es) + EXT4_S_ERR_START, save, EXT4_S_ERR_LEN); kfree(save); } if (err) { ext4_msg(sb, KERN_ERR, "error loading journal"); jbd2_journal_destroy(journal); return err; } EXT4_SB(sb)->s_journal = journal; ext4_clear_journal_err(sb, es); if (!really_read_only && journal_devnum && journal_devnum != le32_to_cpu(es->s_journal_dev)) { es->s_journal_dev = cpu_to_le32(journal_devnum); /* Make sure we flush the recovery flag to disk. */ ext4_commit_super(sb, 1); } return 0; } static int ext4_commit_super(struct super_block *sb, int sync) { struct ext4_super_block *es = EXT4_SB(sb)->s_es; struct buffer_head *sbh = EXT4_SB(sb)->s_sbh; int error = 0; if (!sbh || block_device_ejected(sb)) return error; if (buffer_write_io_error(sbh)) { /* * Oh, dear. A previous attempt to write the * superblock failed. This could happen because the * USB device was yanked out. Or it could happen to * be a transient write error and maybe the block will * be remapped. Nothing we can do but to retry the * write and hope for the best. */ ext4_msg(sb, KERN_ERR, "previous I/O error to " "superblock detected"); clear_buffer_write_io_error(sbh); set_buffer_uptodate(sbh); } /* * If the file system is mounted read-only, don't update the * superblock write time. This avoids updating the superblock * write time when we are mounting the root file system * read/only but we need to replay the journal; at that point, * for people who are east of GMT and who make their clock * tick in localtime for Windows bug-for-bug compatibility, * the clock is set in the future, and this will cause e2fsck * to complain and force a full file system check. */ if (!(sb->s_flags & MS_RDONLY)) es->s_wtime = cpu_to_le32(get_seconds()); if (sb->s_bdev->bd_part) es->s_kbytes_written = cpu_to_le64(EXT4_SB(sb)->s_kbytes_written + ((part_stat_read(sb->s_bdev->bd_part, sectors[1]) - EXT4_SB(sb)->s_sectors_written_start) >> 1)); else es->s_kbytes_written = cpu_to_le64(EXT4_SB(sb)->s_kbytes_written); ext4_free_blocks_count_set(es, EXT4_C2B(EXT4_SB(sb), percpu_counter_sum_positive( &EXT4_SB(sb)->s_freeclusters_counter))); es->s_free_inodes_count = cpu_to_le32(percpu_counter_sum_positive( &EXT4_SB(sb)->s_freeinodes_counter)); BUFFER_TRACE(sbh, "marking dirty"); ext4_superblock_csum_set(sb); mark_buffer_dirty(sbh); if (sync) { error = sync_dirty_buffer(sbh); if (error) return error; error = buffer_write_io_error(sbh); if (error) { ext4_msg(sb, KERN_ERR, "I/O error while writing " "superblock"); clear_buffer_write_io_error(sbh); set_buffer_uptodate(sbh); } } return error; } /* * Have we just finished recovery? If so, and if we are mounting (or * remounting) the filesystem readonly, then we will end up with a * consistent fs on disk. Record that fact. */ static void ext4_mark_recovery_complete(struct super_block *sb, struct ext4_super_block *es) { journal_t *journal = EXT4_SB(sb)->s_journal; if (!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) { BUG_ON(journal != NULL); return; } jbd2_journal_lock_updates(journal); if (jbd2_journal_flush(journal) < 0) goto out; if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER) && sb->s_flags & MS_RDONLY) { EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER); ext4_commit_super(sb, 1); } out: jbd2_journal_unlock_updates(journal); } /* * If we are mounting (or read-write remounting) a filesystem whose journal * has recorded an error from a previous lifetime, move that error to the * main filesystem now. */ static void ext4_clear_journal_err(struct super_block *sb, struct ext4_super_block *es) { journal_t *journal; int j_errno; const char *errstr; BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)); journal = EXT4_SB(sb)->s_journal; /* * Now check for any error status which may have been recorded in the * journal by a prior ext4_error() or ext4_abort() */ j_errno = jbd2_journal_errno(journal); if (j_errno) { char nbuf[16]; errstr = ext4_decode_error(sb, j_errno, nbuf); ext4_warning(sb, "Filesystem error recorded " "from previous mount: %s", errstr); ext4_warning(sb, "Marking fs in need of filesystem check."); EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS; es->s_state |= cpu_to_le16(EXT4_ERROR_FS); ext4_commit_super(sb, 1); jbd2_journal_clear_err(journal); jbd2_journal_update_sb_errno(journal); } } /* * Force the running and committing transactions to commit, * and wait on the commit. */ int ext4_force_commit(struct super_block *sb) { journal_t *journal; if (sb->s_flags & MS_RDONLY) return 0; journal = EXT4_SB(sb)->s_journal; return ext4_journal_force_commit(journal); } static int ext4_sync_fs(struct super_block *sb, int wait) { int ret = 0; tid_t target; bool needs_barrier = false; struct ext4_sb_info *sbi = EXT4_SB(sb); trace_ext4_sync_fs(sb, wait); flush_workqueue(sbi->rsv_conversion_wq); flush_workqueue(sbi->unrsv_conversion_wq); /* * Writeback quota in non-journalled quota case - journalled quota has * no dirty dquots */ dquot_writeback_dquots(sb, -1); /* * Data writeback is possible w/o journal transaction, so barrier must * being sent at the end of the function. But we can skip it if * transaction_commit will do it for us. */ target = jbd2_get_latest_transaction(sbi->s_journal); if (wait && sbi->s_journal->j_flags & JBD2_BARRIER && !jbd2_trans_will_send_data_barrier(sbi->s_journal, target)) needs_barrier = true; if (jbd2_journal_start_commit(sbi->s_journal, &target)) { if (wait) ret = jbd2_log_wait_commit(sbi->s_journal, target); } if (needs_barrier) { int err; err = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL, NULL); if (!ret) ret = err; } return ret; } static int ext4_sync_fs_nojournal(struct super_block *sb, int wait) { int ret = 0; trace_ext4_sync_fs(sb, wait); flush_workqueue(EXT4_SB(sb)->rsv_conversion_wq); flush_workqueue(EXT4_SB(sb)->unrsv_conversion_wq); dquot_writeback_dquots(sb, -1); if (wait && test_opt(sb, BARRIER)) ret = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL, NULL); return ret; } /* * LVM calls this function before a (read-only) snapshot is created. This * gives us a chance to flush the journal completely and mark the fs clean. * * Note that only this function cannot bring a filesystem to be in a clean * state independently. It relies on upper layer to stop all data & metadata * modifications. */ static int ext4_freeze(struct super_block *sb) { int error = 0; journal_t *journal; if (sb->s_flags & MS_RDONLY) return 0; journal = EXT4_SB(sb)->s_journal; /* Now we set up the journal barrier. */ jbd2_journal_lock_updates(journal); /* * Don't clear the needs_recovery flag if we failed to flush * the journal. */ error = jbd2_journal_flush(journal); if (error < 0) goto out; /* Journal blocked and flushed, clear needs_recovery flag. */ EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER); error = ext4_commit_super(sb, 1); out: /* we rely on upper layer to stop further updates */ jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal); return error; } /* * Called by LVM after the snapshot is done. We need to reset the RECOVER * flag here, even though the filesystem is not technically dirty yet. */ static int ext4_unfreeze(struct super_block *sb) { if (sb->s_flags & MS_RDONLY) return 0; /* Reset the needs_recovery flag before the fs is unlocked. */ EXT4_SET_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER); ext4_commit_super(sb, 1); return 0; } /* * Structure to save mount options for ext4_remount's benefit */ struct ext4_mount_options { unsigned long s_mount_opt; unsigned long s_mount_opt2; kuid_t s_resuid; kgid_t s_resgid; unsigned long s_commit_interval; u32 s_min_batch_time, s_max_batch_time; #ifdef CONFIG_QUOTA int s_jquota_fmt; char *s_qf_names[MAXQUOTAS]; #endif }; static int ext4_remount(struct super_block *sb, int *flags, char *data) { struct ext4_super_block *es; struct ext4_sb_info *sbi = EXT4_SB(sb); unsigned long old_sb_flags; struct ext4_mount_options old_opts; int enable_quota = 0; ext4_group_t g; unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO; int err = 0; #ifdef CONFIG_QUOTA int i, j; #endif char *orig_data = kstrdup(data, GFP_KERNEL); /* Store the original options */ old_sb_flags = sb->s_flags; old_opts.s_mount_opt = sbi->s_mount_opt; old_opts.s_mount_opt2 = sbi->s_mount_opt2; old_opts.s_resuid = sbi->s_resuid; old_opts.s_resgid = sbi->s_resgid; old_opts.s_commit_interval = sbi->s_commit_interval; old_opts.s_min_batch_time = sbi->s_min_batch_time; old_opts.s_max_batch_time = sbi->s_max_batch_time; #ifdef CONFIG_QUOTA old_opts.s_jquota_fmt = sbi->s_jquota_fmt; for (i = 0; i < MAXQUOTAS; i++) if (sbi->s_qf_names[i]) { old_opts.s_qf_names[i] = kstrdup(sbi->s_qf_names[i], GFP_KERNEL); if (!old_opts.s_qf_names[i]) { for (j = 0; j < i; j++) kfree(old_opts.s_qf_names[j]); kfree(orig_data); return -ENOMEM; } } else old_opts.s_qf_names[i] = NULL; #endif if (sbi->s_journal && sbi->s_journal->j_task->io_context) journal_ioprio = sbi->s_journal->j_task->io_context->ioprio; /* * Allow the "check" option to be passed as a remount option. */ if (!parse_options(data, sb, NULL, &journal_ioprio, 1)) { err = -EINVAL; goto restore_opts; } if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) ext4_abort(sb, "Abort forced by user"); sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); es = sbi->s_es; if (sbi->s_journal) { ext4_init_journal_params(sb, sbi->s_journal); set_task_ioprio(sbi->s_journal->j_task, journal_ioprio); } if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY)) { if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) { err = -EROFS; goto restore_opts; } if (*flags & MS_RDONLY) { err = dquot_suspend(sb, -1); if (err < 0) goto restore_opts; /* * First of all, the unconditional stuff we have to do * to disable replay of the journal when we next remount */ sb->s_flags |= MS_RDONLY; /* * OK, test if we are remounting a valid rw partition * readonly, and if so set the rdonly flag and then * mark the partition as valid again. */ if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) && (sbi->s_mount_state & EXT4_VALID_FS)) es->s_state = cpu_to_le16(sbi->s_mount_state); if (sbi->s_journal) ext4_mark_recovery_complete(sb, es); } else { /* Make sure we can mount this feature set readwrite */ if (!ext4_feature_set_ok(sb, 0)) { err = -EROFS; goto restore_opts; } /* * Make sure the group descriptor checksums * are sane. If they aren't, refuse to remount r/w. */ for (g = 0; g < sbi->s_groups_count; g++) { struct ext4_group_desc *gdp = ext4_get_group_desc(sb, g, NULL); if (!ext4_group_desc_csum_verify(sb, g, gdp)) { ext4_msg(sb, KERN_ERR, "ext4_remount: Checksum for group %u failed (%u!=%u)", g, le16_to_cpu(ext4_group_desc_csum(sbi, g, gdp)), le16_to_cpu(gdp->bg_checksum)); err = -EINVAL; goto restore_opts; } } /* * If we have an unprocessed orphan list hanging * around from a previously readonly bdev mount, * require a full umount/remount for now. */ if (es->s_last_orphan) { ext4_msg(sb, KERN_WARNING, "Couldn't " "remount RDWR because of unprocessed " "orphan inode list. Please " "umount/remount instead"); err = -EINVAL; goto restore_opts; } /* * Mounting a RDONLY partition read-write, so reread * and store the current valid flag. (It may have * been changed by e2fsck since we originally mounted * the partition.) */ if (sbi->s_journal) ext4_clear_journal_err(sb, es); sbi->s_mount_state = le16_to_cpu(es->s_state); if (!ext4_setup_super(sb, es, 0)) sb->s_flags &= ~MS_RDONLY; if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_MMP)) if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block))) { err = -EROFS; goto restore_opts; } enable_quota = 1; } } /* * Reinitialize lazy itable initialization thread based on * current settings */ if ((sb->s_flags & MS_RDONLY) || !test_opt(sb, INIT_INODE_TABLE)) ext4_unregister_li_request(sb); else { ext4_group_t first_not_zeroed; first_not_zeroed = ext4_has_uninit_itable(sb); ext4_register_li_request(sb, first_not_zeroed); } ext4_setup_system_zone(sb); if (sbi->s_journal == NULL && !(old_sb_flags & MS_RDONLY)) ext4_commit_super(sb, 1); #ifdef CONFIG_QUOTA /* Release old quota file names */ for (i = 0; i < MAXQUOTAS; i++) kfree(old_opts.s_qf_names[i]); if (enable_quota) { if (sb_any_quota_suspended(sb)) dquot_resume(sb, -1); else if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA)) { err = ext4_enable_quotas(sb); if (err) goto restore_opts; } } #endif ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data); kfree(orig_data); return 0; restore_opts: sb->s_flags = old_sb_flags; sbi->s_mount_opt = old_opts.s_mount_opt; sbi->s_mount_opt2 = old_opts.s_mount_opt2; sbi->s_resuid = old_opts.s_resuid; sbi->s_resgid = old_opts.s_resgid; sbi->s_commit_interval = old_opts.s_commit_interval; sbi->s_min_batch_time = old_opts.s_min_batch_time; sbi->s_max_batch_time = old_opts.s_max_batch_time; #ifdef CONFIG_QUOTA sbi->s_jquota_fmt = old_opts.s_jquota_fmt; for (i = 0; i < MAXQUOTAS; i++) { kfree(sbi->s_qf_names[i]); sbi->s_qf_names[i] = old_opts.s_qf_names[i]; } #endif kfree(orig_data); return err; } static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf) { struct super_block *sb = dentry->d_sb; struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; ext4_fsblk_t overhead = 0, resv_blocks; u64 fsid; s64 bfree; resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters)); if (!test_opt(sb, MINIX_DF)) overhead = sbi->s_overhead; buf->f_type = EXT4_SUPER_MAGIC; buf->f_bsize = sb->s_blocksize; buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead); bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) - percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter); /* prevent underflow in case that few free space is available */ buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0)); buf->f_bavail = buf->f_bfree - (ext4_r_blocks_count(es) + resv_blocks); if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks)) buf->f_bavail = 0; buf->f_files = le32_to_cpu(es->s_inodes_count); buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter); buf->f_namelen = EXT4_NAME_LEN; fsid = le64_to_cpup((void *)es->s_uuid) ^ le64_to_cpup((void *)es->s_uuid + sizeof(u64)); buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL; buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL; return 0; } /* Helper function for writing quotas on sync - we need to start transaction * before quota file is locked for write. Otherwise the are possible deadlocks: * Process 1 Process 2 * ext4_create() quota_sync() * jbd2_journal_start() write_dquot() * dquot_initialize() down(dqio_mutex) * down(dqio_mutex) jbd2_journal_start() * */ #ifdef CONFIG_QUOTA static inline struct inode *dquot_to_inode(struct dquot *dquot) { return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type]; } static int ext4_write_dquot(struct dquot *dquot) { int ret, err; handle_t *handle; struct inode *inode; inode = dquot_to_inode(dquot); handle = ext4_journal_start(inode, EXT4_HT_QUOTA, EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb)); if (IS_ERR(handle)) return PTR_ERR(handle); ret = dquot_commit(dquot); err = ext4_journal_stop(handle); if (!ret) ret = err; return ret; } static int ext4_acquire_dquot(struct dquot *dquot) { int ret, err; handle_t *handle; handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA, EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb)); if (IS_ERR(handle)) return PTR_ERR(handle); ret = dquot_acquire(dquot); err = ext4_journal_stop(handle); if (!ret) ret = err; return ret; } static int ext4_release_dquot(struct dquot *dquot) { int ret, err; handle_t *handle; handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA, EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb)); if (IS_ERR(handle)) { /* Release dquot anyway to avoid endless cycle in dqput() */ dquot_release(dquot); return PTR_ERR(handle); } ret = dquot_release(dquot); err = ext4_journal_stop(handle); if (!ret) ret = err; return ret; } static int ext4_mark_dquot_dirty(struct dquot *dquot) { struct super_block *sb = dquot->dq_sb; struct ext4_sb_info *sbi = EXT4_SB(sb); /* Are we journaling quotas? */ if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) || sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) { dquot_mark_dquot_dirty(dquot); return ext4_write_dquot(dquot); } else { return dquot_mark_dquot_dirty(dquot); } } static int ext4_write_info(struct super_block *sb, int type) { int ret, err; handle_t *handle; /* Data block + inode block */ handle = ext4_journal_start(sb->s_root->d_inode, EXT4_HT_QUOTA, 2); if (IS_ERR(handle)) return PTR_ERR(handle); ret = dquot_commit_info(sb, type); err = ext4_journal_stop(handle); if (!ret) ret = err; return ret; } /* * Turn on quotas during mount time - we need to find * the quota file and such... */ static int ext4_quota_on_mount(struct super_block *sb, int type) { return dquot_quota_on_mount(sb, EXT4_SB(sb)->s_qf_names[type], EXT4_SB(sb)->s_jquota_fmt, type); } /* * Standard function to be called on quota_on */ static int ext4_quota_on(struct super_block *sb, int type, int format_id, struct path *path) { int err; if (!test_opt(sb, QUOTA)) return -EINVAL; /* Quotafile not on the same filesystem? */ if (path->dentry->d_sb != sb) return -EXDEV; /* Journaling quota? */ if (EXT4_SB(sb)->s_qf_names[type]) { /* Quotafile not in fs root? */ if (path->dentry->d_parent != sb->s_root) ext4_msg(sb, KERN_WARNING, "Quota file not on filesystem root. " "Journaled quota will not work"); } /* * When we journal data on quota file, we have to flush journal to see * all updates to the file when we bypass pagecache... */ if (EXT4_SB(sb)->s_journal && ext4_should_journal_data(path->dentry->d_inode)) { /* * We don't need to lock updates but journal_flush() could * otherwise be livelocked... */ jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal); err = jbd2_journal_flush(EXT4_SB(sb)->s_journal); jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal); if (err) return err; } return dquot_quota_on(sb, type, format_id, path); } static int ext4_quota_enable(struct super_block *sb, int type, int format_id, unsigned int flags) { int err; struct inode *qf_inode; unsigned long qf_inums[MAXQUOTAS] = { le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum), le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum) }; BUG_ON(!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA)); if (!qf_inums[type]) return -EPERM; qf_inode = ext4_iget(sb, qf_inums[type]); if (IS_ERR(qf_inode)) { ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]); return PTR_ERR(qf_inode); } /* Don't account quota for quota files to avoid recursion */ qf_inode->i_flags |= S_NOQUOTA; err = dquot_enable(qf_inode, type, format_id, flags); iput(qf_inode); return err; } /* Enable usage tracking for all quota types. */ static int ext4_enable_quotas(struct super_block *sb) { int type, err = 0; unsigned long qf_inums[MAXQUOTAS] = { le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum), le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum) }; sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE; for (type = 0; type < MAXQUOTAS; type++) { if (qf_inums[type]) { err = ext4_quota_enable(sb, type, QFMT_VFS_V1, DQUOT_USAGE_ENABLED); if (err) { ext4_warning(sb, "Failed to enable quota tracking " "(type=%d, err=%d). Please run " "e2fsck to fix.", type, err); return err; } } } return 0; } /* * quota_on function that is used when QUOTA feature is set. */ static int ext4_quota_on_sysfile(struct super_block *sb, int type, int format_id) { if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA)) return -EINVAL; /* * USAGE was enabled at mount time. Only need to enable LIMITS now. */ return ext4_quota_enable(sb, type, format_id, DQUOT_LIMITS_ENABLED); } static int ext4_quota_off(struct super_block *sb, int type) { struct inode *inode = sb_dqopt(sb)->files[type]; handle_t *handle; /* Force all delayed allocation blocks to be allocated. * Caller already holds s_umount sem */ if (test_opt(sb, DELALLOC)) sync_filesystem(sb); if (!inode) goto out; /* Update modification times of quota files when userspace can * start looking at them */ handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1); if (IS_ERR(handle)) goto out; inode->i_mtime = inode->i_ctime = CURRENT_TIME; ext4_mark_inode_dirty(handle, inode); ext4_journal_stop(handle); out: return dquot_quota_off(sb, type); } /* * quota_off function that is used when QUOTA feature is set. */ static int ext4_quota_off_sysfile(struct super_block *sb, int type) { if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA)) return -EINVAL; /* Disable only the limits. */ return dquot_disable(sb, type, DQUOT_LIMITS_ENABLED); } /* Read data from quotafile - avoid pagecache and such because we cannot afford * acquiring the locks... As quota files are never truncated and quota code * itself serializes the operations (and no one else should touch the files) * we don't have to be afraid of races */ static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data, size_t len, loff_t off) { struct inode *inode = sb_dqopt(sb)->files[type]; ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb); int err = 0; int offset = off & (sb->s_blocksize - 1); int tocopy; size_t toread; struct buffer_head *bh; loff_t i_size = i_size_read(inode); if (off > i_size) return 0; if (off+len > i_size) len = i_size-off; toread = len; while (toread > 0) { tocopy = sb->s_blocksize - offset < toread ? sb->s_blocksize - offset : toread; bh = ext4_bread(NULL, inode, blk, 0, &err); if (err) return err; if (!bh) /* A hole? */ memset(data, 0, tocopy); else memcpy(data, bh->b_data+offset, tocopy); brelse(bh); offset = 0; toread -= tocopy; data += tocopy; blk++; } return len; } /* Write to quotafile (we know the transaction is already started and has * enough credits) */ static ssize_t ext4_quota_write(struct super_block *sb, int type, const char *data, size_t len, loff_t off) { struct inode *inode = sb_dqopt(sb)->files[type]; ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb); int err = 0; int offset = off & (sb->s_blocksize - 1); struct buffer_head *bh; handle_t *handle = journal_current_handle(); if (EXT4_SB(sb)->s_journal && !handle) { ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)" " cancelled because transaction is not started", (unsigned long long)off, (unsigned long long)len); return -EIO; } /* * Since we account only one data block in transaction credits, * then it is impossible to cross a block boundary. */ if (sb->s_blocksize - offset < len) { ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)" " cancelled because not block aligned", (unsigned long long)off, (unsigned long long)len); return -EIO; } bh = ext4_bread(handle, inode, blk, 1, &err); if (!bh) goto out; err = ext4_journal_get_write_access(handle, bh); if (err) { brelse(bh); goto out; } lock_buffer(bh); memcpy(bh->b_data+offset, data, len); flush_dcache_page(bh->b_page); unlock_buffer(bh); err = ext4_handle_dirty_metadata(handle, NULL, bh); brelse(bh); out: if (err) return err; if (inode->i_size < off + len) { i_size_write(inode, off + len); EXT4_I(inode)->i_disksize = inode->i_size; ext4_mark_inode_dirty(handle, inode); } return len; } #endif static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_bdev(fs_type, flags, dev_name, data, ext4_fill_super); } #if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23) static inline void register_as_ext2(void) { int err = register_filesystem(&ext2_fs_type); if (err) printk(KERN_WARNING "EXT4-fs: Unable to register as ext2 (%d)\n", err); } static inline void unregister_as_ext2(void) { unregister_filesystem(&ext2_fs_type); } static inline int ext2_feature_set_ok(struct super_block *sb) { if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT2_FEATURE_INCOMPAT_SUPP)) return 0; if (sb->s_flags & MS_RDONLY) return 1; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT2_FEATURE_RO_COMPAT_SUPP)) return 0; return 1; } #else static inline void register_as_ext2(void) { } static inline void unregister_as_ext2(void) { } static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; } #endif #if !defined(CONFIG_EXT3_FS) && !defined(CONFIG_EXT3_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23) static inline void register_as_ext3(void) { int err = register_filesystem(&ext3_fs_type); if (err) printk(KERN_WARNING "EXT4-fs: Unable to register as ext3 (%d)\n", err); } static inline void unregister_as_ext3(void) { unregister_filesystem(&ext3_fs_type); } static inline int ext3_feature_set_ok(struct super_block *sb) { if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT3_FEATURE_INCOMPAT_SUPP)) return 0; if (!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) return 0; if (sb->s_flags & MS_RDONLY) return 1; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT3_FEATURE_RO_COMPAT_SUPP)) return 0; return 1; } #else static inline void register_as_ext3(void) { } static inline void unregister_as_ext3(void) { } static inline int ext3_feature_set_ok(struct super_block *sb) { return 0; } #endif static struct file_system_type ext4_fs_type = { .owner = THIS_MODULE, .name = "ext4", .mount = ext4_mount, .kill_sb = kill_block_super, .fs_flags = FS_REQUIRES_DEV, }; MODULE_ALIAS_FS("ext4"); static int __init ext4_init_feat_adverts(void) { struct ext4_features *ef; int ret = -ENOMEM; ef = kzalloc(sizeof(struct ext4_features), GFP_KERNEL); if (!ef) goto out; ef->f_kobj.kset = ext4_kset; init_completion(&ef->f_kobj_unregister); ret = kobject_init_and_add(&ef->f_kobj, &ext4_feat_ktype, NULL, "features"); if (ret) { kfree(ef); goto out; } ext4_feat = ef; ret = 0; out: return ret; } static void ext4_exit_feat_adverts(void) { kobject_put(&ext4_feat->f_kobj); wait_for_completion(&ext4_feat->f_kobj_unregister); kfree(ext4_feat); } /* Shared across all ext4 file systems */ wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ]; struct mutex ext4__aio_mutex[EXT4_WQ_HASH_SZ]; static int __init ext4_init_fs(void) { int i, err; ext4_li_info = NULL; mutex_init(&ext4_li_mtx); /* Build-time check for flags consistency */ ext4_check_flag_values(); for (i = 0; i < EXT4_WQ_HASH_SZ; i++) { mutex_init(&ext4__aio_mutex[i]); init_waitqueue_head(&ext4__ioend_wq[i]); } err = ext4_init_es(); if (err) return err; err = ext4_init_pageio(); if (err) goto out7; err = ext4_init_system_zone(); if (err) goto out6; ext4_kset = kset_create_and_add("ext4", NULL, fs_kobj); if (!ext4_kset) { err = -ENOMEM; goto out5; } ext4_proc_root = proc_mkdir("fs/ext4", NULL); err = ext4_init_feat_adverts(); if (err) goto out4; err = ext4_init_mballoc(); if (err) goto out3; err = ext4_init_xattr(); if (err) goto out2; err = init_inodecache(); if (err) goto out1; register_as_ext3(); register_as_ext2(); err = register_filesystem(&ext4_fs_type); if (err) goto out; return 0; out: unregister_as_ext2(); unregister_as_ext3(); destroy_inodecache(); out1: ext4_exit_xattr(); out2: ext4_exit_mballoc(); out3: ext4_exit_feat_adverts(); out4: if (ext4_proc_root) remove_proc_entry("fs/ext4", NULL); kset_unregister(ext4_kset); out5: ext4_exit_system_zone(); out6: ext4_exit_pageio(); out7: ext4_exit_es(); return err; } static void __exit ext4_exit_fs(void) { ext4_destroy_lazyinit_thread(); unregister_as_ext2(); unregister_as_ext3(); unregister_filesystem(&ext4_fs_type); destroy_inodecache(); ext4_exit_xattr(); ext4_exit_mballoc(); ext4_exit_feat_adverts(); remove_proc_entry("fs/ext4", NULL); kset_unregister(ext4_kset); ext4_exit_system_zone(); ext4_exit_pageio(); ext4_exit_es(); } MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others"); MODULE_DESCRIPTION("Fourth Extended Filesystem"); MODULE_LICENSE("GPL"); module_init(ext4_init_fs) module_exit(ext4_exit_fs)
rkharwar/ubuntu-saucy-powerpc
fs/ext4/super.c
C
gpl-2.0
158,220
/* 32-bit ELF support for S+core. Copyright (C) 2006-2017 Free Software Foundation, Inc. Contributed by Brain.lin (brain.lin@sunplusct.com) Mei Ligang (ligang@sunnorth.com.cn) Pei-Lin Tsai (pltsai@sunplus.com) This file is part of BFD, the Binary File Descriptor library. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #include "sysdep.h" #include "bfd.h" #include "libbfd.h" #include "libiberty.h" #include "elf-bfd.h" #include "elf/score.h" #include "elf/common.h" #include "elf/internal.h" #include "hashtab.h" #include "elf32-score.h" int score3 = 0; int score7 = 1; /* The SCORE ELF linker needs additional information for each symbol in the global hash table. */ struct score_elf_link_hash_entry { struct elf_link_hash_entry root; /* Number of R_SCORE_ABS32, R_SCORE_REL32 relocs against this symbol. */ unsigned int possibly_dynamic_relocs; /* If the R_SCORE_ABS32, R_SCORE_REL32 reloc is against a readonly section. */ bfd_boolean readonly_reloc; /* We must not create a stub for a symbol that has relocations related to taking the function's address, i.e. any but R_SCORE_CALL15 ones. */ bfd_boolean no_fn_stub; /* Are we forced local? This will only be set if we have converted the initial global GOT entry to a local GOT entry. */ bfd_boolean forced_local; }; /* Traverse a score ELF linker hash table. */ #define score_elf_link_hash_traverse(table, func, info) \ (elf_link_hash_traverse \ ((table), \ (bfd_boolean (*) (struct elf_link_hash_entry *, void *)) (func), \ (info))) /* This structure is used to hold .got entries while estimating got sizes. */ struct score_got_entry { /* The input bfd in which the symbol is defined. */ bfd *abfd; /* The index of the symbol, as stored in the relocation r_info, if we have a local symbol; -1 otherwise. */ long symndx; union { /* If abfd == NULL, an address that must be stored in the got. */ bfd_vma address; /* If abfd != NULL && symndx != -1, the addend of the relocation that should be added to the symbol value. */ bfd_vma addend; /* If abfd != NULL && symndx == -1, the hash table entry corresponding to a global symbol in the got (or, local, if h->forced_local). */ struct score_elf_link_hash_entry *h; } d; /* The offset from the beginning of the .got section to the entry corresponding to this symbol+addend. If it's a global symbol whose offset is yet to be decided, it's going to be -1. */ long gotidx; }; /* This structure is passed to score_elf_sort_hash_table_f when sorting the dynamic symbols. */ struct score_elf_hash_sort_data { /* The symbol in the global GOT with the lowest dynamic symbol table index. */ struct elf_link_hash_entry *low; /* The least dynamic symbol table index corresponding to a symbol with a GOT entry. */ long min_got_dynindx; /* The greatest dynamic symbol table index corresponding to a symbol with a GOT entry that is not referenced (e.g., a dynamic symbol with dynamic relocations pointing to it from non-primary GOTs). */ long max_unref_got_dynindx; /* The greatest dynamic symbol table index not corresponding to a symbol without a GOT entry. */ long max_non_got_dynindx; }; struct score_got_info { /* The global symbol in the GOT with the lowest index in the dynamic symbol table. */ struct elf_link_hash_entry *global_gotsym; /* The number of global .got entries. */ unsigned int global_gotno; /* The number of local .got entries. */ unsigned int local_gotno; /* The number of local .got entries we have used. */ unsigned int assigned_gotno; /* A hash table holding members of the got. */ struct htab *got_entries; /* In multi-got links, a pointer to the next got (err, rather, most of the time, it points to the previous got). */ struct score_got_info *next; }; /* A structure used to count GOT entries, for GOT entry or ELF symbol table traversal. */ struct _score_elf_section_data { struct bfd_elf_section_data elf; union { struct score_got_info *got_info; bfd_byte *tdata; } u; }; #define score_elf_section_data(sec) \ ((struct _score_elf_section_data *) elf_section_data (sec)) /* The size of a symbol-table entry. */ #define SCORE_ELF_SYM_SIZE(abfd) \ (get_elf_backend_data (abfd)->s->sizeof_sym) /* In case we're on a 32-bit machine, construct a 64-bit "-1" value from smaller values. Start with zero, widen, *then* decrement. */ #define MINUS_ONE (((bfd_vma)0) - 1) #define MINUS_TWO (((bfd_vma)0) - 2) #define PDR_SIZE 32 /* The number of local .got entries we reserve. */ #define SCORE_RESERVED_GOTNO (2) #define ELF_DYNAMIC_INTERPRETER "/usr/lib/ld.so.1" /* The offset of $gp from the beginning of the .got section. */ #define ELF_SCORE_GP_OFFSET(abfd) (0x3ff0) /* The maximum size of the GOT for it to be addressable using 15-bit offsets from $gp. */ #define SCORE_ELF_GOT_MAX_SIZE(abfd) (ELF_SCORE_GP_OFFSET(abfd) + 0x3fff) #define SCORE_ELF_STUB_SECTION_NAME (".SCORE.stub") #define SCORE_FUNCTION_STUB_SIZE (16) #define STUB_LW 0xc3bcc010 /* lw r29, [r28, -0x3ff0] */ #define STUB_MOVE 0x8363bc56 /* mv r27, r3 */ #define STUB_LI16 0x87548000 /* ori r26, .dynsym_index */ #define STUB_BRL 0x801dbc09 /* brl r29 */ #define SCORE_ELF_GOT_SIZE(abfd) \ (get_elf_backend_data (abfd)->s->arch_size / 8) #define SCORE_ELF_ADD_DYNAMIC_ENTRY(info, tag, val) \ (_bfd_elf_add_dynamic_entry (info, (bfd_vma) tag, (bfd_vma) val)) /* The size of an external dynamic table entry. */ #define SCORE_ELF_DYN_SIZE(abfd) \ (get_elf_backend_data (abfd)->s->sizeof_dyn) /* The size of an external REL relocation. */ #define SCORE_ELF_REL_SIZE(abfd) \ (get_elf_backend_data (abfd)->s->sizeof_rel) /* The default alignment for sections, as a power of two. */ #define SCORE_ELF_LOG_FILE_ALIGN(abfd)\ (get_elf_backend_data (abfd)->s->log_file_align) static bfd_byte *hi16_rel_addr; /* This will be used when we sort the dynamic relocation records. */ static bfd *reldyn_sorting_bfd; /* SCORE ELF uses two common sections. One is the usual one, and the other is for small objects. All the small objects are kept together, and then referenced via the gp pointer, which yields faster assembler code. This is what we use for the small common section. This approach is copied from ecoff.c. */ static asection score_elf_scom_section; static asymbol score_elf_scom_symbol; static asymbol *score_elf_scom_symbol_ptr; static bfd_vma score_bfd_get_16 (bfd *abfd, const void *data) { return bfd_get_16 (abfd, data); } static bfd_vma score3_bfd_getl32 (const void *p) { const bfd_byte *addr = p; unsigned long v; v = (unsigned long) addr[2]; v |= (unsigned long) addr[3] << 8; v |= (unsigned long) addr[0] << 16; v |= (unsigned long) addr[1] << 24; return v; } static bfd_vma score3_bfd_getl48 (const void *p) { const bfd_byte *addr = p; unsigned long long v; v = (unsigned long long) addr[4]; v |= (unsigned long long) addr[5] << 8; v |= (unsigned long long) addr[2] << 16; v |= (unsigned long long) addr[3] << 24; v |= (unsigned long long) addr[0] << 32; v |= (unsigned long long) addr[1] << 40; return v; } static bfd_vma score_bfd_get_32 (bfd *abfd, const void *data) { if (/* score3 && */ abfd->xvec->byteorder == BFD_ENDIAN_LITTLE) return score3_bfd_getl32 (data); else return bfd_get_32 (abfd, data); } static bfd_vma score_bfd_get_48 (bfd *abfd, const void *p) { if (/* score3 && */ abfd->xvec->byteorder == BFD_ENDIAN_LITTLE) return score3_bfd_getl48 (p); else return bfd_get_bits (p, 48, 1); } static void score_bfd_put_16 (bfd *abfd, bfd_vma addr, void *data) { return bfd_put_16 (abfd, addr, data); } static void score3_bfd_putl32 (bfd_vma data, void *p) { bfd_byte *addr = p; addr[0] = (data >> 16) & 0xff; addr[1] = (data >> 24) & 0xff; addr[2] = data & 0xff; addr[3] = (data >> 8) & 0xff; } static void score3_bfd_putl48 (bfd_vma data, void *p) { bfd_byte *addr = p; addr[0] = (data >> 32) & 0xff; addr[1] = (data >> 40) & 0xff; addr[2] = (data >> 16) & 0xff; addr[3] = (data >> 24) & 0xff; addr[4] = data & 0xff; addr[5] = (data >> 8) & 0xff; } static void score_bfd_put_32 (bfd *abfd, bfd_vma addr, void *data) { if (/* score3 && */ abfd->xvec->byteorder == BFD_ENDIAN_LITTLE) return score3_bfd_putl32 (addr, data); else return bfd_put_32 (abfd, addr, data); } static void score_bfd_put_48 (bfd *abfd, bfd_vma val, void *p) { if (/* score3 && */ abfd->xvec->byteorder == BFD_ENDIAN_LITTLE) return score3_bfd_putl48 (val, p); else return bfd_put_bits (val, p, 48, 1); } static bfd_reloc_status_type score_elf_hi16_reloc (bfd *abfd ATTRIBUTE_UNUSED, arelent *reloc_entry, asymbol *symbol ATTRIBUTE_UNUSED, void * data, asection *input_section ATTRIBUTE_UNUSED, bfd *output_bfd ATTRIBUTE_UNUSED, char **error_message ATTRIBUTE_UNUSED) { hi16_rel_addr = (bfd_byte *) data + reloc_entry->address; return bfd_reloc_ok; } static bfd_reloc_status_type score_elf_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol ATTRIBUTE_UNUSED, void * data, asection *input_section, bfd *output_bfd ATTRIBUTE_UNUSED, char **error_message ATTRIBUTE_UNUSED) { bfd_vma addend = 0, offset = 0; unsigned long val; unsigned long hi16_offset, hi16_value, uvalue; hi16_value = score_bfd_get_32 (abfd, hi16_rel_addr); hi16_offset = ((((hi16_value >> 16) & 0x3) << 15) | (hi16_value & 0x7fff)) >> 1; addend = score_bfd_get_32 (abfd, (bfd_byte *) data + reloc_entry->address); offset = ((((addend >> 16) & 0x3) << 15) | (addend & 0x7fff)) >> 1; val = reloc_entry->addend; if (reloc_entry->address > input_section->size) return bfd_reloc_outofrange; uvalue = ((hi16_offset << 16) | (offset & 0xffff)) + val; hi16_offset = (uvalue >> 16) << 1; hi16_value = (hi16_value & ~0x37fff) | (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000); score_bfd_put_32 (abfd, hi16_value, hi16_rel_addr); offset = (uvalue & 0xffff) << 1; addend = (addend & ~0x37fff) | (offset & 0x7fff) | ((offset << 1) & 0x30000); score_bfd_put_32 (abfd, addend, (bfd_byte *) data + reloc_entry->address); return bfd_reloc_ok; } /* Set the GP value for OUTPUT_BFD. Returns FALSE if this is a dangerous relocation. */ static bfd_boolean score_elf_assign_gp (bfd *output_bfd, bfd_vma *pgp) { unsigned int count; asymbol **sym; unsigned int i; /* If we've already figured out what GP will be, just return it. */ *pgp = _bfd_get_gp_value (output_bfd); if (*pgp) return TRUE; count = bfd_get_symcount (output_bfd); sym = bfd_get_outsymbols (output_bfd); /* The linker script will have created a symbol named `_gp' with the appropriate value. */ if (sym == NULL) i = count; else { for (i = 0; i < count; i++, sym++) { const char *name; name = bfd_asymbol_name (*sym); if (*name == '_' && strcmp (name, "_gp") == 0) { *pgp = bfd_asymbol_value (*sym); _bfd_set_gp_value (output_bfd, *pgp); break; } } } if (i >= count) { /* Only get the error once. */ *pgp = 4; _bfd_set_gp_value (output_bfd, *pgp); return FALSE; } return TRUE; } /* We have to figure out the gp value, so that we can adjust the symbol value correctly. We look up the symbol _gp in the output BFD. If we can't find it, we're stuck. We cache it in the ELF target data. We don't need to adjust the symbol value for an external symbol if we are producing relocatable output. */ static bfd_reloc_status_type score_elf_final_gp (bfd *output_bfd, asymbol *symbol, bfd_boolean relocatable, char **error_message, bfd_vma *pgp) { if (bfd_is_und_section (symbol->section) && ! relocatable) { *pgp = 0; return bfd_reloc_undefined; } *pgp = _bfd_get_gp_value (output_bfd); if (*pgp == 0 && (! relocatable || (symbol->flags & BSF_SECTION_SYM) != 0)) { if (relocatable) { /* Make up a value. */ *pgp = symbol->section->output_section->vma + 0x4000; _bfd_set_gp_value (output_bfd, *pgp); } else if (!score_elf_assign_gp (output_bfd, pgp)) { *error_message = (char *) _("GP relative relocation when _gp not defined"); return bfd_reloc_dangerous; } } return bfd_reloc_ok; } static bfd_reloc_status_type score_elf_gprel15_with_gp (bfd *abfd, asymbol *symbol, arelent *reloc_entry, asection *input_section, bfd_boolean relocateable, void * data, bfd_vma gp ATTRIBUTE_UNUSED) { bfd_vma relocation; unsigned long insn; if (bfd_is_com_section (symbol->section)) relocation = 0; else relocation = symbol->value; relocation += symbol->section->output_section->vma; relocation += symbol->section->output_offset; if (reloc_entry->address > input_section->size) return bfd_reloc_outofrange; insn = score_bfd_get_32 (abfd, (bfd_byte *) data + reloc_entry->address); if (((reloc_entry->addend & 0xffffc000) != 0) && ((reloc_entry->addend & 0xffffc000) != 0xffffc000)) return bfd_reloc_overflow; insn = (insn & ~0x7fff) | (reloc_entry->addend & 0x7fff); score_bfd_put_32 (abfd, insn, (bfd_byte *) data + reloc_entry->address); if (relocateable) reloc_entry->address += input_section->output_offset; return bfd_reloc_ok; } static bfd_reloc_status_type gprel32_with_gp (bfd *abfd, asymbol *symbol, arelent *reloc_entry, asection *input_section, bfd_boolean relocatable, void *data, bfd_vma gp) { bfd_vma relocation; bfd_vma val; if (bfd_is_com_section (symbol->section)) relocation = 0; else relocation = symbol->value; relocation += symbol->section->output_section->vma; relocation += symbol->section->output_offset; if (reloc_entry->address > bfd_get_section_limit (abfd, input_section)) return bfd_reloc_outofrange; /* Set val to the offset into the section or symbol. */ val = reloc_entry->addend; if (reloc_entry->howto->partial_inplace) val += score_bfd_get_32 (abfd, (bfd_byte *) data + reloc_entry->address); /* Adjust val for the final section location and GP value. If we are producing relocatable output, we don't want to do this for an external symbol. */ if (! relocatable || (symbol->flags & BSF_SECTION_SYM) != 0) val += relocation - gp; if (reloc_entry->howto->partial_inplace) score_bfd_put_32 (abfd, val, (bfd_byte *) data + reloc_entry->address); else reloc_entry->addend = val; if (relocatable) reloc_entry->address += input_section->output_offset; return bfd_reloc_ok; } static bfd_reloc_status_type score_elf_gprel15_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol, void * data, asection *input_section, bfd *output_bfd, char **error_message) { bfd_boolean relocateable; bfd_reloc_status_type ret; bfd_vma gp; if (output_bfd != NULL && (symbol->flags & BSF_SECTION_SYM) == 0 && reloc_entry->addend == 0) { reloc_entry->address += input_section->output_offset; return bfd_reloc_ok; } if (output_bfd != NULL) relocateable = TRUE; else { relocateable = FALSE; output_bfd = symbol->section->output_section->owner; } ret = score_elf_final_gp (output_bfd, symbol, relocateable, error_message, &gp); if (ret != bfd_reloc_ok) return ret; return score_elf_gprel15_with_gp (abfd, symbol, reloc_entry, input_section, relocateable, data, gp); } /* Do a R_SCORE_GPREL32 relocation. This is a 32 bit value which must become the offset from the gp register. */ static bfd_reloc_status_type score_elf_gprel32_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol, void *data, asection *input_section, bfd *output_bfd, char **error_message) { bfd_boolean relocatable; bfd_reloc_status_type ret; bfd_vma gp; /* R_SCORE_GPREL32 relocations are defined for local symbols only. */ if (output_bfd != NULL && (symbol->flags & BSF_SECTION_SYM) == 0 && (symbol->flags & BSF_LOCAL) != 0) { *error_message = (char *) _("32bits gp relative relocation occurs for an external symbol"); return bfd_reloc_outofrange; } if (output_bfd != NULL) relocatable = TRUE; else { relocatable = FALSE; output_bfd = symbol->section->output_section->owner; } ret = score_elf_final_gp (output_bfd, symbol, relocatable, error_message, &gp); if (ret != bfd_reloc_ok) return ret; gp = 0; return gprel32_with_gp (abfd, symbol, reloc_entry, input_section, relocatable, data, gp); } /* A howto special_function for R_SCORE_GOT15 relocations. This is just like any other 16-bit relocation when applied to global symbols, but is treated in the same as R_SCORE_HI16 when applied to local symbols. */ static bfd_reloc_status_type score_elf_got15_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol, void *data, asection *input_section, bfd *output_bfd, char **error_message) { if ((symbol->flags & (BSF_GLOBAL | BSF_WEAK)) != 0 || bfd_is_und_section (bfd_get_section (symbol)) || bfd_is_com_section (bfd_get_section (symbol))) /* The relocation is against a global symbol. */ return bfd_elf_generic_reloc (abfd, reloc_entry, symbol, data, input_section, output_bfd, error_message); return score_elf_hi16_reloc (abfd, reloc_entry, symbol, data, input_section, output_bfd, error_message); } static bfd_reloc_status_type score_elf_got_lo16_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol ATTRIBUTE_UNUSED, void * data, asection *input_section, bfd *output_bfd ATTRIBUTE_UNUSED, char **error_message ATTRIBUTE_UNUSED) { bfd_vma addend = 0, offset = 0; signed long val; signed long hi16_offset, hi16_value, uvalue; hi16_value = score_bfd_get_32 (abfd, hi16_rel_addr); hi16_offset = ((((hi16_value >> 16) & 0x3) << 15) | (hi16_value & 0x7fff)) >> 1; addend = score_bfd_get_32 (abfd, (bfd_byte *) data + reloc_entry->address); offset = ((((addend >> 16) & 0x3) << 15) | (addend & 0x7fff)) >> 1; val = reloc_entry->addend; if (reloc_entry->address > input_section->size) return bfd_reloc_outofrange; uvalue = ((hi16_offset << 16) | (offset & 0xffff)) + val; if ((uvalue > -0x8000) && (uvalue < 0x7fff)) hi16_offset = 0; else hi16_offset = (uvalue >> 16) & 0x7fff; hi16_value = (hi16_value & ~0x37fff) | (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000); score_bfd_put_32 (abfd, hi16_value, hi16_rel_addr); offset = (uvalue & 0xffff) << 1; addend = (addend & ~0x37fff) | (offset & 0x7fff) | ((offset << 1) & 0x30000); score_bfd_put_32 (abfd, addend, (bfd_byte *) data + reloc_entry->address); return bfd_reloc_ok; } static reloc_howto_type elf32_score_howto_table[] = { /* No relocation. */ HOWTO (R_SCORE_NONE, /* type */ 0, /* rightshift */ 3, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_NONE", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ /* R_SCORE_HI16 */ HOWTO (R_SCORE_HI16, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 1, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ score_elf_hi16_reloc, /* special_function */ "R_SCORE_HI16", /* name */ TRUE, /* partial_inplace */ 0x37fff, /* src_mask */ 0x37fff, /* dst_mask */ FALSE), /* pcrel_offset */ /* R_SCORE_LO16 */ HOWTO (R_SCORE_LO16, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 1, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ score_elf_lo16_reloc, /* special_function */ "R_SCORE_LO16", /* name */ TRUE, /* partial_inplace */ 0x37fff, /* src_mask */ 0x37fff, /* dst_mask */ FALSE), /* pcrel_offset */ /* R_SCORE_BCMP */ HOWTO (R_SCORE_BCMP, /* type */ 1, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ TRUE, /* pc_relative */ 1, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_BCMP", /* name */ FALSE, /* partial_inplace */ 0x03e00381, /* src_mask */ 0x03e00381, /* dst_mask */ FALSE), /* pcrel_offset */ /*R_SCORE_24 */ HOWTO (R_SCORE_24, /* type */ 1, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 24, /* bitsize */ FALSE, /* pc_relative */ 1, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_24", /* name */ FALSE, /* partial_inplace */ 0x3ff7fff, /* src_mask */ 0x3ff7fff, /* dst_mask */ FALSE), /* pcrel_offset */ /*R_SCORE_PC19 */ HOWTO (R_SCORE_PC19, /* type */ 1, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 19, /* bitsize */ TRUE, /* pc_relative */ 1, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_PC19", /* name */ FALSE, /* partial_inplace */ 0x3ff03fe, /* src_mask */ 0x3ff03fe, /* dst_mask */ FALSE), /* pcrel_offset */ /*R_SCORE16_11 */ HOWTO (R_SCORE16_11, /* type */ 1, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 11, /* bitsize */ FALSE, /* pc_relative */ 1, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE16_11", /* name */ FALSE, /* partial_inplace */ 0x000000ffe, /* src_mask */ 0x000000ffe, /* dst_mask */ FALSE), /* pcrel_offset */ /* R_SCORE16_PC8 */ HOWTO (R_SCORE16_PC8, /* type */ 1, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 9, /* bitsize */ TRUE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE16_PC8", /* name */ FALSE, /* partial_inplace */ 0x000001ff, /* src_mask */ 0x000001ff, /* dst_mask */ FALSE), /* pcrel_offset */ /* 32 bit absolute */ HOWTO (R_SCORE_ABS32, /* type 8 */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_ABS32", /* name */ FALSE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* 16 bit absolute */ HOWTO (R_SCORE_ABS16, /* type 11 */ 0, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_ABS16", /* name */ FALSE, /* partial_inplace */ 0x0000ffff, /* src_mask */ 0x0000ffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* R_SCORE_DUMMY2 */ HOWTO (R_SCORE_DUMMY2, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_DUMMY2", /* name */ TRUE, /* partial_inplace */ 0x00007fff, /* src_mask */ 0x00007fff, /* dst_mask */ FALSE), /* pcrel_offset */ /* R_SCORE_GP15 */ HOWTO (R_SCORE_GP15, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ score_elf_gprel15_reloc,/* special_function */ "R_SCORE_GP15", /* name */ TRUE, /* partial_inplace */ 0x00007fff, /* src_mask */ 0x00007fff, /* dst_mask */ FALSE), /* pcrel_offset */ /* GNU extension to record C++ vtable hierarchy. */ HOWTO (R_SCORE_GNU_VTINHERIT, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ NULL, /* special_function */ "R_SCORE_GNU_VTINHERIT", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ /* GNU extension to record C++ vtable member usage */ HOWTO (R_SCORE_GNU_VTENTRY, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ _bfd_elf_rel_vtable_reloc_fn, /* special_function */ "R_SCORE_GNU_VTENTRY", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ /* Reference to global offset table. */ HOWTO (R_SCORE_GOT15, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ score_elf_got15_reloc, /* special_function */ "R_SCORE_GOT15", /* name */ TRUE, /* partial_inplace */ 0x00007fff, /* src_mask */ 0x00007fff, /* dst_mask */ FALSE), /* pcrel_offset */ /* Low 16 bits of displacement in global offset table. */ HOWTO (R_SCORE_GOT_LO16, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 1, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ score_elf_got_lo16_reloc, /* special_function */ "R_SCORE_GOT_LO16", /* name */ TRUE, /* partial_inplace */ 0x37ffe, /* src_mask */ 0x37ffe, /* dst_mask */ FALSE), /* pcrel_offset */ /* 15 bit call through global offset table. */ HOWTO (R_SCORE_CALL15, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_CALL15", /* name */ TRUE, /* partial_inplace */ 0x0000ffff, /* src_mask */ 0x0000ffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* 32 bit GP relative reference. */ HOWTO (R_SCORE_GPREL32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ score_elf_gprel32_reloc, /* special_function */ "R_SCORE_GPREL32", /* name */ TRUE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* 32 bit symbol relative relocation. */ HOWTO (R_SCORE_REL32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_REL32", /* name */ TRUE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* R_SCORE_DUMMY_HI16 */ HOWTO (R_SCORE_DUMMY_HI16, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 1, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ score_elf_hi16_reloc, /* special_function */ "R_SCORE_DUMMY_HI16", /* name */ TRUE, /* partial_inplace */ 0x37fff, /* src_mask */ 0x37fff, /* dst_mask */ FALSE), /* pcrel_offset */ /* R_SCORE_IMM30 */ HOWTO (R_SCORE_IMM30, /* type */ 2, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 30, /* bitsize */ FALSE, /* pc_relative */ 7, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_IMM30", /* name */ FALSE, /* partial_inplace */ 0x7f7fff7f80LL, /* src_mask */ 0x7f7fff7f80LL, /* dst_mask */ FALSE), /* pcrel_offset */ /* R_SCORE_IMM32 */ HOWTO (R_SCORE_IMM32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 5, /* bitpos */ complain_overflow_dont,/* complain_on_overflow */ bfd_elf_generic_reloc, /* special_function */ "R_SCORE_IMM32", /* name */ FALSE, /* partial_inplace */ 0x7f7fff7fe0LL, /* src_mask */ 0x7f7fff7fe0LL, /* dst_mask */ FALSE), /* pcrel_offset */ }; struct score_reloc_map { bfd_reloc_code_real_type bfd_reloc_val; unsigned char elf_reloc_val; }; static const struct score_reloc_map elf32_score_reloc_map[] = { {BFD_RELOC_NONE, R_SCORE_NONE}, {BFD_RELOC_HI16_S, R_SCORE_HI16}, {BFD_RELOC_LO16, R_SCORE_LO16}, {BFD_RELOC_SCORE_BCMP, R_SCORE_BCMP}, {BFD_RELOC_SCORE_JMP, R_SCORE_24}, {BFD_RELOC_SCORE_BRANCH, R_SCORE_PC19}, {BFD_RELOC_SCORE16_JMP, R_SCORE16_11}, {BFD_RELOC_SCORE16_BRANCH, R_SCORE16_PC8}, {BFD_RELOC_32, R_SCORE_ABS32}, {BFD_RELOC_16, R_SCORE_ABS16}, {BFD_RELOC_SCORE_DUMMY2, R_SCORE_DUMMY2}, {BFD_RELOC_SCORE_GPREL15, R_SCORE_GP15}, {BFD_RELOC_VTABLE_INHERIT, R_SCORE_GNU_VTINHERIT}, {BFD_RELOC_VTABLE_ENTRY, R_SCORE_GNU_VTENTRY}, {BFD_RELOC_SCORE_GOT15, R_SCORE_GOT15}, {BFD_RELOC_SCORE_GOT_LO16, R_SCORE_GOT_LO16}, {BFD_RELOC_SCORE_CALL15, R_SCORE_CALL15}, {BFD_RELOC_GPREL32, R_SCORE_GPREL32}, {BFD_RELOC_32_PCREL, R_SCORE_REL32}, {BFD_RELOC_SCORE_DUMMY_HI16, R_SCORE_DUMMY_HI16}, {BFD_RELOC_SCORE_IMM30, R_SCORE_IMM30}, {BFD_RELOC_SCORE_IMM32, R_SCORE_IMM32}, }; /* got_entries only match if they're identical, except for gotidx, so use all fields to compute the hash, and compare the appropriate union members. */ static hashval_t score_elf_got_entry_hash (const void *entry_) { const struct score_got_entry *entry = (struct score_got_entry *)entry_; return entry->symndx + (!entry->abfd ? entry->d.address : entry->abfd->id); } static int score_elf_got_entry_eq (const void *entry1, const void *entry2) { const struct score_got_entry *e1 = (struct score_got_entry *)entry1; const struct score_got_entry *e2 = (struct score_got_entry *)entry2; return e1->abfd == e2->abfd && e1->symndx == e2->symndx && (! e1->abfd ? e1->d.address == e2->d.address : e1->symndx >= 0 ? e1->d.addend == e2->d.addend : e1->d.h == e2->d.h); } /* If H needs a GOT entry, assign it the highest available dynamic index. Otherwise, assign it the lowest available dynamic index. */ static bfd_boolean score_elf_sort_hash_table_f (struct score_elf_link_hash_entry *h, void *data) { struct score_elf_hash_sort_data *hsd = data; /* Symbols without dynamic symbol table entries aren't interesting at all. */ if (h->root.dynindx == -1) return TRUE; /* Global symbols that need GOT entries that are not explicitly referenced are marked with got offset 2. Those that are referenced get a 1, and those that don't need GOT entries get -1. */ if (h->root.got.offset == 2) { if (hsd->max_unref_got_dynindx == hsd->min_got_dynindx) hsd->low = (struct elf_link_hash_entry *) h; h->root.dynindx = hsd->max_unref_got_dynindx++; } else if (h->root.got.offset != 1) h->root.dynindx = hsd->max_non_got_dynindx++; else { h->root.dynindx = --hsd->min_got_dynindx; hsd->low = (struct elf_link_hash_entry *) h; } return TRUE; } static asection * score_elf_got_section (bfd *abfd, bfd_boolean maybe_excluded) { asection *sgot = bfd_get_linker_section (abfd, ".got"); if (sgot == NULL || (! maybe_excluded && (sgot->flags & SEC_EXCLUDE) != 0)) return NULL; return sgot; } /* Returns the GOT information associated with the link indicated by INFO. If SGOTP is non-NULL, it is filled in with the GOT section. */ static struct score_got_info * score_elf_got_info (bfd *abfd, asection **sgotp) { asection *sgot; struct score_got_info *g; sgot = score_elf_got_section (abfd, TRUE); BFD_ASSERT (sgot != NULL); BFD_ASSERT (elf_section_data (sgot) != NULL); g = score_elf_section_data (sgot)->u.got_info; BFD_ASSERT (g != NULL); if (sgotp) *sgotp = sgot; return g; } /* Sort the dynamic symbol table so that symbols that need GOT entries appear towards the end. This reduces the amount of GOT space required. MAX_LOCAL is used to set the number of local symbols known to be in the dynamic symbol table. During s3_bfd_score_elf_size_dynamic_sections, this value is 1. Afterward, the section symbols are added and the count is higher. */ static bfd_boolean score_elf_sort_hash_table (struct bfd_link_info *info, unsigned long max_local) { struct score_elf_hash_sort_data hsd; struct score_got_info *g; bfd *dynobj; dynobj = elf_hash_table (info)->dynobj; g = score_elf_got_info (dynobj, NULL); hsd.low = NULL; hsd.max_unref_got_dynindx = hsd.min_got_dynindx = elf_hash_table (info)->dynsymcount /* In the multi-got case, assigned_gotno of the master got_info indicate the number of entries that aren't referenced in the primary GOT, but that must have entries because there are dynamic relocations that reference it. Since they aren't referenced, we move them to the end of the GOT, so that they don't prevent other entries that are referenced from getting too large offsets. */ - (g->next ? g->assigned_gotno : 0); hsd.max_non_got_dynindx = max_local; score_elf_link_hash_traverse (elf_hash_table (info), score_elf_sort_hash_table_f, &hsd); /* There should have been enough room in the symbol table to accommodate both the GOT and non-GOT symbols. */ BFD_ASSERT (hsd.max_non_got_dynindx <= hsd.min_got_dynindx); BFD_ASSERT ((unsigned long)hsd.max_unref_got_dynindx <= elf_hash_table (info)->dynsymcount); /* Now we know which dynamic symbol has the lowest dynamic symbol table index in the GOT. */ g->global_gotsym = hsd.low; return TRUE; } /* Create an entry in an score ELF linker hash table. */ static struct bfd_hash_entry * score_elf_link_hash_newfunc (struct bfd_hash_entry *entry, struct bfd_hash_table *table, const char *string) { struct score_elf_link_hash_entry *ret = (struct score_elf_link_hash_entry *) entry; /* Allocate the structure if it has not already been allocated by a subclass. */ if (ret == NULL) ret = bfd_hash_allocate (table, sizeof (struct score_elf_link_hash_entry)); if (ret == NULL) return (struct bfd_hash_entry *) ret; /* Call the allocation method of the superclass. */ ret = ((struct score_elf_link_hash_entry *) _bfd_elf_link_hash_newfunc ((struct bfd_hash_entry *) ret, table, string)); if (ret != NULL) { ret->possibly_dynamic_relocs = 0; ret->readonly_reloc = FALSE; ret->no_fn_stub = FALSE; ret->forced_local = FALSE; } return (struct bfd_hash_entry *) ret; } /* Returns the first relocation of type r_type found, beginning with RELOCATION. RELEND is one-past-the-end of the relocation table. */ static const Elf_Internal_Rela * score_elf_next_relocation (bfd *abfd ATTRIBUTE_UNUSED, unsigned int r_type, const Elf_Internal_Rela *relocation, const Elf_Internal_Rela *relend) { while (relocation < relend) { if (ELF32_R_TYPE (relocation->r_info) == r_type) return relocation; ++relocation; } /* We didn't find it. */ bfd_set_error (bfd_error_bad_value); return NULL; } /* This function is called via qsort() to sort the dynamic relocation entries by increasing r_symndx value. */ static int score_elf_sort_dynamic_relocs (const void *arg1, const void *arg2) { Elf_Internal_Rela int_reloc1; Elf_Internal_Rela int_reloc2; bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg1, &int_reloc1); bfd_elf32_swap_reloc_in (reldyn_sorting_bfd, arg2, &int_reloc2); return (ELF32_R_SYM (int_reloc1.r_info) - ELF32_R_SYM (int_reloc2.r_info)); } /* Return whether a relocation is against a local symbol. */ static bfd_boolean score_elf_local_relocation_p (bfd *input_bfd, const Elf_Internal_Rela *relocation, asection **local_sections, bfd_boolean check_forced) { unsigned long r_symndx; Elf_Internal_Shdr *symtab_hdr; struct score_elf_link_hash_entry *h; size_t extsymoff; r_symndx = ELF32_R_SYM (relocation->r_info); symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr; extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info; if (r_symndx < extsymoff) return TRUE; if (elf_bad_symtab (input_bfd) && local_sections[r_symndx] != NULL) return TRUE; if (check_forced) { /* Look up the hash table to check whether the symbol was forced local. */ h = (struct score_elf_link_hash_entry *) elf_sym_hashes (input_bfd) [r_symndx - extsymoff]; /* Find the real hash-table entry for this symbol. */ while (h->root.root.type == bfd_link_hash_indirect || h->root.root.type == bfd_link_hash_warning) h = (struct score_elf_link_hash_entry *) h->root.root.u.i.link; if (h->root.forced_local) return TRUE; } return FALSE; } /* Returns the dynamic relocation section for DYNOBJ. */ static asection * score_elf_rel_dyn_section (bfd *dynobj, bfd_boolean create_p) { static const char dname[] = ".rel.dyn"; asection *sreloc; sreloc = bfd_get_linker_section (dynobj, dname); if (sreloc == NULL && create_p) { sreloc = bfd_make_section_anyway_with_flags (dynobj, dname, (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED | SEC_READONLY)); if (sreloc == NULL || ! bfd_set_section_alignment (dynobj, sreloc, SCORE_ELF_LOG_FILE_ALIGN (dynobj))) return NULL; } return sreloc; } static void score_elf_allocate_dynamic_relocations (bfd *abfd, unsigned int n) { asection *s; s = score_elf_rel_dyn_section (abfd, FALSE); BFD_ASSERT (s != NULL); if (s->size == 0) { /* Make room for a null element. */ s->size += SCORE_ELF_REL_SIZE (abfd); ++s->reloc_count; } s->size += n * SCORE_ELF_REL_SIZE (abfd); } /* Create a rel.dyn relocation for the dynamic linker to resolve. REL is the original relocation, which is now being transformed into a dynamic relocation. The ADDENDP is adjusted if necessary; the caller should store the result in place of the original addend. */ static bfd_boolean score_elf_create_dynamic_relocation (bfd *output_bfd, struct bfd_link_info *info, const Elf_Internal_Rela *rel, struct score_elf_link_hash_entry *h, bfd_vma symbol, bfd_vma *addendp, asection *input_section) { Elf_Internal_Rela outrel[3]; asection *sreloc; bfd *dynobj; int r_type; long indx; bfd_boolean defined_p; r_type = ELF32_R_TYPE (rel->r_info); dynobj = elf_hash_table (info)->dynobj; sreloc = score_elf_rel_dyn_section (dynobj, FALSE); BFD_ASSERT (sreloc != NULL); BFD_ASSERT (sreloc->contents != NULL); BFD_ASSERT (sreloc->reloc_count * SCORE_ELF_REL_SIZE (output_bfd) < sreloc->size); outrel[0].r_offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel[0].r_offset); outrel[1].r_offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel[1].r_offset); outrel[2].r_offset = _bfd_elf_section_offset (output_bfd, info, input_section, rel[2].r_offset); if (outrel[0].r_offset == MINUS_ONE) /* The relocation field has been deleted. */ return TRUE; if (outrel[0].r_offset == MINUS_TWO) { /* The relocation field has been converted into a relative value of some sort. Functions like _bfd_elf_write_section_eh_frame expect the field to be fully relocated, so add in the symbol's value. */ *addendp += symbol; return TRUE; } /* We must now calculate the dynamic symbol table index to use in the relocation. */ if (h != NULL && (! info->symbolic || !h->root.def_regular) /* h->root.dynindx may be -1 if this symbol was marked to become local. */ && h->root.dynindx != -1) { indx = h->root.dynindx; /* ??? glibc's ld.so just adds the final GOT entry to the relocation field. It therefore treats relocs against defined symbols in the same way as relocs against undefined symbols. */ defined_p = FALSE; } else { indx = 0; defined_p = TRUE; } /* If the relocation was previously an absolute relocation and this symbol will not be referred to by the relocation, we must adjust it by the value we give it in the dynamic symbol table. Otherwise leave the job up to the dynamic linker. */ if (defined_p && r_type != R_SCORE_REL32) *addendp += symbol; /* The relocation is always an REL32 relocation because we don't know where the shared library will wind up at load-time. */ outrel[0].r_info = ELF32_R_INFO ((unsigned long) indx, R_SCORE_REL32); /* For strict adherence to the ABI specification, we should generate a R_SCORE_64 relocation record by itself before the _REL32/_64 record as well, such that the addend is read in as a 64-bit value (REL32 is a 32-bit relocation, after all). However, since none of the existing ELF64 SCORE dynamic loaders seems to care, we don't waste space with these artificial relocations. If this turns out to not be true, score_elf_allocate_dynamic_relocations() should be tweaked so as to make room for a pair of dynamic relocations per invocation if ABI_64_P, and here we should generate an additional relocation record with R_SCORE_64 by itself for a NULL symbol before this relocation record. */ outrel[1].r_info = ELF32_R_INFO (0, R_SCORE_NONE); outrel[2].r_info = ELF32_R_INFO (0, R_SCORE_NONE); /* Adjust the output offset of the relocation to reference the correct location in the output file. */ outrel[0].r_offset += (input_section->output_section->vma + input_section->output_offset); outrel[1].r_offset += (input_section->output_section->vma + input_section->output_offset); outrel[2].r_offset += (input_section->output_section->vma + input_section->output_offset); /* Put the relocation back out. We have to use the special relocation outputter in the 64-bit case since the 64-bit relocation format is non-standard. */ bfd_elf32_swap_reloc_out (output_bfd, &outrel[0], (sreloc->contents + sreloc->reloc_count * sizeof (Elf32_External_Rel))); /* We've now added another relocation. */ ++sreloc->reloc_count; /* Make sure the output section is writable. The dynamic linker will be writing to it. */ elf_section_data (input_section->output_section)->this_hdr.sh_flags |= SHF_WRITE; return TRUE; } static bfd_boolean score_elf_create_got_section (bfd *abfd, struct bfd_link_info *info, bfd_boolean maybe_exclude) { flagword flags; asection *s; struct elf_link_hash_entry *h; struct bfd_link_hash_entry *bh; struct score_got_info *g; bfd_size_type amt; /* This function may be called more than once. */ s = score_elf_got_section (abfd, TRUE); if (s) { if (! maybe_exclude) s->flags &= ~SEC_EXCLUDE; return TRUE; } flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED); if (maybe_exclude) flags |= SEC_EXCLUDE; /* We have to use an alignment of 2**4 here because this is hardcoded in the function stub generation and in the linker script. */ s = bfd_make_section_anyway_with_flags (abfd, ".got", flags); elf_hash_table (info)->sgot = s; if (s == NULL || ! bfd_set_section_alignment (abfd, s, 4)) return FALSE; /* Define the symbol _GLOBAL_OFFSET_TABLE_. We don't do this in the linker script because we don't want to define the symbol if we are not creating a global offset table. */ bh = NULL; if (! (_bfd_generic_link_add_one_symbol (info, abfd, "_GLOBAL_OFFSET_TABLE_", BSF_GLOBAL, s, 0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh))) return FALSE; h = (struct elf_link_hash_entry *) bh; h->non_elf = 0; h->def_regular = 1; h->type = STT_OBJECT; elf_hash_table (info)->hgot = h; if (bfd_link_pic (info) && ! bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; amt = sizeof (struct score_got_info); g = bfd_alloc (abfd, amt); if (g == NULL) return FALSE; g->global_gotsym = NULL; g->global_gotno = 0; g->local_gotno = SCORE_RESERVED_GOTNO; g->assigned_gotno = SCORE_RESERVED_GOTNO; g->next = NULL; g->got_entries = htab_try_create (1, score_elf_got_entry_hash, score_elf_got_entry_eq, NULL); if (g->got_entries == NULL) return FALSE; score_elf_section_data (s)->u.got_info = g; score_elf_section_data (s)->elf.this_hdr.sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_SCORE_GPREL; return TRUE; } /* Calculate the %high function. */ static bfd_vma score_elf_high (bfd_vma value) { return ((value + (bfd_vma) 0x8000) >> 16) & 0xffff; } /* Create a local GOT entry for VALUE. Return the index of the entry, or -1 if it could not be created. */ static struct score_got_entry * score_elf_create_local_got_entry (bfd *abfd, bfd *ibfd ATTRIBUTE_UNUSED, struct score_got_info *gg, asection *sgot, bfd_vma value, unsigned long r_symndx ATTRIBUTE_UNUSED, struct score_elf_link_hash_entry *h ATTRIBUTE_UNUSED, int r_type ATTRIBUTE_UNUSED) { struct score_got_entry entry, **loc; struct score_got_info *g; entry.abfd = NULL; entry.symndx = -1; entry.d.address = value; g = gg; loc = (struct score_got_entry **) htab_find_slot (g->got_entries, &entry, INSERT); if (*loc) return *loc; entry.gotidx = SCORE_ELF_GOT_SIZE (abfd) * g->assigned_gotno++; *loc = bfd_alloc (abfd, sizeof entry); if (! *loc) return NULL; memcpy (*loc, &entry, sizeof entry); if (g->assigned_gotno >= g->local_gotno) { (*loc)->gotidx = -1; /* We didn't allocate enough space in the GOT. */ _bfd_error_handler (_("not enough GOT space for local GOT entries")); bfd_set_error (bfd_error_bad_value); return NULL; } score_bfd_put_32 (abfd, value, (sgot->contents + entry.gotidx)); return *loc; } /* Find a GOT entry whose higher-order 16 bits are the same as those for value. Return the index into the GOT for this entry. */ static bfd_vma score_elf_got16_entry (bfd *abfd, bfd *ibfd, struct bfd_link_info *info, bfd_vma value, bfd_boolean external) { asection *sgot; struct score_got_info *g; struct score_got_entry *entry; if (!external) { /* Although the ABI says that it is "the high-order 16 bits" that we want, it is really the %high value. The complete value is calculated with a `addiu' of a LO16 relocation, just as with a HI16/LO16 pair. */ value = score_elf_high (value) << 16; } g = score_elf_got_info (elf_hash_table (info)->dynobj, &sgot); entry = score_elf_create_local_got_entry (abfd, ibfd, g, sgot, value, 0, NULL, R_SCORE_GOT15); if (entry) return entry->gotidx; else return MINUS_ONE; } static void s3_bfd_score_elf_hide_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *entry, bfd_boolean force_local) { bfd *dynobj; asection *got; struct score_got_info *g; struct score_elf_link_hash_entry *h; h = (struct score_elf_link_hash_entry *) entry; if (h->forced_local) return; h->forced_local = TRUE; dynobj = elf_hash_table (info)->dynobj; if (dynobj != NULL && force_local) { got = score_elf_got_section (dynobj, FALSE); if (got == NULL) return; g = score_elf_section_data (got)->u.got_info; if (g->next) { struct score_got_entry e; struct score_got_info *gg = g; /* Since we're turning what used to be a global symbol into a local one, bump up the number of local entries of each GOT that had an entry for it. This will automatically decrease the number of global entries, since global_gotno is actually the upper limit of global entries. */ e.abfd = dynobj; e.symndx = -1; e.d.h = h; for (g = g->next; g != gg; g = g->next) if (htab_find (g->got_entries, &e)) { BFD_ASSERT (g->global_gotno > 0); g->local_gotno++; g->global_gotno--; } /* If this was a global symbol forced into the primary GOT, we no longer need an entry for it. We can't release the entry at this point, but we must at least stop counting it as one of the symbols that required a forced got entry. */ if (h->root.got.offset == 2) { BFD_ASSERT (gg->assigned_gotno > 0); gg->assigned_gotno--; } } else if (g->global_gotno == 0 && g->global_gotsym == NULL) /* If we haven't got through GOT allocation yet, just bump up the number of local entries, as this symbol won't be counted as global. */ g->local_gotno++; else if (h->root.got.offset == 1) { /* If we're past non-multi-GOT allocation and this symbol had been marked for a global got entry, give it a local entry instead. */ BFD_ASSERT (g->global_gotno > 0); g->local_gotno++; g->global_gotno--; } } _bfd_elf_link_hash_hide_symbol (info, &h->root, force_local); } /* If H is a symbol that needs a global GOT entry, but has a dynamic symbol table index lower than any we've seen to date, record it for posterity. */ static bfd_boolean score_elf_record_global_got_symbol (struct elf_link_hash_entry *h, bfd *abfd, struct bfd_link_info *info, struct score_got_info *g) { struct score_got_entry entry, **loc; /* A global symbol in the GOT must also be in the dynamic symbol table. */ if (h->dynindx == -1) { switch (ELF_ST_VISIBILITY (h->other)) { case STV_INTERNAL: case STV_HIDDEN: s3_bfd_score_elf_hide_symbol (info, h, TRUE); break; } if (!bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; } entry.abfd = abfd; entry.symndx = -1; entry.d.h = (struct score_elf_link_hash_entry *)h; loc = (struct score_got_entry **)htab_find_slot (g->got_entries, &entry, INSERT); /* If we've already marked this entry as needing GOT space, we don't need to do it again. */ if (*loc) return TRUE; *loc = bfd_alloc (abfd, sizeof entry); if (! *loc) return FALSE; entry.gotidx = -1; memcpy (*loc, &entry, sizeof (entry)); if (h->got.offset != MINUS_ONE) return TRUE; /* By setting this to a value other than -1, we are indicating that there needs to be a GOT entry for H. Avoid using zero, as the generic ELF copy_indirect_symbol tests for <= 0. */ h->got.offset = 1; return TRUE; } /* Reserve space in G for a GOT entry containing the value of symbol SYMNDX in input bfd ABDF, plus ADDEND. */ static bfd_boolean score_elf_record_local_got_symbol (bfd *abfd, long symndx, bfd_vma addend, struct score_got_info *g) { struct score_got_entry entry, **loc; entry.abfd = abfd; entry.symndx = symndx; entry.d.addend = addend; loc = (struct score_got_entry **)htab_find_slot (g->got_entries, &entry, INSERT); if (*loc) return TRUE; entry.gotidx = g->local_gotno++; *loc = bfd_alloc (abfd, sizeof(entry)); if (! *loc) return FALSE; memcpy (*loc, &entry, sizeof (entry)); return TRUE; } /* Returns the GOT offset at which the indicated address can be found. If there is not yet a GOT entry for this value, create one. Returns -1 if no satisfactory GOT offset can be found. */ static bfd_vma score_elf_local_got_index (bfd *abfd, bfd *ibfd, struct bfd_link_info *info, bfd_vma value, unsigned long r_symndx, struct score_elf_link_hash_entry *h, int r_type) { asection *sgot; struct score_got_info *g; struct score_got_entry *entry; g = score_elf_got_info (elf_hash_table (info)->dynobj, &sgot); entry = score_elf_create_local_got_entry (abfd, ibfd, g, sgot, value, r_symndx, h, r_type); if (!entry) return MINUS_ONE; else return entry->gotidx; } /* Returns the GOT index for the global symbol indicated by H. */ static bfd_vma score_elf_global_got_index (bfd *abfd, struct elf_link_hash_entry *h) { bfd_vma got_index; asection *sgot; struct score_got_info *g; long global_got_dynindx = 0; g = score_elf_got_info (abfd, &sgot); if (g->global_gotsym != NULL) global_got_dynindx = g->global_gotsym->dynindx; /* Once we determine the global GOT entry with the lowest dynamic symbol table index, we must put all dynamic symbols with greater indices into the GOT. That makes it easy to calculate the GOT offset. */ BFD_ASSERT (h->dynindx >= global_got_dynindx); got_index = ((h->dynindx - global_got_dynindx + g->local_gotno) * SCORE_ELF_GOT_SIZE (abfd)); BFD_ASSERT (got_index < sgot->size); return got_index; } /* Returns the offset for the entry at the INDEXth position in the GOT. */ static bfd_vma score_elf_got_offset_from_index (bfd *dynobj, bfd *output_bfd, bfd *input_bfd ATTRIBUTE_UNUSED, bfd_vma got_index) { asection *sgot; bfd_vma gp; score_elf_got_info (dynobj, &sgot); gp = _bfd_get_gp_value (output_bfd); return sgot->output_section->vma + sgot->output_offset + got_index - gp; } /* Follow indirect and warning hash entries so that each got entry points to the final symbol definition. P must point to a pointer to the hash table we're traversing. Since this traversal may modify the hash table, we set this pointer to NULL to indicate we've made a potentially-destructive change to the hash table, so the traversal must be restarted. */ static int score_elf_resolve_final_got_entry (void **entryp, void *p) { struct score_got_entry *entry = (struct score_got_entry *)*entryp; htab_t got_entries = *(htab_t *)p; if (entry->abfd != NULL && entry->symndx == -1) { struct score_elf_link_hash_entry *h = entry->d.h; while (h->root.root.type == bfd_link_hash_indirect || h->root.root.type == bfd_link_hash_warning) h = (struct score_elf_link_hash_entry *) h->root.root.u.i.link; if (entry->d.h == h) return 1; entry->d.h = h; /* If we can't find this entry with the new bfd hash, re-insert it, and get the traversal restarted. */ if (! htab_find (got_entries, entry)) { htab_clear_slot (got_entries, entryp); entryp = htab_find_slot (got_entries, entry, INSERT); if (! *entryp) *entryp = entry; /* Abort the traversal, since the whole table may have moved, and leave it up to the parent to restart the process. */ *(htab_t *)p = NULL; return 0; } /* We might want to decrement the global_gotno count, but it's either too early or too late for that at this point. */ } return 1; } /* Turn indirect got entries in a got_entries table into their final locations. */ static void score_elf_resolve_final_got_entries (struct score_got_info *g) { htab_t got_entries; do { got_entries = g->got_entries; htab_traverse (got_entries, score_elf_resolve_final_got_entry, &got_entries); } while (got_entries == NULL); } /* Add INCREMENT to the reloc (of type HOWTO) at ADDRESS. for -r */ static void score_elf_add_to_rel (bfd *abfd, bfd_byte *address, reloc_howto_type *howto, bfd_signed_vma increment) { bfd_signed_vma addend; bfd_vma contents; unsigned long offset; unsigned long r_type = howto->type; unsigned long hi16_addend, hi16_offset, hi16_value, uvalue; contents = score_bfd_get_32 (abfd, address); /* Get the (signed) value from the instruction. */ addend = contents & howto->src_mask; if (addend & ((howto->src_mask + 1) >> 1)) { bfd_signed_vma mask; mask = -1; mask &= ~howto->src_mask; addend |= mask; } /* Add in the increment, (which is a byte value). */ switch (r_type) { case R_SCORE_PC19: offset = (((contents & howto->src_mask) & 0x3ff0000) >> 6) | ((contents & howto->src_mask) & 0x3ff); offset += increment; contents = (contents & ~howto-> src_mask) | (((offset << 6) & howto->src_mask) & 0x3ff0000) | (offset & 0x3ff); score_bfd_put_32 (abfd, contents, address); break; case R_SCORE_HI16: break; case R_SCORE_LO16: hi16_addend = score_bfd_get_32 (abfd, address - 4); hi16_offset = ((((hi16_addend >> 16) & 0x3) << 15) | (hi16_addend & 0x7fff)) >> 1; offset = ((((contents >> 16) & 0x3) << 15) | (contents & 0x7fff)) >> 1; offset = (hi16_offset << 16) | (offset & 0xffff); uvalue = increment + offset; hi16_offset = (uvalue >> 16) << 1; hi16_value = (hi16_addend & (~(howto->dst_mask))) | (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000); score_bfd_put_32 (abfd, hi16_value, address - 4); offset = (uvalue & 0xffff) << 1; contents = (contents & (~(howto->dst_mask))) | (offset & 0x7fff) | ((offset << 1) & 0x30000); score_bfd_put_32 (abfd, contents, address); break; case R_SCORE_24: offset = (((contents & howto->src_mask) >> 1) & 0x1ff8000) | ((contents & howto->src_mask) & 0x7fff); offset += increment; contents = (contents & ~howto-> src_mask) | (((offset << 1) & howto->src_mask) & 0x3ff0000) | (offset & 0x7fff); score_bfd_put_32 (abfd, contents, address); break; case R_SCORE16_11: contents = score_bfd_get_16 (abfd, address); offset = contents & howto->src_mask; offset += increment; contents = (contents & ~howto->src_mask) | (offset & howto->src_mask); score_bfd_put_16 (abfd, contents, address); break; case R_SCORE16_PC8: contents = score_bfd_get_16 (abfd, address); offset = (contents & howto->src_mask) + ((increment >> 1) & 0x1ff); contents = (contents & (~howto->src_mask)) | (offset & howto->src_mask); score_bfd_put_16 (abfd, contents, address); break; case R_SCORE_BCMP: contents = score_bfd_get_32 (abfd, address); offset = (contents & howto->src_mask); offset <<= howto->rightshift; offset += increment; offset >>= howto->rightshift; contents = (contents & (~howto->src_mask)) | (offset & howto->src_mask); score_bfd_put_32 (abfd, contents, address); break; case R_SCORE_IMM30: contents = score_bfd_get_48 (abfd, address); offset = (contents & howto->src_mask); offset <<= howto->rightshift; offset += increment; offset >>= howto->rightshift; contents = (contents & (~howto->src_mask)) | (offset & howto->src_mask); score_bfd_put_48 (abfd, contents, address); break; case R_SCORE_IMM32: contents = score_bfd_get_48 (abfd, address); offset = (contents & howto->src_mask); offset += increment; contents = (contents & (~howto->src_mask)) | (offset & howto->src_mask); score_bfd_put_48 (abfd, contents, address); break; default: addend += increment; contents = (contents & ~howto->dst_mask) | (addend & howto->dst_mask); score_bfd_put_32 (abfd, contents, address); break; } } /* Perform a relocation as part of a final link. */ static bfd_reloc_status_type score_elf_final_link_relocate (reloc_howto_type *howto, bfd *input_bfd, bfd *output_bfd, asection *input_section, bfd_byte *contents, Elf_Internal_Rela *rel, Elf_Internal_Rela *relocs, bfd_vma symbol, struct bfd_link_info *info, const char *sym_name ATTRIBUTE_UNUSED, int sym_flags ATTRIBUTE_UNUSED, struct score_elf_link_hash_entry *h, asection **local_sections, bfd_boolean gp_disp_p) { unsigned long r_type; unsigned long r_symndx; bfd_byte *hit_data = contents + rel->r_offset; bfd_vma addend; /* The final GP value to be used for the relocatable, executable, or shared object file being produced. */ bfd_vma gp = MINUS_ONE; /* The place (section offset or address) of the storage unit being relocated. */ bfd_vma rel_addr; /* The offset into the global offset table at which the address of the relocation entry symbol, adjusted by the addend, resides during execution. */ bfd_vma g = MINUS_ONE; /* TRUE if the symbol referred to by this relocation is a local symbol. */ bfd_boolean local_p; /* The eventual value we will relocate. */ bfd_vma value = symbol; unsigned long hi16_addend, hi16_offset, hi16_value, uvalue, offset, abs_value = 0; if (elf_gp (output_bfd) == 0) { struct bfd_link_hash_entry *bh; asection *o; bh = bfd_link_hash_lookup (info->hash, "_gp", 0, 0, 1); if (bh != NULL && bh->type == bfd_link_hash_defined) elf_gp (output_bfd) = (bh->u.def.value + bh->u.def.section->output_section->vma + bh->u.def.section->output_offset); else if (bfd_link_relocatable (info)) { bfd_vma lo = -1; /* Find the GP-relative section with the lowest offset. */ for (o = output_bfd->sections; o != NULL; o = o->next) if (o->vma < lo) lo = o->vma; /* And calculate GP relative to that. */ elf_gp (output_bfd) = lo + ELF_SCORE_GP_OFFSET (input_bfd); } else { /* If the relocate_section function needs to do a reloc involving the GP value, it should make a reloc_dangerous callback to warn that GP is not defined. */ } } /* Parse the relocation. */ r_symndx = ELF32_R_SYM (rel->r_info); r_type = ELF32_R_TYPE (rel->r_info); rel_addr = (input_section->output_section->vma + input_section->output_offset + rel->r_offset); local_p = score_elf_local_relocation_p (input_bfd, rel, local_sections, TRUE); if (r_type == R_SCORE_GOT15) { const Elf_Internal_Rela *relend; const Elf_Internal_Rela *lo16_rel; const struct elf_backend_data *bed; bfd_vma lo_value = 0; bed = get_elf_backend_data (output_bfd); relend = relocs + input_section->reloc_count * bed->s->int_rels_per_ext_rel; lo16_rel = score_elf_next_relocation (input_bfd, R_SCORE_GOT_LO16, rel, relend); if ((local_p) && (lo16_rel != NULL)) { bfd_vma tmp = 0; tmp = score_bfd_get_32 (input_bfd, contents + lo16_rel->r_offset); lo_value = (((tmp >> 16) & 0x3) << 14) | ((tmp & 0x7fff) >> 1); } addend = lo_value; } /* For score3 R_SCORE_ABS32. */ else if (r_type == R_SCORE_ABS32 || r_type == R_SCORE_REL32) { addend = (bfd_get_32 (input_bfd, hit_data) >> howto->bitpos) & howto->src_mask; } else { addend = (score_bfd_get_32 (input_bfd, hit_data) >> howto->bitpos) & howto->src_mask; } /* If we haven't already determined the GOT offset, or the GP value, and we're going to need it, get it now. */ switch (r_type) { case R_SCORE_CALL15: case R_SCORE_GOT15: if (!local_p) { g = score_elf_global_got_index (elf_hash_table (info)->dynobj, (struct elf_link_hash_entry *) h); if ((! elf_hash_table (info)->dynamic_sections_created || (bfd_link_pic (info) && (info->symbolic || h->root.dynindx == -1) && h->root.def_regular))) { /* This is a static link or a -Bsymbolic link. The symbol is defined locally, or was forced to be local. We must initialize this entry in the GOT. */ bfd *tmpbfd = elf_hash_table (info)->dynobj; asection *sgot = score_elf_got_section (tmpbfd, FALSE); score_bfd_put_32 (tmpbfd, value, sgot->contents + g); } } else if (r_type == R_SCORE_GOT15 || r_type == R_SCORE_CALL15) { /* There's no need to create a local GOT entry here; the calculation for a local GOT15 entry does not involve G. */ ; } else { g = score_elf_local_got_index (output_bfd, input_bfd, info, symbol + addend, r_symndx, h, r_type); if (g == MINUS_ONE) return bfd_reloc_outofrange; } /* Convert GOT indices to actual offsets. */ g = score_elf_got_offset_from_index (elf_hash_table (info)->dynobj, output_bfd, input_bfd, g); break; case R_SCORE_HI16: case R_SCORE_LO16: case R_SCORE_GPREL32: gp = _bfd_get_gp_value (output_bfd); break; case R_SCORE_GP15: gp = _bfd_get_gp_value (output_bfd); default: break; } switch (r_type) { case R_SCORE_NONE: return bfd_reloc_ok; case R_SCORE_ABS32: case R_SCORE_REL32: if ((bfd_link_pic (info) || (elf_hash_table (info)->dynamic_sections_created && h != NULL && h->root.def_dynamic && !h->root.def_regular)) && r_symndx != STN_UNDEF && (input_section->flags & SEC_ALLOC) != 0) { /* If we're creating a shared library, or this relocation is against a symbol in a shared library, then we can't know where the symbol will end up. So, we create a relocation record in the output, and leave the job up to the dynamic linker. */ value = addend; if (!score_elf_create_dynamic_relocation (output_bfd, info, rel, h, symbol, &value, input_section)) return bfd_reloc_undefined; } else if (r_symndx == STN_UNDEF) /* r_symndx will be STN_UNDEF (zero) only for relocs against symbols from removed linkonce sections, or sections discarded by a linker script. */ value = 0; else { if (r_type != R_SCORE_REL32) value = symbol + addend; else value = addend; } value &= howto->dst_mask; bfd_put_32 (input_bfd, value, hit_data); return bfd_reloc_ok; case R_SCORE_ABS16: value += addend; if ((long)value > 0x7fff || (long)value < -0x8000) return bfd_reloc_overflow; score_bfd_put_16 (input_bfd, value, hit_data); return bfd_reloc_ok; case R_SCORE_24: addend = score_bfd_get_32 (input_bfd, hit_data); offset = (((addend & howto->src_mask) >> 1) & 0x1ff8000) | ((addend & howto->src_mask) & 0x7fff); if ((offset & 0x1000000) != 0) offset |= 0xfe000000; value += offset; abs_value = value - rel_addr; if ((abs_value & 0xfe000000) != 0) return bfd_reloc_overflow; addend = (addend & ~howto->src_mask) | (((value << 1) & howto->src_mask) & 0x3ff0000) | (value & 0x7fff); score_bfd_put_32 (input_bfd, addend, hit_data); return bfd_reloc_ok; /* signed imm32. */ case R_SCORE_IMM30: { int not_word_align_p = 0; bfd_vma imm_offset = 0; addend = score_bfd_get_48 (input_bfd, hit_data); imm_offset = ((addend >> 7) & 0xff) | (((addend >> 16) & 0x7fff) << 8) | (((addend >> 32) & 0x7f) << 23); imm_offset <<= howto->rightshift; value += imm_offset; value &= 0xffffffff; /* Check lw48/sw48 rd, value/label word align. */ if ((value & 0x3) != 0) not_word_align_p = 1; value >>= howto->rightshift; addend = (addend & ~howto->src_mask) | (((value & 0xff) >> 0) << 7) | (((value & 0x7fff00) >> 8) << 16) | (((value & 0x3f800000) >> 23) << 32); score_bfd_put_48 (input_bfd, addend, hit_data); if (not_word_align_p) return bfd_reloc_other; else return bfd_reloc_ok; } case R_SCORE_IMM32: { bfd_vma imm_offset = 0; addend = score_bfd_get_48 (input_bfd, hit_data); imm_offset = ((addend >> 5) & 0x3ff) | (((addend >> 16) & 0x7fff) << 10) | (((addend >> 32) & 0x7f) << 25); value += imm_offset; value &= 0xffffffff; addend = (addend & ~howto->src_mask) | ((value & 0x3ff) << 5) | (((value >> 10) & 0x7fff) << 16) | (((value >> 25) & 0x7f) << 32); score_bfd_put_48 (input_bfd, addend, hit_data); return bfd_reloc_ok; } case R_SCORE_PC19: addend = score_bfd_get_32 (input_bfd, hit_data); offset = (((addend & howto->src_mask) & 0x3ff0000) >> 6) | ((addend & howto->src_mask) & 0x3ff); if ((offset & 0x80000) != 0) offset |= 0xfff00000; abs_value = value = value - rel_addr + offset; /* exceed 20 bit : overflow. */ if ((abs_value & 0x80000000) == 0x80000000) abs_value = 0xffffffff - value + 1; if ((abs_value & 0xfff80000) != 0) return bfd_reloc_overflow; addend = (addend & ~howto->src_mask) | (((value << 6) & howto->src_mask) & 0x3ff0000) | (value & 0x3ff); score_bfd_put_32 (input_bfd, addend, hit_data); return bfd_reloc_ok; case R_SCORE16_11: addend = score_bfd_get_16 (input_bfd, hit_data); offset = addend & howto->src_mask; if ((offset & 0x800) != 0) /* Offset is negative. */ offset |= 0xfffff000; value += offset; abs_value = value - rel_addr; if ((abs_value & 0xfffff000) != 0) return bfd_reloc_overflow; addend = (addend & ~howto->src_mask) | (value & howto->src_mask); score_bfd_put_16 (input_bfd, addend, hit_data); return bfd_reloc_ok; case R_SCORE16_PC8: addend = score_bfd_get_16 (input_bfd, hit_data); offset = (addend & howto->src_mask) << 1; if ((offset & 0x200) != 0) /* Offset is negative. */ offset |= 0xfffffe00; abs_value = value = value - rel_addr + offset; /* Sign bit + exceed 9 bit. */ if (((value & 0xfffffe00) != 0) && ((value & 0xfffffe00) != 0xfffffe00)) return bfd_reloc_overflow; value >>= 1; addend = (addend & ~howto->src_mask) | (value & howto->src_mask); score_bfd_put_16 (input_bfd, addend, hit_data); return bfd_reloc_ok; case R_SCORE_BCMP: addend = score_bfd_get_32 (input_bfd, hit_data); offset = (addend & howto->src_mask) << howto->rightshift; if ((offset & 0x200) != 0) /* Offset is negative. */ offset |= 0xfffffe00; value = value - rel_addr + offset; /* Sign bit + exceed 9 bit. */ if (((value & 0xfffffe00) != 0) && ((value & 0xfffffe00) != 0xfffffe00)) return bfd_reloc_overflow; value >>= howto->rightshift; addend = (addend & ~howto->src_mask) | (value & 0x1) | (((value >> 1) & 0x7) << 7) | (((value >> 4) & 0x1f) << 21); score_bfd_put_32 (input_bfd, addend, hit_data); return bfd_reloc_ok; case R_SCORE_HI16: return bfd_reloc_ok; case R_SCORE_LO16: hi16_addend = score_bfd_get_32 (input_bfd, hit_data - 4); hi16_offset = ((((hi16_addend >> 16) & 0x3) << 15) | (hi16_addend & 0x7fff)) >> 1; addend = score_bfd_get_32 (input_bfd, hit_data); offset = ((((addend >> 16) & 0x3) << 15) | (addend & 0x7fff)) >> 1; offset = (hi16_offset << 16) | (offset & 0xffff); if (!gp_disp_p) uvalue = value + offset; else uvalue = offset + gp - rel_addr + 4; hi16_offset = (uvalue >> 16) << 1; hi16_value = (hi16_addend & (~(howto->dst_mask))) | (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000); score_bfd_put_32 (input_bfd, hi16_value, hit_data - 4); offset = (uvalue & 0xffff) << 1; value = (addend & (~(howto->dst_mask))) | (offset & 0x7fff) | ((offset << 1) & 0x30000); score_bfd_put_32 (input_bfd, value, hit_data); return bfd_reloc_ok; case R_SCORE_GP15: addend = score_bfd_get_32 (input_bfd, hit_data); offset = addend & 0x7fff; if ((offset & 0x4000) == 0x4000) offset |= 0xffffc000; value = value + offset - gp; if (((value & 0xffffc000) != 0) && ((value & 0xffffc000) != 0xffffc000)) return bfd_reloc_overflow; value = (addend & ~howto->src_mask) | (value & howto->src_mask); score_bfd_put_32 (input_bfd, value, hit_data); return bfd_reloc_ok; case R_SCORE_GOT15: case R_SCORE_CALL15: if (local_p) { bfd_boolean forced; /* The special case is when the symbol is forced to be local. We need the full address in the GOT since no R_SCORE_GOT_LO16 relocation follows. */ forced = ! score_elf_local_relocation_p (input_bfd, rel, local_sections, FALSE); value = score_elf_got16_entry (output_bfd, input_bfd, info, symbol + addend, forced); if (value == MINUS_ONE) return bfd_reloc_outofrange; value = score_elf_got_offset_from_index (elf_hash_table (info)->dynobj, output_bfd, input_bfd, value); } else { value = g; } if ((long) value > 0x3fff || (long) value < -0x4000) return bfd_reloc_overflow; addend = score_bfd_get_32 (input_bfd, hit_data); value = (addend & ~howto->dst_mask) | (value & howto->dst_mask); score_bfd_put_32 (input_bfd, value, hit_data); return bfd_reloc_ok; case R_SCORE_GPREL32: value = (addend + symbol - gp); value &= howto->dst_mask; score_bfd_put_32 (input_bfd, value, hit_data); return bfd_reloc_ok; case R_SCORE_GOT_LO16: addend = score_bfd_get_32 (input_bfd, hit_data); value = (((addend >> 16) & 0x3) << 14) | ((addend & 0x7fff) >> 1); value += symbol; value = (addend & (~(howto->dst_mask))) | ((value & 0x3fff) << 1) | (((value >> 14) & 0x3) << 16); score_bfd_put_32 (input_bfd, value, hit_data); return bfd_reloc_ok; case R_SCORE_DUMMY_HI16: return bfd_reloc_ok; case R_SCORE_GNU_VTINHERIT: case R_SCORE_GNU_VTENTRY: /* We don't do anything with these at present. */ return bfd_reloc_continue; default: return bfd_reloc_notsupported; } } /* Score backend functions. */ static void s3_bfd_score_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED, arelent *bfd_reloc, Elf_Internal_Rela *elf_reloc) { unsigned int r_type; r_type = ELF32_R_TYPE (elf_reloc->r_info); if (r_type >= ARRAY_SIZE (elf32_score_howto_table)) bfd_reloc->howto = NULL; else bfd_reloc->howto = &elf32_score_howto_table[r_type]; } /* Relocate an score ELF section. */ static bfd_boolean s3_bfd_score_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info, bfd *input_bfd, asection *input_section, bfd_byte *contents, Elf_Internal_Rela *relocs, Elf_Internal_Sym *local_syms, asection **local_sections) { Elf_Internal_Shdr *symtab_hdr; Elf_Internal_Rela *rel; Elf_Internal_Rela *relend; const char *name; unsigned long offset; unsigned long hi16_addend, hi16_offset, hi16_value, uvalue; size_t extsymoff; bfd_boolean gp_disp_p = FALSE; /* Sort dynsym. */ if (elf_hash_table (info)->dynamic_sections_created) { bfd_size_type dynsecsymcount = 0; if (bfd_link_pic (info)) { asection * p; const struct elf_backend_data *bed = get_elf_backend_data (output_bfd); for (p = output_bfd->sections; p ; p = p->next) if ((p->flags & SEC_EXCLUDE) == 0 && (p->flags & SEC_ALLOC) != 0 && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p)) ++ dynsecsymcount; } if (!score_elf_sort_hash_table (info, dynsecsymcount + 1)) return FALSE; } symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr; extsymoff = (elf_bad_symtab (input_bfd)) ? 0 : symtab_hdr->sh_info; rel = relocs; relend = relocs + input_section->reloc_count; for (; rel < relend; rel++) { int r_type; reloc_howto_type *howto; unsigned long r_symndx; Elf_Internal_Sym *sym; asection *sec; struct score_elf_link_hash_entry *h; bfd_vma relocation = 0; bfd_reloc_status_type r; arelent bfd_reloc; r_symndx = ELF32_R_SYM (rel->r_info); r_type = ELF32_R_TYPE (rel->r_info); s3_bfd_score_info_to_howto (input_bfd, &bfd_reloc, (Elf_Internal_Rela *) rel); howto = bfd_reloc.howto; h = NULL; sym = NULL; sec = NULL; if (r_symndx < extsymoff) { sym = local_syms + r_symndx; sec = local_sections[r_symndx]; relocation = (sec->output_section->vma + sec->output_offset + sym->st_value); name = bfd_elf_sym_name (input_bfd, symtab_hdr, sym, sec); if (!bfd_link_relocatable (info) && (sec->flags & SEC_MERGE) && ELF_ST_TYPE (sym->st_info) == STT_SECTION) { asection *msec; bfd_vma addend, value; switch (r_type) { case R_SCORE_HI16: break; case R_SCORE_LO16: hi16_addend = score_bfd_get_32 (input_bfd, contents + rel->r_offset - 4); hi16_offset = ((((hi16_addend >> 16) & 0x3) << 15) | (hi16_addend & 0x7fff)) >> 1; value = score_bfd_get_32 (input_bfd, contents + rel->r_offset); offset = ((((value >> 16) & 0x3) << 15) | (value & 0x7fff)) >> 1; addend = (hi16_offset << 16) | (offset & 0xffff); msec = sec; addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend); addend -= relocation; addend += msec->output_section->vma + msec->output_offset; uvalue = addend; hi16_offset = (uvalue >> 16) << 1; hi16_value = (hi16_addend & (~(howto->dst_mask))) | (hi16_offset & 0x7fff) | ((hi16_offset << 1) & 0x30000); score_bfd_put_32 (input_bfd, hi16_value, contents + rel->r_offset - 4); offset = (uvalue & 0xffff) << 1; value = (value & (~(howto->dst_mask))) | (offset & 0x7fff) | ((offset << 1) & 0x30000); score_bfd_put_32 (input_bfd, value, contents + rel->r_offset); break; case R_SCORE_IMM32: { value = score_bfd_get_48 (input_bfd, contents + rel->r_offset); addend = ((value >> 5) & 0x3ff) | (((value >> 16) & 0x7fff) << 10) | (((value >> 32) & 0x7f) << 25); msec = sec; addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend); addend -= relocation; addend += msec->output_section->vma + msec->output_offset; addend &= 0xffffffff; value = (value & ~howto->src_mask) | ((addend & 0x3ff) << 5) | (((addend >> 10) & 0x7fff) << 16) | (((addend >> 25) & 0x7f) << 32); score_bfd_put_48 (input_bfd, value, contents + rel->r_offset); break; } case R_SCORE_IMM30: { int not_word_align_p = 0; value = score_bfd_get_48 (input_bfd, contents + rel->r_offset); addend = ((value >> 7) & 0xff) | (((value >> 16) & 0x7fff) << 8) | (((value >> 32) & 0x7f) << 23); addend <<= howto->rightshift; msec = sec; addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend); addend -= relocation; addend += msec->output_section->vma + msec->output_offset; addend &= 0xffffffff; /* Check lw48/sw48 rd, value/label word align. */ if ((addend & 0x3) != 0) not_word_align_p = 1; addend >>= howto->rightshift; value = (value & ~howto->src_mask) | (((addend & 0xff) >> 0) << 7) | (((addend & 0x7fff00) >> 8) << 16) | (((addend & 0x3f800000) >> 23) << 32); score_bfd_put_48 (input_bfd, value, contents + rel->r_offset); if (not_word_align_p) return bfd_reloc_other; else break; } case R_SCORE_GOT_LO16: value = score_bfd_get_32 (input_bfd, contents + rel->r_offset); addend = (((value >> 16) & 0x3) << 14) | ((value & 0x7fff) >> 1); msec = sec; addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend) - relocation; addend += msec->output_section->vma + msec->output_offset; value = (value & (~(howto->dst_mask))) | ((addend & 0x3fff) << 1) | (((addend >> 14) & 0x3) << 16); score_bfd_put_32 (input_bfd, value, contents + rel->r_offset); break; case R_SCORE_ABS32: case R_SCORE_REL32: value = bfd_get_32 (input_bfd, contents + rel->r_offset); /* Get the (signed) value from the instruction. */ addend = value & howto->src_mask; if (addend & ((howto->src_mask + 1) >> 1)) { bfd_signed_vma mask; mask = -1; mask &= ~howto->src_mask; addend |= mask; } msec = sec; addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend) - relocation; addend += msec->output_section->vma + msec->output_offset; value = (value & ~howto->dst_mask) | (addend & howto->dst_mask); bfd_put_32 (input_bfd, value, contents + rel->r_offset); break; default: value = score_bfd_get_32 (input_bfd, contents + rel->r_offset); /* Get the (signed) value from the instruction. */ addend = value & howto->src_mask; if (addend & ((howto->src_mask + 1) >> 1)) { bfd_signed_vma mask; mask = -1; mask &= ~howto->src_mask; addend |= mask; } msec = sec; addend = _bfd_elf_rel_local_sym (output_bfd, sym, &msec, addend) - relocation; addend += msec->output_section->vma + msec->output_offset; value = (value & ~howto->dst_mask) | (addend & howto->dst_mask); score_bfd_put_32 (input_bfd, value, contents + rel->r_offset); break; } } } else { /* For global symbols we look up the symbol in the hash-table. */ h = ((struct score_elf_link_hash_entry *) elf_sym_hashes (input_bfd) [r_symndx - extsymoff]); if (info->wrap_hash != NULL && (input_section->flags & SEC_DEBUGGING) != 0) h = ((struct score_elf_link_hash_entry *) unwrap_hash_lookup (info, input_bfd, &h->root.root)); /* Find the real hash-table entry for this symbol. */ while (h->root.root.type == bfd_link_hash_indirect || h->root.root.type == bfd_link_hash_warning) h = (struct score_elf_link_hash_entry *) h->root.root.u.i.link; /* Record the name of this symbol, for our caller. */ name = h->root.root.root.string; /* See if this is the special GP_DISP_LABEL symbol. Note that such a symbol must always be a global symbol. */ if (strcmp (name, GP_DISP_LABEL) == 0) { /* Relocations against GP_DISP_LABEL are permitted only with R_SCORE_HI16 and R_SCORE_LO16 relocations. */ if (r_type != R_SCORE_HI16 && r_type != R_SCORE_LO16) return bfd_reloc_notsupported; gp_disp_p = TRUE; } /* If this symbol is defined, calculate its address. Note that GP_DISP_LABEL is a magic symbol, always implicitly defined by the linker, so it's inappropriate to check to see whether or not its defined. */ else if ((h->root.root.type == bfd_link_hash_defined || h->root.root.type == bfd_link_hash_defweak) && h->root.root.u.def.section) { sec = h->root.root.u.def.section; if (sec->output_section) relocation = (h->root.root.u.def.value + sec->output_section->vma + sec->output_offset); else { relocation = h->root.root.u.def.value; } } else if (h->root.root.type == bfd_link_hash_undefweak) /* We allow relocations against undefined weak symbols, giving it the value zero, so that you can undefined weak functions and check to see if they exist by looking at their addresses. */ relocation = 0; else if (info->unresolved_syms_in_objects == RM_IGNORE && ELF_ST_VISIBILITY (h->root.other) == STV_DEFAULT) relocation = 0; else if (strcmp (name, "_DYNAMIC_LINK") == 0) { /* If this is a dynamic link, we should have created a _DYNAMIC_LINK symbol in s3_bfd_score_elf_create_dynamic_sections. Otherwise, we should define the symbol with a value of 0. */ BFD_ASSERT (! bfd_link_pic (info)); BFD_ASSERT (bfd_get_section_by_name (output_bfd, ".dynamic") == NULL); relocation = 0; } else if (!bfd_link_relocatable (info)) { (*info->callbacks->undefined_symbol) (info, h->root.root.root.string, input_bfd, input_section, rel->r_offset, (info->unresolved_syms_in_objects == RM_GENERATE_ERROR) || ELF_ST_VISIBILITY (h->root.other)); relocation = 0; } } if (sec != NULL && discarded_section (sec)) RELOC_AGAINST_DISCARDED_SECTION (info, input_bfd, input_section, rel, 1, relend, howto, 0, contents); if (bfd_link_relocatable (info)) { /* This is a relocatable link. We don't have to change anything, unless the reloc is against a section symbol, in which case we have to adjust according to where the section symbol winds up in the output section. */ if (r_symndx < symtab_hdr->sh_info) { sym = local_syms + r_symndx; if (ELF_ST_TYPE (sym->st_info) == STT_SECTION) { sec = local_sections[r_symndx]; score_elf_add_to_rel (input_bfd, contents + rel->r_offset, howto, (bfd_signed_vma) (sec->output_offset + sym->st_value)); } } continue; } /* This is a final link. */ r = score_elf_final_link_relocate (howto, input_bfd, output_bfd, input_section, contents, rel, relocs, relocation, info, name, (h ? ELF_ST_TYPE ((unsigned int)h->root.root.type) : ELF_ST_TYPE ((unsigned int)sym->st_info)), h, local_sections, gp_disp_p); if (r != bfd_reloc_ok) { const char *msg = (const char *)0; switch (r) { case bfd_reloc_overflow: /* If the overflowing reloc was to an undefined symbol, we have already printed one error message and there is no point complaining again. */ if (!h || h->root.root.type != bfd_link_hash_undefined) (*info->callbacks->reloc_overflow) (info, NULL, name, howto->name, (bfd_vma) 0, input_bfd, input_section, rel->r_offset); break; case bfd_reloc_undefined: (*info->callbacks->undefined_symbol) (info, name, input_bfd, input_section, rel->r_offset, TRUE); break; case bfd_reloc_outofrange: msg = _("internal error: out of range error"); goto common_error; case bfd_reloc_notsupported: msg = _("internal error: unsupported relocation error"); goto common_error; case bfd_reloc_dangerous: msg = _("internal error: dangerous error"); goto common_error; /* Use bfd_reloc_other to check lw48, sw48 word align. */ case bfd_reloc_other: msg = _("address not word align"); goto common_error; default: msg = _("internal error: unknown error"); /* Fall through. */ common_error: (*info->callbacks->warning) (info, msg, name, input_bfd, input_section, rel->r_offset); break; } } } return TRUE; } /* Look through the relocs for a section during the first phase, and allocate space in the global offset table. */ static bfd_boolean s3_bfd_score_elf_check_relocs (bfd *abfd, struct bfd_link_info *info, asection *sec, const Elf_Internal_Rela *relocs) { bfd *dynobj; Elf_Internal_Shdr *symtab_hdr; struct elf_link_hash_entry **sym_hashes; struct score_got_info *g; size_t extsymoff; const Elf_Internal_Rela *rel; const Elf_Internal_Rela *rel_end; asection *sgot; asection *sreloc; const struct elf_backend_data *bed; if (bfd_link_relocatable (info)) return TRUE; dynobj = elf_hash_table (info)->dynobj; symtab_hdr = &elf_tdata (abfd)->symtab_hdr; sym_hashes = elf_sym_hashes (abfd); extsymoff = (elf_bad_symtab (abfd)) ? 0 : symtab_hdr->sh_info; if (dynobj == NULL) { sgot = NULL; g = NULL; } else { sgot = score_elf_got_section (dynobj, FALSE); if (sgot == NULL) g = NULL; else { BFD_ASSERT (score_elf_section_data (sgot) != NULL); g = score_elf_section_data (sgot)->u.got_info; BFD_ASSERT (g != NULL); } } sreloc = NULL; bed = get_elf_backend_data (abfd); rel_end = relocs + sec->reloc_count * bed->s->int_rels_per_ext_rel; for (rel = relocs; rel < rel_end; ++rel) { unsigned long r_symndx; unsigned int r_type; struct elf_link_hash_entry *h; r_symndx = ELF32_R_SYM (rel->r_info); r_type = ELF32_R_TYPE (rel->r_info); if (r_symndx < extsymoff) { h = NULL; } else if (r_symndx >= extsymoff + NUM_SHDR_ENTRIES (symtab_hdr)) { _bfd_error_handler /* xgettext:c-format */ (_("%B: Malformed reloc detected for section %A"), abfd, sec); bfd_set_error (bfd_error_bad_value); return FALSE; } else { h = sym_hashes[r_symndx - extsymoff]; /* This may be an indirect symbol created because of a version. */ if (h != NULL) { while (h->root.type == bfd_link_hash_indirect) h = (struct elf_link_hash_entry *)h->root.u.i.link; /* PR15323, ref flags aren't set for references in the same object. */ h->root.non_ir_ref = 1; } } /* Some relocs require a global offset table. */ if (dynobj == NULL || sgot == NULL) { switch (r_type) { case R_SCORE_GOT15: case R_SCORE_CALL15: if (dynobj == NULL) elf_hash_table (info)->dynobj = dynobj = abfd; if (!score_elf_create_got_section (dynobj, info, FALSE)) return FALSE; g = score_elf_got_info (dynobj, &sgot); break; case R_SCORE_ABS32: case R_SCORE_REL32: if (dynobj == NULL && (bfd_link_pic (info) || h != NULL) && (sec->flags & SEC_ALLOC) != 0) elf_hash_table (info)->dynobj = dynobj = abfd; break; default: break; } } if (!h && (r_type == R_SCORE_GOT_LO16)) { if (! score_elf_record_local_got_symbol (abfd, r_symndx, rel->r_addend, g)) return FALSE; } switch (r_type) { case R_SCORE_CALL15: if (h == NULL) { _bfd_error_handler /* xgettext:c-format */ (_("%B: CALL15 reloc at 0x%lx not against global symbol"), abfd, (unsigned long) rel->r_offset); bfd_set_error (bfd_error_bad_value); return FALSE; } else { /* This symbol requires a global offset table entry. */ if (! score_elf_record_global_got_symbol (h, abfd, info, g)) return FALSE; /* We need a stub, not a plt entry for the undefined function. But we record it as if it needs plt. See _bfd_elf_adjust_dynamic_symbol. */ h->needs_plt = 1; h->type = STT_FUNC; } break; case R_SCORE_GOT15: if (h && ! score_elf_record_global_got_symbol (h, abfd, info, g)) return FALSE; break; case R_SCORE_ABS32: case R_SCORE_REL32: if ((bfd_link_pic (info) || h != NULL) && (sec->flags & SEC_ALLOC) != 0) { if (sreloc == NULL) { sreloc = score_elf_rel_dyn_section (dynobj, TRUE); if (sreloc == NULL) return FALSE; } #define SCORE_READONLY_SECTION (SEC_ALLOC | SEC_LOAD | SEC_READONLY) if (bfd_link_pic (info)) { /* When creating a shared object, we must copy these reloc types into the output file as R_SCORE_REL32 relocs. We make room for this reloc in the .rel.dyn reloc section. */ score_elf_allocate_dynamic_relocations (dynobj, 1); if ((sec->flags & SCORE_READONLY_SECTION) == SCORE_READONLY_SECTION) /* We tell the dynamic linker that there are relocations against the text segment. */ info->flags |= DF_TEXTREL; } else { struct score_elf_link_hash_entry *hscore; /* We only need to copy this reloc if the symbol is defined in a dynamic object. */ hscore = (struct score_elf_link_hash_entry *)h; ++hscore->possibly_dynamic_relocs; if ((sec->flags & SCORE_READONLY_SECTION) == SCORE_READONLY_SECTION) /* We need it to tell the dynamic linker if there are relocations against the text segment. */ hscore->readonly_reloc = TRUE; } /* Even though we don't directly need a GOT entry for this symbol, a symbol must have a dynamic symbol table index greater that DT_SCORE_GOTSYM if there are dynamic relocations against it. */ if (h != NULL) { if (dynobj == NULL) elf_hash_table (info)->dynobj = dynobj = abfd; if (! score_elf_create_got_section (dynobj, info, TRUE)) return FALSE; g = score_elf_got_info (dynobj, &sgot); if (! score_elf_record_global_got_symbol (h, abfd, info, g)) return FALSE; } } break; /* This relocation describes the C++ object vtable hierarchy. Reconstruct it for later use during GC. */ case R_SCORE_GNU_VTINHERIT: if (!bfd_elf_gc_record_vtinherit (abfd, sec, h, rel->r_offset)) return FALSE; break; /* This relocation describes which C++ vtable entries are actually used. Record for later use during GC. */ case R_SCORE_GNU_VTENTRY: if (!bfd_elf_gc_record_vtentry (abfd, sec, h, rel->r_offset)) return FALSE; break; default: break; } /* We must not create a stub for a symbol that has relocations related to taking the function's address. */ switch (r_type) { default: if (h != NULL) { struct score_elf_link_hash_entry *sh; sh = (struct score_elf_link_hash_entry *) h; sh->no_fn_stub = TRUE; } break; case R_SCORE_CALL15: break; } } return TRUE; } static bfd_boolean s3_bfd_score_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym, const char **namep ATTRIBUTE_UNUSED, flagword *flagsp ATTRIBUTE_UNUSED, asection **secp, bfd_vma *valp) { switch (sym->st_shndx) { case SHN_COMMON: if (sym->st_size > elf_gp_size (abfd)) break; /* Fall through. */ case SHN_SCORE_SCOMMON: *secp = bfd_make_section_old_way (abfd, ".scommon"); (*secp)->flags |= SEC_IS_COMMON; *valp = sym->st_size; break; } return TRUE; } static void s3_bfd_score_elf_symbol_processing (bfd *abfd, asymbol *asym) { elf_symbol_type *elfsym; elfsym = (elf_symbol_type *) asym; switch (elfsym->internal_elf_sym.st_shndx) { case SHN_COMMON: if (asym->value > elf_gp_size (abfd)) break; /* Fall through. */ case SHN_SCORE_SCOMMON: if (score_elf_scom_section.name == NULL) { /* Initialize the small common section. */ score_elf_scom_section.name = ".scommon"; score_elf_scom_section.flags = SEC_IS_COMMON; score_elf_scom_section.output_section = &score_elf_scom_section; score_elf_scom_section.symbol = &score_elf_scom_symbol; score_elf_scom_section.symbol_ptr_ptr = &score_elf_scom_symbol_ptr; score_elf_scom_symbol.name = ".scommon"; score_elf_scom_symbol.flags = BSF_SECTION_SYM; score_elf_scom_symbol.section = &score_elf_scom_section; score_elf_scom_symbol_ptr = &score_elf_scom_symbol; } asym->section = &score_elf_scom_section; asym->value = elfsym->internal_elf_sym.st_size; break; } } static int s3_bfd_score_elf_link_output_symbol_hook (struct bfd_link_info *info ATTRIBUTE_UNUSED, const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym, asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED) { /* If we see a common symbol, which implies a relocatable link, then if a symbol was small common in an input file, mark it as small common in the output file. */ if (sym->st_shndx == SHN_COMMON && strcmp (input_sec->name, ".scommon") == 0) sym->st_shndx = SHN_SCORE_SCOMMON; return 1; } static bfd_boolean s3_bfd_score_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, int *retval) { if (strcmp (bfd_get_section_name (abfd, sec), ".scommon") == 0) { *retval = SHN_SCORE_SCOMMON; return TRUE; } return FALSE; } /* Adjust a symbol defined by a dynamic object and referenced by a regular object. The current definition is in some section of the dynamic object, but we're not including those sections. We have to change the definition to something the rest of the link can understand. */ static bfd_boolean s3_bfd_score_elf_adjust_dynamic_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h) { bfd *dynobj; struct score_elf_link_hash_entry *hscore; asection *s; dynobj = elf_hash_table (info)->dynobj; /* Make sure we know what is going on here. */ BFD_ASSERT (dynobj != NULL && (h->needs_plt || h->u.weakdef != NULL || (h->def_dynamic && h->ref_regular && !h->def_regular))); /* If this symbol is defined in a dynamic object, we need to copy any R_SCORE_ABS32 or R_SCORE_REL32 relocs against it into the output file. */ hscore = (struct score_elf_link_hash_entry *)h; if (!bfd_link_relocatable (info) && hscore->possibly_dynamic_relocs != 0 && (h->root.type == bfd_link_hash_defweak || !h->def_regular)) { score_elf_allocate_dynamic_relocations (dynobj, hscore->possibly_dynamic_relocs); if (hscore->readonly_reloc) /* We tell the dynamic linker that there are relocations against the text segment. */ info->flags |= DF_TEXTREL; } /* For a function, create a stub, if allowed. */ if (!hscore->no_fn_stub && h->needs_plt) { if (!elf_hash_table (info)->dynamic_sections_created) return TRUE; /* If this symbol is not defined in a regular file, then set the symbol to the stub location. This is required to make function pointers compare as equal between the normal executable and the shared library. */ if (!h->def_regular) { /* We need .stub section. */ s = bfd_get_linker_section (dynobj, SCORE_ELF_STUB_SECTION_NAME); BFD_ASSERT (s != NULL); h->root.u.def.section = s; h->root.u.def.value = s->size; /* XXX Write this stub address somewhere. */ h->plt.offset = s->size; /* Make room for this stub code. */ s->size += SCORE_FUNCTION_STUB_SIZE; /* The last half word of the stub will be filled with the index of this symbol in .dynsym section. */ return TRUE; } } else if ((h->type == STT_FUNC) && !h->needs_plt) { /* This will set the entry for this symbol in the GOT to 0, and the dynamic linker will take care of this. */ h->root.u.def.value = 0; return TRUE; } /* If this is a weak symbol, and there is a real definition, the processor independent code will have arranged for us to see the real definition first, and we can just use the same value. */ if (h->u.weakdef != NULL) { BFD_ASSERT (h->u.weakdef->root.type == bfd_link_hash_defined || h->u.weakdef->root.type == bfd_link_hash_defweak); h->root.u.def.section = h->u.weakdef->root.u.def.section; h->root.u.def.value = h->u.weakdef->root.u.def.value; return TRUE; } /* This is a reference to a symbol defined by a dynamic object which is not a function. */ return TRUE; } /* This function is called after all the input files have been read, and the input sections have been assigned to output sections. */ static bfd_boolean s3_bfd_score_elf_always_size_sections (bfd *output_bfd, struct bfd_link_info *info) { bfd *dynobj; asection *s; struct score_got_info *g; int i; bfd_size_type loadable_size = 0; bfd_size_type local_gotno; bfd *sub; dynobj = elf_hash_table (info)->dynobj; if (dynobj == NULL) /* Relocatable links don't have it. */ return TRUE; g = score_elf_got_info (dynobj, &s); if (s == NULL) return TRUE; /* Calculate the total loadable size of the output. That will give us the maximum number of GOT_PAGE entries required. */ for (sub = info->input_bfds; sub; sub = sub->link.next) { asection *subsection; for (subsection = sub->sections; subsection; subsection = subsection->next) { if ((subsection->flags & SEC_ALLOC) == 0) continue; loadable_size += ((subsection->size + 0xf) &~ (bfd_size_type) 0xf); } } /* There has to be a global GOT entry for every symbol with a dynamic symbol table index of DT_SCORE_GOTSYM or higher. Therefore, it make sense to put those symbols that need GOT entries at the end of the symbol table. We do that here. */ if (! score_elf_sort_hash_table (info, 1)) return FALSE; if (g->global_gotsym != NULL) i = elf_hash_table (info)->dynsymcount - g->global_gotsym->dynindx; else /* If there are no global symbols, or none requiring relocations, then GLOBAL_GOTSYM will be NULL. */ i = 0; /* In the worst case, we'll get one stub per dynamic symbol. */ loadable_size += SCORE_FUNCTION_STUB_SIZE * i; /* Assume there are two loadable segments consisting of contiguous sections. Is 5 enough? */ local_gotno = (loadable_size >> 16) + 5; g->local_gotno += local_gotno; s->size += g->local_gotno * SCORE_ELF_GOT_SIZE (output_bfd); g->global_gotno = i; s->size += i * SCORE_ELF_GOT_SIZE (output_bfd); score_elf_resolve_final_got_entries (g); if (s->size > SCORE_ELF_GOT_MAX_SIZE (output_bfd)) { /* Fixme. Error message or Warning message should be issued here. */ } return TRUE; } /* Set the sizes of the dynamic sections. */ static bfd_boolean s3_bfd_score_elf_size_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info) { bfd *dynobj; asection *s; bfd_boolean reltext; dynobj = elf_hash_table (info)->dynobj; BFD_ASSERT (dynobj != NULL); if (elf_hash_table (info)->dynamic_sections_created) { /* Set the contents of the .interp section to the interpreter. */ if (!bfd_link_pic (info) && !info->nointerp) { s = bfd_get_linker_section (dynobj, ".interp"); BFD_ASSERT (s != NULL); s->size = strlen (ELF_DYNAMIC_INTERPRETER) + 1; s->contents = (bfd_byte *) ELF_DYNAMIC_INTERPRETER; } } /* The check_relocs and adjust_dynamic_symbol entry points have determined the sizes of the various dynamic sections. Allocate memory for them. */ reltext = FALSE; for (s = dynobj->sections; s != NULL; s = s->next) { const char *name; if ((s->flags & SEC_LINKER_CREATED) == 0) continue; /* It's OK to base decisions on the section name, because none of the dynobj section names depend upon the input files. */ name = bfd_get_section_name (dynobj, s); if (CONST_STRNEQ (name, ".rel")) { if (s->size == 0) { /* We only strip the section if the output section name has the same name. Otherwise, there might be several input sections for this output section. FIXME: This code is probably not needed these days anyhow, since the linker now does not create empty output sections. */ if (s->output_section != NULL && strcmp (name, bfd_get_section_name (s->output_section->owner, s->output_section)) == 0) s->flags |= SEC_EXCLUDE; } else { const char *outname; asection *target; /* If this relocation section applies to a read only section, then we probably need a DT_TEXTREL entry. If the relocation section is .rel.dyn, we always assert a DT_TEXTREL entry rather than testing whether there exists a relocation to a read only section or not. */ outname = bfd_get_section_name (output_bfd, s->output_section); target = bfd_get_section_by_name (output_bfd, outname + 4); if ((target != NULL && (target->flags & SEC_READONLY) != 0 && (target->flags & SEC_ALLOC) != 0) || strcmp (outname, ".rel.dyn") == 0) reltext = TRUE; /* We use the reloc_count field as a counter if we need to copy relocs into the output file. */ if (strcmp (name, ".rel.dyn") != 0) s->reloc_count = 0; } } else if (CONST_STRNEQ (name, ".got")) { /* s3_bfd_score_elf_always_size_sections() has already done most of the work, but some symbols may have been mapped to versions that we must now resolve in the got_entries hash tables. */ } else if (strcmp (name, SCORE_ELF_STUB_SECTION_NAME) == 0) { /* IRIX rld assumes that the function stub isn't at the end of .text section. So put a dummy. XXX */ s->size += SCORE_FUNCTION_STUB_SIZE; } else if (! CONST_STRNEQ (name, ".init")) { /* It's not one of our sections, so don't allocate space. */ continue; } /* Allocate memory for the section contents. */ s->contents = bfd_zalloc (dynobj, s->size); if (s->contents == NULL && s->size != 0) { bfd_set_error (bfd_error_no_memory); return FALSE; } } if (elf_hash_table (info)->dynamic_sections_created) { /* Add some entries to the .dynamic section. We fill in the values later, in s3_bfd_score_elf_finish_dynamic_sections, but we must add the entries now so that we get the correct size for the .dynamic section. The DT_DEBUG entry is filled in by the dynamic linker and used by the debugger. */ if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_DEBUG, 0)) return FALSE; if (reltext) info->flags |= DF_TEXTREL; if ((info->flags & DF_TEXTREL) != 0) { if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_TEXTREL, 0)) return FALSE; } if (! SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_PLTGOT, 0)) return FALSE; if (score_elf_rel_dyn_section (dynobj, FALSE)) { if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_REL, 0)) return FALSE; if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELSZ, 0)) return FALSE; if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_RELENT, 0)) return FALSE; } if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_BASE_ADDRESS, 0)) return FALSE; if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_LOCAL_GOTNO, 0)) return FALSE; if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_SYMTABNO, 0)) return FALSE; if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_UNREFEXTNO, 0)) return FALSE; if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_GOTSYM, 0)) return FALSE; if (!SCORE_ELF_ADD_DYNAMIC_ENTRY (info, DT_SCORE_HIPAGENO, 0)) return FALSE; } return TRUE; } static bfd_boolean s3_bfd_score_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info) { struct elf_link_hash_entry *h; struct bfd_link_hash_entry *bh; flagword flags; asection *s; flags = (SEC_ALLOC | SEC_LOAD | SEC_HAS_CONTENTS | SEC_IN_MEMORY | SEC_LINKER_CREATED | SEC_READONLY); /* ABI requests the .dynamic section to be read only. */ s = bfd_get_linker_section (abfd, ".dynamic"); if (s != NULL) { if (!bfd_set_section_flags (abfd, s, flags)) return FALSE; } /* We need to create .got section. */ if (!score_elf_create_got_section (abfd, info, FALSE)) return FALSE; if (!score_elf_rel_dyn_section (elf_hash_table (info)->dynobj, TRUE)) return FALSE; /* Create .stub section. */ if (bfd_get_linker_section (abfd, SCORE_ELF_STUB_SECTION_NAME) == NULL) { s = bfd_make_section_anyway_with_flags (abfd, SCORE_ELF_STUB_SECTION_NAME, flags | SEC_CODE); if (s == NULL || !bfd_set_section_alignment (abfd, s, 2)) return FALSE; } if (!bfd_link_pic (info)) { const char *name; name = "_DYNAMIC_LINK"; bh = NULL; if (!(_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL, bfd_abs_section_ptr, (bfd_vma) 0, NULL, FALSE, get_elf_backend_data (abfd)->collect, &bh))) return FALSE; h = (struct elf_link_hash_entry *)bh; h->non_elf = 0; h->def_regular = 1; h->type = STT_SECTION; if (!bfd_elf_link_record_dynamic_symbol (info, h)) return FALSE; } return TRUE; } /* Finish up dynamic symbol handling. We set the contents of various dynamic sections here. */ static bfd_boolean s3_bfd_score_elf_finish_dynamic_symbol (bfd *output_bfd, struct bfd_link_info *info, struct elf_link_hash_entry *h, Elf_Internal_Sym *sym) { bfd *dynobj; asection *sgot; struct score_got_info *g; const char *name; dynobj = elf_hash_table (info)->dynobj; if (h->plt.offset != MINUS_ONE) { asection *s; bfd_byte stub[SCORE_FUNCTION_STUB_SIZE]; /* This symbol has a stub. Set it up. */ BFD_ASSERT (h->dynindx != -1); s = bfd_get_linker_section (dynobj, SCORE_ELF_STUB_SECTION_NAME); BFD_ASSERT (s != NULL); /* FIXME: Can h->dynindex be more than 64K? */ if (h->dynindx & 0xffff0000) return FALSE; /* Fill the stub. */ score_bfd_put_32 (output_bfd, STUB_LW, stub); score_bfd_put_32 (output_bfd, STUB_MOVE, stub + 4); score_bfd_put_32 (output_bfd, STUB_LI16 | (h->dynindx << 1), stub + 8); score_bfd_put_32 (output_bfd, STUB_BRL, stub + 12); BFD_ASSERT (h->plt.offset <= s->size); memcpy (s->contents + h->plt.offset, stub, SCORE_FUNCTION_STUB_SIZE); /* Mark the symbol as undefined. plt.offset != -1 occurs only for the referenced symbol. */ sym->st_shndx = SHN_UNDEF; /* The run-time linker uses the st_value field of the symbol to reset the global offset table entry for this external to its stub address when unlinking a shared object. */ sym->st_value = (s->output_section->vma + s->output_offset + h->plt.offset); } BFD_ASSERT (h->dynindx != -1 || h->forced_local); sgot = score_elf_got_section (dynobj, FALSE); BFD_ASSERT (sgot != NULL); BFD_ASSERT (score_elf_section_data (sgot) != NULL); g = score_elf_section_data (sgot)->u.got_info; BFD_ASSERT (g != NULL); /* Run through the global symbol table, creating GOT entries for all the symbols that need them. */ if (g->global_gotsym != NULL && h->dynindx >= g->global_gotsym->dynindx) { bfd_vma offset; bfd_vma value; value = sym->st_value; offset = score_elf_global_got_index (dynobj, h); score_bfd_put_32 (output_bfd, value, sgot->contents + offset); } /* Mark _DYNAMIC and _GLOBAL_OFFSET_TABLE_ as absolute. */ name = h->root.root.string; if (h == elf_hash_table (info)->hdynamic || h == elf_hash_table (info)->hgot) sym->st_shndx = SHN_ABS; else if (strcmp (name, "_DYNAMIC_LINK") == 0) { sym->st_shndx = SHN_ABS; sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION); sym->st_value = 1; } else if (strcmp (name, GP_DISP_LABEL) == 0) { sym->st_shndx = SHN_ABS; sym->st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION); sym->st_value = elf_gp (output_bfd); } return TRUE; } /* Finish up the dynamic sections. */ static bfd_boolean s3_bfd_score_elf_finish_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info) { bfd *dynobj; asection *sdyn; asection *sgot; asection *s; struct score_got_info *g; dynobj = elf_hash_table (info)->dynobj; sdyn = bfd_get_linker_section (dynobj, ".dynamic"); sgot = score_elf_got_section (dynobj, FALSE); if (sgot == NULL) g = NULL; else { BFD_ASSERT (score_elf_section_data (sgot) != NULL); g = score_elf_section_data (sgot)->u.got_info; BFD_ASSERT (g != NULL); } if (elf_hash_table (info)->dynamic_sections_created) { bfd_byte *b; BFD_ASSERT (sdyn != NULL); BFD_ASSERT (g != NULL); for (b = sdyn->contents; b < sdyn->contents + sdyn->size; b += SCORE_ELF_DYN_SIZE (dynobj)) { Elf_Internal_Dyn dyn; const char *name; size_t elemsize; bfd_boolean swap_out_p; /* Read in the current dynamic entry. */ (*get_elf_backend_data (dynobj)->s->swap_dyn_in) (dynobj, b, &dyn); /* Assume that we're going to modify it and write it out. */ swap_out_p = TRUE; switch (dyn.d_tag) { case DT_RELENT: dyn.d_un.d_val = SCORE_ELF_REL_SIZE (dynobj); break; case DT_STRSZ: /* Rewrite DT_STRSZ. */ dyn.d_un.d_val = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr); break; case DT_PLTGOT: s = elf_hash_table (info)->sgot; dyn.d_un.d_ptr = s->output_section->vma + s->output_offset; break; case DT_SCORE_BASE_ADDRESS: s = output_bfd->sections; BFD_ASSERT (s != NULL); dyn.d_un.d_ptr = s->vma & ~(bfd_vma) 0xffff; break; case DT_SCORE_LOCAL_GOTNO: dyn.d_un.d_val = g->local_gotno; break; case DT_SCORE_UNREFEXTNO: /* The index into the dynamic symbol table which is the entry of the first external symbol that is not referenced within the same object. */ dyn.d_un.d_val = bfd_count_sections (output_bfd) + 1; break; case DT_SCORE_GOTSYM: if (g->global_gotsym) { dyn.d_un.d_val = g->global_gotsym->dynindx; break; } /* In case if we don't have global got symbols we default to setting DT_SCORE_GOTSYM to the same value as DT_SCORE_SYMTABNO. */ /* Fall through. */ case DT_SCORE_SYMTABNO: name = ".dynsym"; elemsize = SCORE_ELF_SYM_SIZE (output_bfd); s = bfd_get_linker_section (dynobj, name); dyn.d_un.d_val = s->size / elemsize; break; case DT_SCORE_HIPAGENO: dyn.d_un.d_val = g->local_gotno - SCORE_RESERVED_GOTNO; break; default: swap_out_p = FALSE; break; } if (swap_out_p) (*get_elf_backend_data (dynobj)->s->swap_dyn_out) (dynobj, &dyn, b); } } /* The first entry of the global offset table will be filled at runtime. The second entry will be used by some runtime loaders. This isn't the case of IRIX rld. */ if (sgot != NULL && sgot->size > 0) { score_bfd_put_32 (output_bfd, 0, sgot->contents); score_bfd_put_32 (output_bfd, 0x80000000, sgot->contents + SCORE_ELF_GOT_SIZE (output_bfd)); } if (sgot != NULL) elf_section_data (sgot->output_section)->this_hdr.sh_entsize = SCORE_ELF_GOT_SIZE (output_bfd); /* We need to sort the entries of the dynamic relocation section. */ s = score_elf_rel_dyn_section (dynobj, FALSE); if (s != NULL && s->size > (bfd_vma)2 * SCORE_ELF_REL_SIZE (output_bfd)) { reldyn_sorting_bfd = output_bfd; qsort ((Elf32_External_Rel *) s->contents + 1, s->reloc_count - 1, sizeof (Elf32_External_Rel), score_elf_sort_dynamic_relocs); } return TRUE; } /* This function set up the ELF section header for a BFD section in preparation for writing it out. This is where the flags and type fields are set for unusual sections. */ static bfd_boolean s3_bfd_score_elf_fake_sections (bfd *abfd ATTRIBUTE_UNUSED, Elf_Internal_Shdr *hdr, asection *sec) { const char *name; name = bfd_get_section_name (abfd, sec); if (strcmp (name, ".got") == 0 || strcmp (name, ".srdata") == 0 || strcmp (name, ".sdata") == 0 || strcmp (name, ".sbss") == 0) hdr->sh_flags |= SHF_SCORE_GPREL; return TRUE; } /* This function do additional processing on the ELF section header before writing it out. This is used to set the flags and type fields for some sections. */ /* assign_file_positions_except_relocs() check section flag and if it is allocatable, warning message will be issued. backend_fake_section is called before assign_file_positions_except_relocs(); backend_section_processing after it. so, we modify section flag there, but not backend_fake_section. */ static bfd_boolean s3_bfd_score_elf_section_processing (bfd *abfd ATTRIBUTE_UNUSED, Elf_Internal_Shdr *hdr) { if (hdr->bfd_section != NULL) { const char *name = bfd_get_section_name (abfd, hdr->bfd_section); if (strcmp (name, ".sdata") == 0) { hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_SCORE_GPREL; hdr->sh_type = SHT_PROGBITS; } else if (strcmp (name, ".sbss") == 0) { hdr->sh_flags |= SHF_ALLOC | SHF_WRITE | SHF_SCORE_GPREL; hdr->sh_type = SHT_NOBITS; } else if (strcmp (name, ".srdata") == 0) { hdr->sh_flags |= SHF_ALLOC | SHF_SCORE_GPREL; hdr->sh_type = SHT_PROGBITS; } } return TRUE; } static bfd_boolean s3_bfd_score_elf_write_section (bfd *output_bfd, asection *sec, bfd_byte *contents) { bfd_byte *to, *from, *end; int i; if (strcmp (sec->name, ".pdr") != 0) return FALSE; if (score_elf_section_data (sec)->u.tdata == NULL) return FALSE; to = contents; end = contents + sec->size; for (from = contents, i = 0; from < end; from += PDR_SIZE, i++) { if ((score_elf_section_data (sec)->u.tdata)[i] == 1) continue; if (to != from) memcpy (to, from, PDR_SIZE); to += PDR_SIZE; } bfd_set_section_contents (output_bfd, sec->output_section, contents, (file_ptr) sec->output_offset, sec->size); return TRUE; } /* Copy data from a SCORE ELF indirect symbol to its direct symbol, hiding the old indirect symbol. Process additional relocation information. */ static void s3_bfd_score_elf_copy_indirect_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *dir, struct elf_link_hash_entry *ind) { struct score_elf_link_hash_entry *dirscore, *indscore; _bfd_elf_link_hash_copy_indirect (info, dir, ind); if (ind->root.type != bfd_link_hash_indirect) return; dirscore = (struct score_elf_link_hash_entry *) dir; indscore = (struct score_elf_link_hash_entry *) ind; dirscore->possibly_dynamic_relocs += indscore->possibly_dynamic_relocs; if (indscore->readonly_reloc) dirscore->readonly_reloc = TRUE; if (indscore->no_fn_stub) dirscore->no_fn_stub = TRUE; } /* Remove information about discarded functions from other sections which mention them. */ static bfd_boolean s3_bfd_score_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie, struct bfd_link_info *info) { asection *o; bfd_boolean ret = FALSE; unsigned char *tdata; size_t i, skip; o = bfd_get_section_by_name (abfd, ".pdr"); if ((!o) || (o->size == 0) || (o->size % PDR_SIZE != 0) || (o->output_section != NULL && bfd_is_abs_section (o->output_section))) return FALSE; tdata = bfd_zmalloc (o->size / PDR_SIZE); if (!tdata) return FALSE; cookie->rels = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL, info->keep_memory); if (!cookie->rels) { free (tdata); return FALSE; } cookie->rel = cookie->rels; cookie->relend = cookie->rels + o->reloc_count; for (i = 0, skip = 0; i < o->size; i++) { if (bfd_elf_reloc_symbol_deleted_p (i * PDR_SIZE, cookie)) { tdata[i] = 1; skip++; } } if (skip != 0) { score_elf_section_data (o)->u.tdata = tdata; o->size -= skip * PDR_SIZE; ret = TRUE; } else free (tdata); if (!info->keep_memory) free (cookie->rels); return ret; } /* Signal that discard_info() has removed the discarded relocations for this section. */ static bfd_boolean s3_bfd_score_elf_ignore_discarded_relocs (asection *sec) { if (strcmp (sec->name, ".pdr") == 0) return TRUE; return FALSE; } /* Return the section that should be marked against GC for a given relocation. */ static asection * s3_bfd_score_elf_gc_mark_hook (asection *sec, struct bfd_link_info *info, Elf_Internal_Rela *rel, struct elf_link_hash_entry *h, Elf_Internal_Sym *sym) { if (h != NULL) switch (ELF32_R_TYPE (rel->r_info)) { case R_SCORE_GNU_VTINHERIT: case R_SCORE_GNU_VTENTRY: return NULL; } return _bfd_elf_gc_mark_hook (sec, info, rel, h, sym); } /* Support for core dump NOTE sections. */ static bfd_boolean s3_bfd_score_elf_grok_prstatus (bfd *abfd, Elf_Internal_Note *note) { int offset; unsigned int raw_size; switch (note->descsz) { default: return FALSE; case 148: /* Linux/Score 32-bit. */ /* pr_cursig */ elf_tdata (abfd)->core->signal = score_bfd_get_16 (abfd, note->descdata + 12); /* pr_pid */ elf_tdata (abfd)->core->lwpid = score_bfd_get_32 (abfd, note->descdata + 24); /* pr_reg */ offset = 72; raw_size = 72; break; } /* Make a ".reg/999" section. */ return _bfd_elfcore_make_pseudosection (abfd, ".reg", raw_size, note->descpos + offset); } static bfd_boolean s3_bfd_score_elf_grok_psinfo (bfd *abfd, Elf_Internal_Note *note) { switch (note->descsz) { default: return FALSE; case 124: /* Linux/Score elf_prpsinfo. */ elf_tdata (abfd)->core->program = _bfd_elfcore_strndup (abfd, note->descdata + 28, 16); elf_tdata (abfd)->core->command = _bfd_elfcore_strndup (abfd, note->descdata + 44, 80); } /* Note that for some reason, a spurious space is tacked onto the end of the args in some (at least one anyway) implementations, so strip it off if it exists. */ { char *command = elf_tdata (abfd)->core->command; int n = strlen (command); if (0 < n && command[n - 1] == ' ') command[n - 1] = '\0'; } return TRUE; } /* Score BFD functions. */ static reloc_howto_type * s3_elf32_score_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED, bfd_reloc_code_real_type code) { unsigned int i; for (i = 0; i < ARRAY_SIZE (elf32_score_reloc_map); i++) if (elf32_score_reloc_map[i].bfd_reloc_val == code) return &elf32_score_howto_table[elf32_score_reloc_map[i].elf_reloc_val]; return NULL; } static reloc_howto_type * elf32_score_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED, const char *r_name) { unsigned int i; for (i = 0; i < (sizeof (elf32_score_howto_table) / sizeof (elf32_score_howto_table[0])); i++) if (elf32_score_howto_table[i].name != NULL && strcasecmp (elf32_score_howto_table[i].name, r_name) == 0) return &elf32_score_howto_table[i]; return NULL; } static bfd_boolean s3_elf32_score_print_private_bfd_data (bfd *abfd, void * ptr) { FILE *file = (FILE *) ptr; BFD_ASSERT (abfd != NULL && ptr != NULL); /* Print normal ELF private data. */ _bfd_elf_print_private_bfd_data (abfd, ptr); /* xgettext:c-format */ fprintf (file, _("private flags = %lx:"), elf_elfheader (abfd)->e_flags); if (elf_elfheader (abfd)->e_flags & EF_SCORE_PIC) { fprintf (file, _(" [pic]")); } if (elf_elfheader (abfd)->e_flags & EF_SCORE_FIXDEP) { fprintf (file, _(" [fix dep]")); } fputc ('\n', file); return TRUE; } static bfd_boolean s3_elf32_score_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info) { bfd *obfd = info->output_bfd; flagword in_flags; flagword out_flags; if (!_bfd_generic_verify_endian_match (ibfd, info)) return FALSE; in_flags = elf_elfheader (ibfd)->e_flags; out_flags = elf_elfheader (obfd)->e_flags; if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour || bfd_get_flavour (obfd) != bfd_target_elf_flavour) return TRUE; in_flags = elf_elfheader (ibfd)->e_flags; out_flags = elf_elfheader (obfd)->e_flags; if (! elf_flags_init (obfd)) { elf_flags_init (obfd) = TRUE; elf_elfheader (obfd)->e_flags = in_flags; if (bfd_get_arch (obfd) == bfd_get_arch (ibfd) && bfd_get_arch_info (obfd)->the_default) { return bfd_set_arch_mach (obfd, bfd_get_arch (ibfd), bfd_get_mach (ibfd)); } return TRUE; } if (((in_flags & EF_SCORE_PIC) != 0) != ((out_flags & EF_SCORE_PIC) != 0)) _bfd_error_handler (_("%B: warning: linking PIC files with non-PIC files"), ibfd); /* FIXME: Maybe dependency fix compatibility should be checked here. */ return TRUE; } static bfd_boolean s3_elf32_score_new_section_hook (bfd *abfd, asection *sec) { struct _score_elf_section_data *sdata; bfd_size_type amt = sizeof (*sdata); sdata = bfd_zalloc (abfd, amt); if (sdata == NULL) return FALSE; sec->used_by_bfd = sdata; return _bfd_elf_new_section_hook (abfd, sec); } /*****************************************************************************/ /* s3_s7: backend hooks. */ static void _bfd_score_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED, arelent *bfd_reloc, Elf_Internal_Rela *elf_reloc) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_info_to_howto (abfd, bfd_reloc, elf_reloc); else return s7_bfd_score_info_to_howto (abfd, bfd_reloc, elf_reloc); } static bfd_boolean _bfd_score_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info, bfd *input_bfd, asection *input_section, bfd_byte *contents, Elf_Internal_Rela *relocs, Elf_Internal_Sym *local_syms, asection **local_sections) { if (bfd_get_mach (output_bfd) == bfd_mach_score3) return s3_bfd_score_elf_relocate_section (output_bfd, info, input_bfd, input_section, contents, relocs, local_syms, local_sections); else return s7_bfd_score_elf_relocate_section (output_bfd, info, input_bfd, input_section, contents, relocs, local_syms, local_sections); } static bfd_boolean _bfd_score_elf_check_relocs (bfd *abfd, struct bfd_link_info *info, asection *sec, const Elf_Internal_Rela *relocs) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_check_relocs (abfd, info, sec, relocs); else return s7_bfd_score_elf_check_relocs (abfd, info, sec, relocs); } static bfd_boolean _bfd_score_elf_add_symbol_hook (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym, const char **namep ATTRIBUTE_UNUSED, flagword *flagsp ATTRIBUTE_UNUSED, asection **secp, bfd_vma *valp) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_add_symbol_hook (abfd, info, sym, namep, flagsp, secp, valp); else return s7_bfd_score_elf_add_symbol_hook (abfd, info, sym, namep, flagsp, secp, valp); } static void _bfd_score_elf_symbol_processing (bfd *abfd, asymbol *asym) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_symbol_processing (abfd, asym); else return s7_bfd_score_elf_symbol_processing (abfd, asym); } static int _bfd_score_elf_link_output_symbol_hook (struct bfd_link_info *info ATTRIBUTE_UNUSED, const char *name ATTRIBUTE_UNUSED, Elf_Internal_Sym *sym, asection *input_sec, struct elf_link_hash_entry *h ATTRIBUTE_UNUSED) { /* If link a empty .o, then this filed is NULL. */ if (info->input_bfds == NULL) { /* If we see a common symbol, which implies a relocatable link, then if a symbol was small common in an input file, mark it as small common in the output file. */ if (sym->st_shndx == SHN_COMMON && strcmp (input_sec->name, ".scommon") == 0) sym->st_shndx = SHN_SCORE_SCOMMON; return 1; } if (bfd_get_mach (info->input_bfds) == bfd_mach_score3) return s3_bfd_score_elf_link_output_symbol_hook (info, name, sym, input_sec, h); else return s7_bfd_score_elf_link_output_symbol_hook (info, name, sym, input_sec, h); } static bfd_boolean _bfd_score_elf_section_from_bfd_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, int *retval) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_section_from_bfd_section (abfd, sec, retval); else return s7_bfd_score_elf_section_from_bfd_section (abfd, sec, retval); } static bfd_boolean _bfd_score_elf_adjust_dynamic_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *h) { if (bfd_get_mach (info->input_bfds) == bfd_mach_score3) return s3_bfd_score_elf_adjust_dynamic_symbol (info, h); else return s7_bfd_score_elf_adjust_dynamic_symbol (info, h); } static bfd_boolean _bfd_score_elf_always_size_sections (bfd *output_bfd, struct bfd_link_info *info) { if (bfd_get_mach (output_bfd) == bfd_mach_score3) return s3_bfd_score_elf_always_size_sections (output_bfd, info); else return s7_bfd_score_elf_always_size_sections (output_bfd, info); } static bfd_boolean _bfd_score_elf_size_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info) { if (bfd_get_mach (output_bfd) == bfd_mach_score3) return s3_bfd_score_elf_size_dynamic_sections (output_bfd, info); else return s7_bfd_score_elf_size_dynamic_sections (output_bfd, info); } static bfd_boolean _bfd_score_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_create_dynamic_sections (abfd, info); else return s7_bfd_score_elf_create_dynamic_sections (abfd, info); } static bfd_boolean _bfd_score_elf_finish_dynamic_symbol (bfd *output_bfd, struct bfd_link_info *info, struct elf_link_hash_entry *h, Elf_Internal_Sym *sym) { if (bfd_get_mach (output_bfd) == bfd_mach_score3) return s3_bfd_score_elf_finish_dynamic_symbol (output_bfd, info, h, sym); else return s7_bfd_score_elf_finish_dynamic_symbol (output_bfd, info, h, sym); } static bfd_boolean _bfd_score_elf_finish_dynamic_sections (bfd *output_bfd, struct bfd_link_info *info) { if (bfd_get_mach (output_bfd) == bfd_mach_score3) return s3_bfd_score_elf_finish_dynamic_sections (output_bfd, info); else return s7_bfd_score_elf_finish_dynamic_sections (output_bfd, info); } static bfd_boolean _bfd_score_elf_fake_sections (bfd *abfd ATTRIBUTE_UNUSED, Elf_Internal_Shdr *hdr, asection *sec) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_fake_sections (abfd, hdr, sec); else return s7_bfd_score_elf_fake_sections (abfd, hdr, sec); } static bfd_boolean _bfd_score_elf_section_processing (bfd *abfd ATTRIBUTE_UNUSED, Elf_Internal_Shdr *hdr) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_section_processing (abfd, hdr); else return s7_bfd_score_elf_section_processing (abfd, hdr); } static bfd_boolean _bfd_score_elf_write_section (bfd *output_bfd, struct bfd_link_info *link_info ATTRIBUTE_UNUSED, asection *sec, bfd_byte *contents) { if (bfd_get_mach (output_bfd) == bfd_mach_score3) return s3_bfd_score_elf_write_section (output_bfd, sec, contents); else return s7_bfd_score_elf_write_section (output_bfd, sec, contents); } static void _bfd_score_elf_copy_indirect_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *dir, struct elf_link_hash_entry *ind) { if (bfd_get_mach (info->input_bfds) == bfd_mach_score3) return s3_bfd_score_elf_copy_indirect_symbol (info, dir, ind); else return s7_bfd_score_elf_copy_indirect_symbol (info, dir, ind); } static void _bfd_score_elf_hide_symbol (struct bfd_link_info *info, struct elf_link_hash_entry *entry, bfd_boolean force_local) { if (bfd_get_mach (info->input_bfds) == bfd_mach_score3) return s3_bfd_score_elf_hide_symbol (info, entry, force_local); else return s7_bfd_score_elf_hide_symbol (info, entry, force_local); } static bfd_boolean _bfd_score_elf_discard_info (bfd *abfd, struct elf_reloc_cookie *cookie, struct bfd_link_info *info) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_discard_info (abfd, cookie, info); else return s7_bfd_score_elf_discard_info (abfd, cookie, info); } static bfd_boolean _bfd_score_elf_ignore_discarded_relocs (asection *sec) { if (bfd_get_mach (sec->owner) == bfd_mach_score3) return s3_bfd_score_elf_ignore_discarded_relocs (sec); else return s7_bfd_score_elf_ignore_discarded_relocs (sec); } static asection * _bfd_score_elf_gc_mark_hook (asection *sec, struct bfd_link_info *info, Elf_Internal_Rela *rel, struct elf_link_hash_entry *h, Elf_Internal_Sym *sym) { if (bfd_get_mach (info->input_bfds) == bfd_mach_score3) return s3_bfd_score_elf_gc_mark_hook (sec, info, rel, h, sym); else return s7_bfd_score_elf_gc_mark_hook (sec, info, rel, h, sym); } static bfd_boolean _bfd_score_elf_grok_prstatus (bfd *abfd, Elf_Internal_Note *note) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_grok_prstatus (abfd, note); else return s7_bfd_score_elf_grok_prstatus (abfd, note); } static bfd_boolean _bfd_score_elf_grok_psinfo (bfd *abfd, Elf_Internal_Note *note) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_bfd_score_elf_grok_psinfo (abfd, note); else return s7_bfd_score_elf_grok_psinfo (abfd, note); } static reloc_howto_type * elf32_score_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED, bfd_reloc_code_real_type code) { /* s3: NOTE!!! gas will call elf32_score_reloc_type_lookup, and don't write elf file. So just using score3, but we don't know ld will call this or not. If so, this way can't work. */ if (score3) return s3_elf32_score_reloc_type_lookup (abfd, code); else return s7_elf32_score_reloc_type_lookup (abfd, code); } /* Create a score elf linker hash table. This is a copy of _bfd_elf_link_hash_table_create() except with a different hash table entry creation function. */ static struct bfd_link_hash_table * elf32_score_link_hash_table_create (bfd *abfd) { struct elf_link_hash_table *ret; bfd_size_type amt = sizeof (struct elf_link_hash_table); ret = (struct elf_link_hash_table *) bfd_zmalloc (amt); if (ret == NULL) return NULL; if (!_bfd_elf_link_hash_table_init (ret, abfd, score_elf_link_hash_newfunc, sizeof (struct score_elf_link_hash_entry), GENERIC_ELF_DATA)) { free (ret); return NULL; } return &ret->root; } static bfd_boolean elf32_score_print_private_bfd_data (bfd *abfd, void * ptr) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_elf32_score_print_private_bfd_data (abfd, ptr); else return s7_elf32_score_print_private_bfd_data (abfd, ptr); } static bfd_boolean elf32_score_merge_private_bfd_data (bfd *ibfd, struct bfd_link_info *info) { if (bfd_get_mach (info->output_bfd) == bfd_mach_score3) return s3_elf32_score_merge_private_bfd_data (ibfd, info); else return s7_elf32_score_merge_private_bfd_data (ibfd, info); } static bfd_boolean elf32_score_new_section_hook (bfd *abfd, asection *sec) { if (bfd_get_mach (abfd) == bfd_mach_score3) return s3_elf32_score_new_section_hook (abfd, sec); else return s7_elf32_score_new_section_hook (abfd, sec); } /* s3_s7: don't need to split. */ /* Set the right machine number. */ static bfd_boolean _bfd_score_elf_score_object_p (bfd * abfd) { int e_set = bfd_mach_score7; if (elf_elfheader (abfd)->e_machine == EM_SCORE) { int e_mach = elf_elfheader (abfd)->e_flags & EF_SCORE_MACH & EF_OMIT_PIC_FIXDD; switch (e_mach) { /* Set default target is score7. */ default: case E_SCORE_MACH_SCORE7: e_set = bfd_mach_score7; break; case E_SCORE_MACH_SCORE3: e_set = bfd_mach_score3; break; } } return bfd_default_set_arch_mach (abfd, bfd_arch_score, e_set); } bfd_boolean _bfd_score_elf_common_definition (Elf_Internal_Sym *sym) { return (sym->st_shndx == SHN_COMMON || sym->st_shndx == SHN_SCORE_SCOMMON); } /*****************************************************************************/ #define USE_REL 1 #define TARGET_LITTLE_SYM score_elf32_le_vec #define TARGET_LITTLE_NAME "elf32-littlescore" #define TARGET_BIG_SYM score_elf32_be_vec #define TARGET_BIG_NAME "elf32-bigscore" #define ELF_ARCH bfd_arch_score #define ELF_MACHINE_CODE EM_SCORE #define ELF_MACHINE_ALT1 EM_SCORE_OLD #define ELF_MAXPAGESIZE 0x8000 #define elf_info_to_howto 0 #define elf_info_to_howto_rel _bfd_score_info_to_howto #define elf_backend_relocate_section _bfd_score_elf_relocate_section #define elf_backend_check_relocs _bfd_score_elf_check_relocs #define elf_backend_add_symbol_hook _bfd_score_elf_add_symbol_hook #define elf_backend_symbol_processing _bfd_score_elf_symbol_processing #define elf_backend_link_output_symbol_hook \ _bfd_score_elf_link_output_symbol_hook #define elf_backend_section_from_bfd_section \ _bfd_score_elf_section_from_bfd_section #define elf_backend_adjust_dynamic_symbol \ _bfd_score_elf_adjust_dynamic_symbol #define elf_backend_always_size_sections \ _bfd_score_elf_always_size_sections #define elf_backend_size_dynamic_sections \ _bfd_score_elf_size_dynamic_sections #define elf_backend_omit_section_dynsym \ ((bfd_boolean (*) (bfd *, struct bfd_link_info *, asection *)) bfd_true) #define elf_backend_create_dynamic_sections \ _bfd_score_elf_create_dynamic_sections #define elf_backend_finish_dynamic_symbol \ _bfd_score_elf_finish_dynamic_symbol #define elf_backend_finish_dynamic_sections \ _bfd_score_elf_finish_dynamic_sections #define elf_backend_fake_sections _bfd_score_elf_fake_sections #define elf_backend_section_processing _bfd_score_elf_section_processing #define elf_backend_write_section _bfd_score_elf_write_section #define elf_backend_copy_indirect_symbol _bfd_score_elf_copy_indirect_symbol #define elf_backend_hide_symbol _bfd_score_elf_hide_symbol #define elf_backend_discard_info _bfd_score_elf_discard_info #define elf_backend_ignore_discarded_relocs \ _bfd_score_elf_ignore_discarded_relocs #define elf_backend_gc_mark_hook _bfd_score_elf_gc_mark_hook #define elf_backend_grok_prstatus _bfd_score_elf_grok_prstatus #define elf_backend_grok_psinfo _bfd_score_elf_grok_psinfo #define elf_backend_can_gc_sections 1 #define elf_backend_want_plt_sym 0 #define elf_backend_got_header_size (4 * SCORE_RESERVED_GOTNO) #define elf_backend_plt_header_size 0 #define elf_backend_collect TRUE #define elf_backend_type_change_ok TRUE #define elf_backend_object_p _bfd_score_elf_score_object_p #define bfd_elf32_bfd_reloc_type_lookup elf32_score_reloc_type_lookup #define bfd_elf32_bfd_reloc_name_lookup \ elf32_score_reloc_name_lookup #define bfd_elf32_bfd_link_hash_table_create elf32_score_link_hash_table_create #define bfd_elf32_bfd_print_private_bfd_data elf32_score_print_private_bfd_data #define bfd_elf32_bfd_merge_private_bfd_data elf32_score_merge_private_bfd_data #define bfd_elf32_new_section_hook elf32_score_new_section_hook #include "elf32-target.h"
totalspectrum/binutils-propeller
bfd/elf32-score.c
C
gpl-2.0
157,881
/**************************************************************************************************************** Default styles for the WYSIWYG editor Adding style-editor.css to a child theme's root will over-write these styles. ****************************************************************************************************************/ html .mceContentBody { max-width:640px; background:#fff; color:#333; font:100% Arial,sans-serif; line-height:1.5em; } * { font-family: Arial,sans-serif; color: #333; line-height: 1.5em; } a, a:visited { text-decoration:none; color:#999; } a:hover, a:active { color:#333; } h1,h2,h3,h4,h5,h6 { color:#111; font-weight:bold; font-family:Arial,sans-serif; line-height:2em; } h1 { font-size:2em; } h2 { font-size:1.8em; } h3 { font-size:1.4em; } h4 { font-size:1.2em; } h5 { font-size:1em; } h6 { font-size:.8em; } hr { margin:1.4em auto; display:block; clear:both; border-collapse:collapse; border:0; border-bottom:1px solid #aaa; } p { margin-bottom:18px; } blockquote { font-style:italic; } cite { border:0; } sup, sub { font-size:.6em; } pre { background:#f9f9f9; padding:1em; border:1px solid #dadada; } del { color:inherit; } ins { background:#ff8; color:inherit; text-decoration:none; border:0; padding:0 4px; } .wp-caption { background:#f0f0f0; color:#555; padding:10px; border:1px solid #ddd; } .wp-caption img { margin:0; padding:0; } strong { color:#111; } table { border:1px solid #ddd; width:100%; } table th { padding:5px 20px; text-align:left; font-weight:bold; color:#111; } table td { border-top:1px solid #ddd; padding:5px 20px; } .al, .alignleft, .left { position:relative; float:left!important; margin-right:10px; } .ar, .alignright, .right { position:relative; float:right!important; margin-left:10px; } .ma {margin:auto;} .cb {clear:both;} img, p img { float:none; margin:auto; border:0; } .more-link { display:block; position:relative; float:left; clear:both; } .submit-button { background:#333; color:#fff; border:0; width:auto; font-weight:bold; text-transform:uppercase; } .submit-button:hover { background:#555; } .hideme { display:none; } dl, ul, ol { margin:1em 2em; } dl dl, ul ul, ol ol { margin:0em 2em; } ul { list-style:disc; } ol { list-style-type:lower-roman; }
WebDevStudios/StartBox
includes/styles/editor.css
CSS
gpl-2.0
2,312
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #pragma once #if !defined(RXCPP_OPERATORS_RX_SEQUENCE_EQUAL_HPP) #define RXCPP_OPERATORS_RX_SEQUENCE_EQUAL_HPP #include "../rx-includes.hpp" namespace rxcpp { namespace operators { namespace detail { template<class T, class Observable, class OtherObservable, class BinaryPredicate, class Coordination> struct sequence_equal : public operator_base<bool> { typedef rxu::decay_t<Observable> source_type; typedef rxu::decay_t<T> source_value_type; typedef rxu::decay_t<OtherObservable> other_source_type; typedef typename other_source_type::value_type other_source_value_type; typedef rxu::decay_t<BinaryPredicate> predicate_type; typedef rxu::decay_t<Coordination> coordination_type; typedef typename coordination_type::coordinator_type coordinator_type; struct values { values(source_type s, other_source_type t, predicate_type pred, coordination_type sf) : source(std::move(s)) , other(std::move(t)) , pred(std::move(pred)) , coordination(std::move(sf)) { } source_type source; other_source_type other; predicate_type pred; coordination_type coordination; }; values initial; sequence_equal(source_type s, other_source_type t, predicate_type pred, coordination_type sf) : initial(std::move(s), std::move(t), std::move(pred), std::move(sf)) { } template<class Subscriber> void on_subscribe(Subscriber s) const { typedef Subscriber output_type; struct state_type : public std::enable_shared_from_this<state_type> , public values { state_type(const values& vals, coordinator_type coor, const output_type& o) : values(vals) , coordinator(std::move(coor)) , out(o) , source_completed(false) , other_completed(false) { out.add(other_lifetime); out.add(source_lifetime); } composite_subscription other_lifetime; composite_subscription source_lifetime; coordinator_type coordinator; output_type out; mutable std::list<source_value_type> source_values; mutable std::list<other_source_value_type> other_values; mutable bool source_completed; mutable bool other_completed; }; auto coordinator = initial.coordination.create_coordinator(); auto state = std::make_shared<state_type>(initial, std::move(coordinator), std::move(s)); auto other = on_exception( [&](){ return state->coordinator.in(state->other); }, state->out); if (other.empty()) { return; } auto source = on_exception( [&](){ return state->coordinator.in(state->source); }, state->out); if (source.empty()) { return; } auto check_equal = [state]() { if(!state->source_values.empty() && !state->other_values.empty()) { auto x = std::move(state->source_values.front()); state->source_values.pop_front(); auto y = std::move(state->other_values.front()); state->other_values.pop_front(); if (!state->pred(x, y)) { state->out.on_next(false); state->out.on_completed(); } } else { if((!state->source_values.empty() && state->other_completed) || (!state->other_values.empty() && state->source_completed)) { state->out.on_next(false); state->out.on_completed(); } } }; auto check_complete = [state]() { if(state->source_completed && state->other_completed) { state->out.on_next(state->source_values.empty() && state->other_values.empty()); state->out.on_completed(); } }; auto sinkOther = make_subscriber<other_source_value_type>( state->out, state->other_lifetime, // on_next [state, check_equal](other_source_value_type t) { auto& values = state->other_values; values.push_back(t); check_equal(); }, // on_error [state](std::exception_ptr e) { state->out.on_error(e); }, // on_completed [state, check_complete]() { auto& completed = state->other_completed; completed = true; check_complete(); } ); auto selectedSinkOther = on_exception( [&](){ return state->coordinator.out(sinkOther); }, state->out); if (selectedSinkOther.empty()) { return; } other->subscribe(std::move(selectedSinkOther.get())); source.get().subscribe( state->source_lifetime, // on_next [state, check_equal](source_value_type t) { auto& values = state->source_values; values.push_back(t); check_equal(); }, // on_error [state](std::exception_ptr e) { state->out.on_error(e); }, // on_completed [state, check_complete]() { auto& completed = state->source_completed; completed = true; check_complete(); } ); } }; template<class OtherObservable, class BinaryPredicate, class Coordination> class sequence_equal_factory { typedef rxu::decay_t<OtherObservable> other_source_type; typedef rxu::decay_t<Coordination> coordination_type; typedef rxu::decay_t<BinaryPredicate> predicate_type; other_source_type other_source; coordination_type coordination; predicate_type pred; public: sequence_equal_factory(other_source_type t, predicate_type p, coordination_type sf) : other_source(std::move(t)) , coordination(std::move(sf)) , pred(std::move(p)) { } template<class Observable> auto operator()(Observable&& source) -> observable<bool, sequence_equal<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, other_source_type, BinaryPredicate, Coordination>> { return observable<bool, sequence_equal<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, other_source_type, BinaryPredicate, Coordination>>( sequence_equal<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, other_source_type, BinaryPredicate, Coordination>(std::forward<Observable>(source), other_source, pred, coordination)); } }; } template<class OtherObservable> inline auto sequence_equal(OtherObservable&& t) -> detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, identity_one_worker> { return detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, identity_one_worker>(std::forward<OtherObservable>(t), rxu::equal_to<>(), identity_current_thread()); } template<class OtherObservable, class BinaryPredicate, class Check = typename std::enable_if<!is_coordination<BinaryPredicate>::value>::type> inline auto sequence_equal(OtherObservable&& t, BinaryPredicate&& pred) -> detail::sequence_equal_factory<OtherObservable, BinaryPredicate, identity_one_worker> { return detail::sequence_equal_factory<OtherObservable, BinaryPredicate, identity_one_worker>(std::forward<OtherObservable>(t), std::forward<BinaryPredicate>(pred), identity_current_thread()); } template<class OtherObservable, class Coordination, class Check = typename std::enable_if<is_coordination<Coordination>::value>::type> inline auto sequence_equal(OtherObservable&& t, Coordination&& cn) -> detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, Coordination> { return detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, Coordination>(std::forward<OtherObservable>(t), rxu::equal_to<>(), std::forward<Coordination>(cn)); } template<class OtherObservable, class BinaryPredicate, class Coordination> inline auto sequence_equal(OtherObservable&& t, BinaryPredicate&& pred, Coordination&& cn) -> detail::sequence_equal_factory<OtherObservable, BinaryPredicate, Coordination> { return detail::sequence_equal_factory<OtherObservable, BinaryPredicate, Coordination>(std::forward<OtherObservable>(t), std::forward<BinaryPredicate>(pred), std::forward<Coordination>(cn)); } } } #endif
drazenzadravec/nequeo
Tools/Linq/cpp/RX/v2/rxcpp/operators/rx-sequence_equal.hpp
C++
gpl-2.0
8,921
/** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ var varienTabs = new Class.create(); varienTabs.prototype = { initialize : function(containerId, destElementId, activeTabId, shadowTabs){ this.containerId = containerId; this.destElementId = destElementId; this.activeTab = null; this.tabOnClick = this.tabMouseClick.bindAsEventListener(this); this.tabs = $$('#'+this.containerId+' li a.tab-item-link'); this.hideAllTabsContent(); for (var tab=0; tab<this.tabs.length; tab++) { Event.observe(this.tabs[tab],'click',this.tabOnClick); // move tab contents to destination element if($(this.destElementId)){ var tabContentElement = $(this.getTabContentElementId(this.tabs[tab])); if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){ $(this.destElementId).appendChild(tabContentElement); tabContentElement.container = this; tabContentElement.statusBar = this.tabs[tab]; tabContentElement.tabObject = this.tabs[tab]; this.tabs[tab].contentMoved = true; this.tabs[tab].container = this; this.tabs[tab].show = function(){ this.container.showTabContent(this); } if(varienGlobalEvents){ varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]}); } } } /* // this code is pretty slow in IE, so lets do it in tabs*.phtml // mark ajax tabs as not loaded if (Element.hasClassName($(this.tabs[tab].id), 'ajax')) { Element.addClassName($(this.tabs[tab].id), 'notloaded'); } */ // bind shadow tabs if (this.tabs[tab].id && shadowTabs && shadowTabs[this.tabs[tab].id]) { this.tabs[tab].shadowTabs = shadowTabs[this.tabs[tab].id]; } } this.displayFirst = activeTabId; Event.observe(window,'load',this.moveTabContentInDest.bind(this)); }, setSkipDisplayFirstTab : function(){ this.displayFirst = null; }, moveTabContentInDest : function(){ for(var tab=0; tab<this.tabs.length; tab++){ if($(this.destElementId) && !this.tabs[tab].contentMoved){ var tabContentElement = $(this.getTabContentElementId(this.tabs[tab])); if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){ $(this.destElementId).appendChild(tabContentElement); tabContentElement.container = this; tabContentElement.statusBar = this.tabs[tab]; tabContentElement.tabObject = this.tabs[tab]; this.tabs[tab].container = this; this.tabs[tab].show = function(){ this.container.showTabContent(this); } if(varienGlobalEvents){ varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]}); } } } } if (this.displayFirst) { this.showTabContent($(this.displayFirst)); this.displayFirst = null; } }, getTabContentElementId : function(tab){ if(tab){ return tab.id+'_content'; } return false; }, tabMouseClick : function(event) { var tab = Event.findElement(event, 'a'); // go directly to specified url or switch tab if ((tab.href.indexOf('#') != tab.href.length-1) && !(Element.hasClassName(tab, 'ajax')) ) { location.href = tab.href; } else { this.showTabContent(tab); } Event.stop(event); }, hideAllTabsContent : function(){ for(var tab in this.tabs){ this.hideTabContent(this.tabs[tab]); } }, // show tab, ready or not showTabContentImmediately : function(tab) { this.hideAllTabsContent(); var tabContentElement = $(this.getTabContentElementId(tab)); if (tabContentElement) { Element.show(tabContentElement); Element.addClassName(tab, 'active'); // load shadow tabs, if any if (tab.shadowTabs && tab.shadowTabs.length) { for (var k in tab.shadowTabs) { this.loadShadowTab($(tab.shadowTabs[k])); } } if (!Element.hasClassName(tab, 'ajax only')) { Element.removeClassName(tab, 'notloaded'); } this.activeTab = tab; } if (varienGlobalEvents) { varienGlobalEvents.fireEvent('showTab', {tab:tab}); } }, // the lazy show tab method showTabContent : function(tab) { var tabContentElement = $(this.getTabContentElementId(tab)); if (tabContentElement) { if (this.activeTab != tab) { if (varienGlobalEvents) { if (varienGlobalEvents.fireEvent('tabChangeBefore', $(this.getTabContentElementId(this.activeTab))).indexOf('cannotchange') != -1) { return; }; } } // wait for ajax request, if defined var isAjax = Element.hasClassName(tab, 'ajax'); var isEmpty = tabContentElement.innerHTML=='' && tab.href.indexOf('#')!=tab.href.length-1; var isNotLoaded = Element.hasClassName(tab, 'notloaded'); if ( isAjax && (isEmpty || isNotLoaded) ) { new Ajax.Request(tab.href, { parameters: {form_key: FORM_KEY}, evalScripts: true, onSuccess: function(transport) { try { if (transport.responseText.isJSON()) { var response = transport.responseText.evalJSON() if (response.error) { alert(response.message); } if(response.ajaxExpired && response.ajaxRedirect) { setLocation(response.ajaxRedirect); } } else { $(tabContentElement.id).update(transport.responseText); this.showTabContentImmediately(tab) } } catch (e) { $(tabContentElement.id).update(transport.responseText); this.showTabContentImmediately(tab) } }.bind(this) }); } else { this.showTabContentImmediately(tab); } } }, loadShadowTab : function(tab) { var tabContentElement = $(this.getTabContentElementId(tab)); if (tabContentElement && Element.hasClassName(tab, 'ajax') && Element.hasClassName(tab, 'notloaded')) { new Ajax.Request(tab.href, { parameters: {form_key: FORM_KEY}, evalScripts: true, onSuccess: function(transport) { try { if (transport.responseText.isJSON()) { var response = transport.responseText.evalJSON() if (response.error) { alert(response.message); } if(response.ajaxExpired && response.ajaxRedirect) { setLocation(response.ajaxRedirect); } } else { $(tabContentElement.id).update(transport.responseText); if (!Element.hasClassName(tab, 'ajax only')) { Element.removeClassName(tab, 'notloaded'); } } } catch (e) { $(tabContentElement.id).update(transport.responseText); if (!Element.hasClassName(tab, 'ajax only')) { Element.removeClassName(tab, 'notloaded'); } } }.bind(this) }); } }, hideTabContent : function(tab){ var tabContentElement = $(this.getTabContentElementId(tab)); if($(this.destElementId) && tabContentElement){ Element.hide(tabContentElement); Element.removeClassName(tab, 'active'); } if(varienGlobalEvents){ varienGlobalEvents.fireEvent('hideTab', {tab:tab}); } } }
tonio-44/tikflak
shop/js/mage/adminhtml/tabs.js
JavaScript
gpl-2.0
9,985
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2011-2015 ArkCORE <http://www.arkania.net/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "DatabaseEnv.h" #include "Log.h" ResultSet::ResultSet(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount) : _rowCount(rowCount), _fieldCount(fieldCount), _result(result), _fields(fields) { _currentRow = new Field[_fieldCount]; ASSERT(_currentRow); } PreparedResultSet::PreparedResultSet(MYSQL_STMT* stmt, MYSQL_RES *result, uint64 rowCount, uint32 fieldCount) : m_rowCount(rowCount), m_rowPosition(0), m_fieldCount(fieldCount), m_rBind(NULL), m_stmt(stmt), m_res(result), m_isNull(NULL), m_length(NULL) { if (!m_res) return; if (m_stmt->bind_result_done) { delete[] m_stmt->bind->length; delete[] m_stmt->bind->is_null; } m_rBind = new MYSQL_BIND[m_fieldCount]; m_isNull = new my_bool[m_fieldCount]; m_length = new unsigned long[m_fieldCount]; memset(m_isNull, 0, sizeof(my_bool) * m_fieldCount); memset(m_rBind, 0, sizeof(MYSQL_BIND) * m_fieldCount); memset(m_length, 0, sizeof(unsigned long) * m_fieldCount); //- This is where we store the (entire) resultset if (mysql_stmt_store_result(m_stmt)) { TC_LOG_WARN("sql.sql", "%s:mysql_stmt_store_result, cannot bind result from MySQL server. Error: %s", __FUNCTION__, mysql_stmt_error(m_stmt)); delete[] m_rBind; delete[] m_isNull; delete[] m_length; return; } //- This is where we prepare the buffer based on metadata uint32 i = 0; MYSQL_FIELD* field = mysql_fetch_field(m_res); while (field) { size_t size = Field::SizeForType(field); m_rBind[i].buffer_type = field->type; m_rBind[i].buffer = malloc(size); memset(m_rBind[i].buffer, 0, size); m_rBind[i].buffer_length = size; m_rBind[i].length = &m_length[i]; m_rBind[i].is_null = &m_isNull[i]; m_rBind[i].error = NULL; m_rBind[i].is_unsigned = field->flags & UNSIGNED_FLAG; ++i; field = mysql_fetch_field(m_res); } //- This is where we bind the bind the buffer to the statement if (mysql_stmt_bind_result(m_stmt, m_rBind)) { TC_LOG_WARN("sql.sql", "%s:mysql_stmt_bind_result, cannot bind result from MySQL server. Error: %s", __FUNCTION__, mysql_stmt_error(m_stmt)); delete[] m_rBind; delete[] m_isNull; delete[] m_length; return; } m_rowCount = mysql_stmt_num_rows(m_stmt); m_rows.resize(uint32(m_rowCount)); while (_NextRow()) { m_rows[uint32(m_rowPosition)] = new Field[m_fieldCount]; for (uint64 fIndex = 0; fIndex < m_fieldCount; ++fIndex) { if (!*m_rBind[fIndex].is_null) m_rows[uint32(m_rowPosition)][fIndex].SetByteValue( m_rBind[fIndex].buffer, m_rBind[fIndex].buffer_length, m_rBind[fIndex].buffer_type, *m_rBind[fIndex].length ); else switch (m_rBind[fIndex].buffer_type) { case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: case MYSQL_TYPE_STRING: case MYSQL_TYPE_VAR_STRING: m_rows[uint32(m_rowPosition)][fIndex].SetByteValue( "", m_rBind[fIndex].buffer_length, m_rBind[fIndex].buffer_type, *m_rBind[fIndex].length ); break; default: m_rows[uint32(m_rowPosition)][fIndex].SetByteValue( 0, m_rBind[fIndex].buffer_length, m_rBind[fIndex].buffer_type, *m_rBind[fIndex].length ); } } m_rowPosition++; } m_rowPosition = 0; /// All data is buffered, let go of mysql c api structures CleanUp(); } ResultSet::~ResultSet() { CleanUp(); } PreparedResultSet::~PreparedResultSet() { for (uint32 i = 0; i < uint32(m_rowCount); ++i) delete[] m_rows[i]; } bool ResultSet::NextRow() { MYSQL_ROW row; if (!_result) return false; row = mysql_fetch_row(_result); if (!row) { CleanUp(); return false; } for (uint32 i = 0; i < _fieldCount; i++) _currentRow[i].SetStructuredValue(row[i], _fields[i].type); return true; } bool PreparedResultSet::NextRow() { /// Only updates the m_rowPosition so upper level code knows in which element /// of the rows vector to look if (++m_rowPosition >= m_rowCount) return false; return true; } bool PreparedResultSet::_NextRow() { /// Only called in low-level code, namely the constructor /// Will iterate over every row of data and buffer it if (m_rowPosition >= m_rowCount) return false; int retval = mysql_stmt_fetch( m_stmt ); if (!retval || retval == MYSQL_DATA_TRUNCATED) retval = true; if (retval == MYSQL_NO_DATA) retval = false; return retval; } void ResultSet::CleanUp() { if (_currentRow) { delete [] _currentRow; _currentRow = NULL; } if (_result) { mysql_free_result(_result); _result = NULL; } } void PreparedResultSet::CleanUp() { /// More of the in our code allocated sources are deallocated by the poorly documented mysql c api if (m_res) mysql_free_result(m_res); FreeBindBuffer(); mysql_stmt_free_result(m_stmt); delete[] m_rBind; } void PreparedResultSet::FreeBindBuffer() { for (uint32 i = 0; i < m_fieldCount; ++i) free (m_rBind[i].buffer); }
sunshitwowsucks/ArkCORE-NG
src/server/shared/Database/QueryResult.cpp
C++
gpl-2.0
6,901
/* gsm_map_summary.c * Routines for GSM MAP Statictics summary window * * Copyright 2004, Michael Lum <mlum [AT] telostech.com> * In association with Telos Technology Inc. * * Modified from summary_dlg.c * * $Id: gsm_map_summary.c 48448 2013-03-21 02:58:59Z wmeier $ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <gtk/gtk.h> #include <wiretap/wtap.h> #include <epan/epan.h> #include <epan/packet.h> #include <epan/packet_info.h> #include <epan/value_string.h> #include <epan/tap.h> #include <epan/asn1.h> #include <epan/dissectors/packet-gsm_map.h> #include "../stat_menu.h" #include "../globals.h" #include "../file.h" #include "../summary.h" #include "ui/gtk/gui_stat_menu.h" #include "ui/gtk/dlg_utils.h" #include "ui/gtk/gui_utils.h" #include "ui/gtk/gsm_map_stat.h" #define SUM_STR_MAX 1024 static void add_string_to_box(gchar *str, GtkWidget *box) { GtkWidget *lb; lb = gtk_label_new(str); gtk_misc_set_alignment(GTK_MISC(lb), 0.0f, 0.5f); gtk_box_pack_start(GTK_BOX(box), lb,FALSE,FALSE, 0); gtk_widget_show(lb); } void gsm_map_stat_gtk_sum_cb(GtkAction *action _U_, gpointer user_data _U_) { summary_tally summary; GtkWidget *sum_open_w, *main_vb, *file_fr, *data_fr, *file_box, *data_box, *bbox, *close_bt, *invoke_fr, *invoke_box, *rr_fr, *rr_box, *tot_fr, *tot_box; gchar string_buff[SUM_STR_MAX]; double seconds; int i; int tot_invokes, tot_rr; double tot_invokes_size, tot_rr_size; /* initialize the tally */ summary_fill_in(&cfile, &summary); /* initial computations */ seconds = summary.stop_time - summary.start_time; sum_open_w = dlg_window_new("GSM MAP Statistics: Summary"); /* transient_for top_level */ gtk_window_set_destroy_with_parent (GTK_WINDOW(sum_open_w), TRUE); /* Container for each row of widgets */ main_vb = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE); gtk_container_set_border_width(GTK_CONTAINER(main_vb), 5); gtk_container_add(GTK_CONTAINER(sum_open_w), main_vb); gtk_widget_show(main_vb); /* File frame */ file_fr = gtk_frame_new("File"); gtk_box_pack_start(GTK_BOX (main_vb), file_fr, TRUE, TRUE, 0); gtk_widget_show(file_fr); file_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE); gtk_container_add(GTK_CONTAINER(file_fr), file_box); gtk_widget_show(file_box); /* filename */ g_snprintf(string_buff, SUM_STR_MAX, "Name: %s", ((summary.filename) ? summary.filename : "None")); add_string_to_box(string_buff, file_box); /* length */ g_snprintf(string_buff, SUM_STR_MAX, "Length: %" G_GINT64_MODIFIER "d", summary.file_length); add_string_to_box(string_buff, file_box); /* format */ g_snprintf(string_buff, SUM_STR_MAX, "Format: %s", wtap_file_type_string(summary.file_type)); add_string_to_box(string_buff, file_box); if (summary.has_snap) { /* snapshot length */ g_snprintf(string_buff, SUM_STR_MAX, "Snapshot length: %u", summary.snap); add_string_to_box(string_buff, file_box); } /* Data frame */ data_fr = gtk_frame_new("Data"); gtk_box_pack_start(GTK_BOX (main_vb), data_fr, TRUE, TRUE, 0); gtk_widget_show(data_fr); data_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE); gtk_container_add(GTK_CONTAINER(data_fr), data_box); gtk_widget_show(data_box); /* * We must have no un-time-stamped packets (i.e., the number of * time-stamped packets must be the same as the number of packets), * and at least two time-stamped packets, in order for the elapsed * time to be valid. */ if (summary.packet_count_ts == summary.packet_count && summary.packet_count_ts >= 2) { /* seconds */ g_snprintf(string_buff, SUM_STR_MAX, "Elapsed time: %.3f seconds", summary.elapsed_time); add_string_to_box(string_buff, data_box); g_snprintf(string_buff, SUM_STR_MAX, "Between first and last packet: %.3f seconds", seconds); add_string_to_box(string_buff, data_box); } /* Packet count */ g_snprintf(string_buff, SUM_STR_MAX, "Packet count: %i", summary.packet_count); add_string_to_box(string_buff, data_box); tot_invokes = 0; tot_invokes_size = 0; for (i=0; i < GSM_MAP_MAX_NUM_OPR_CODES; i++) { tot_invokes += gsm_map_stat.opr_code[i]; tot_invokes_size += gsm_map_stat.size[i]; } tot_rr = 0; tot_rr_size = 0; for (i=0; i < GSM_MAP_MAX_NUM_OPR_CODES; i++) { tot_rr += gsm_map_stat.opr_code_rr[i]; tot_rr_size += gsm_map_stat.size_rr[i]; } /* Invoke frame */ invoke_fr = gtk_frame_new("Invokes"); gtk_box_pack_start(GTK_BOX (main_vb), invoke_fr, TRUE, TRUE, 0); gtk_widget_show(invoke_fr); invoke_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE); gtk_container_add(GTK_CONTAINER(invoke_fr), invoke_box); gtk_widget_show(invoke_box); /* Total number of invokes */ g_snprintf(string_buff, SUM_STR_MAX, "Total number of Invokes: %u", tot_invokes); add_string_to_box(string_buff, invoke_box); /* * We must have no un-time-stamped packets (i.e., the number of * time-stamped packets must be the same as the number of packets), * and at least two time-stamped packets, in order for the elapsed * time to be valid. */ if (summary.packet_count_ts == summary.packet_count && summary.packet_count_ts >= 2) { /* Total number of invokes per second */ if (seconds) g_snprintf(string_buff, SUM_STR_MAX, "Total number of Invokes per second: %.2f", tot_invokes/seconds); else g_snprintf(string_buff, SUM_STR_MAX, "Total number of Invokes per second: N/A"); add_string_to_box(string_buff, invoke_box); } /* Total size of invokes */ g_snprintf(string_buff, SUM_STR_MAX, "Total number of bytes for Invokes: %.0f", tot_invokes_size); add_string_to_box(string_buff, invoke_box); /* Average size of invokes */ if (tot_invokes) g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per Invoke: %.2f", tot_invokes_size/tot_invokes); else g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per Invoke: N/A"); add_string_to_box(string_buff, invoke_box); /* * We must have no un-time-stamped packets (i.e., the number of * time-stamped packets must be the same as the number of packets), * and at least two time-stamped packets, in order for the elapsed * time to be valid. */ if (summary.packet_count_ts == summary.packet_count && summary.packet_count_ts >= 2) { /* Average size of invokes per second */ if (seconds) g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per second: %.2f", tot_invokes_size/seconds); else g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per second: N/A"); add_string_to_box(string_buff, invoke_box); } /* Return Results frame */ rr_fr = gtk_frame_new("Return Results"); gtk_box_pack_start(GTK_BOX (main_vb), rr_fr, TRUE, TRUE, 0); gtk_widget_show(rr_fr); rr_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE); gtk_container_add(GTK_CONTAINER(rr_fr), rr_box); gtk_widget_show(rr_box); /* Total number of return results */ g_snprintf(string_buff, SUM_STR_MAX, "Total number of Return Results: %u", tot_rr); add_string_to_box(string_buff, rr_box); /* * We must have no un-time-stamped packets (i.e., the number of * time-stamped packets must be the same as the number of packets), * and at least two time-stamped packets, in order for the elapsed * time to be valid. */ if (summary.packet_count_ts == summary.packet_count && summary.packet_count_ts >= 2) { /* Total number of return results per second */ if (seconds) g_snprintf(string_buff, SUM_STR_MAX, "Total number of Return Results per second: %.2f", tot_rr/seconds); else g_snprintf(string_buff, SUM_STR_MAX, "Total number of Return Results per second: N/A"); add_string_to_box(string_buff, rr_box); } /* Total size of return results */ g_snprintf(string_buff, SUM_STR_MAX, "Total number of bytes for Return Results: %.0f", tot_rr_size); add_string_to_box(string_buff, rr_box); /* Average size of return results */ if (tot_rr) g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per Return Result: %.2f", tot_rr_size/tot_rr); else g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per Return Result: N/A"); add_string_to_box(string_buff, rr_box); /* * We must have no un-time-stamped packets (i.e., the number of * time-stamped packets must be the same as the number of packets), * and at least two time-stamped packets, in order for the elapsed * time to be valid. */ if (summary.packet_count_ts == summary.packet_count && summary.packet_count_ts >= 2) { /* Average size of return results per second */ if (seconds) g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per second: %.2f", tot_rr_size/seconds); else g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per second: N/A"); add_string_to_box(string_buff, rr_box); } /* Totals frame */ tot_fr = gtk_frame_new("Totals"); gtk_box_pack_start(GTK_BOX (main_vb), tot_fr, TRUE, TRUE, 0); gtk_widget_show(tot_fr); tot_box = ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE); gtk_container_add(GTK_CONTAINER(tot_fr), tot_box); gtk_widget_show(tot_box); /* Total number of return results */ g_snprintf(string_buff, SUM_STR_MAX, "Total number of GSM MAP messages: %u", tot_invokes + tot_rr); add_string_to_box(string_buff, tot_box); /* * We must have no un-time-stamped packets (i.e., the number of * time-stamped packets must be the same as the number of packets), * and at least two time-stamped packets, in order for the elapsed * time to be valid. */ if (summary.packet_count_ts == summary.packet_count && summary.packet_count_ts >= 2) { if (seconds) g_snprintf(string_buff, SUM_STR_MAX, "Total number of GSM MAP messages per second: %.2f", (tot_invokes + tot_rr)/seconds); else g_snprintf(string_buff, SUM_STR_MAX, "Total number of GSM MAP messages per second: N/A"); add_string_to_box(string_buff, tot_box); } g_snprintf(string_buff, SUM_STR_MAX, "Total number of bytes for GSM MAP messages: %.0f", tot_invokes_size + tot_rr_size); add_string_to_box(string_buff, tot_box); if (tot_invokes + tot_rr) g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per GSM MAP messages: %.2f", (tot_invokes_size + tot_rr_size)/(tot_invokes + tot_rr)); else g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes per GSM MAP messages: N/A"); add_string_to_box(string_buff, tot_box); /* * We must have no un-time-stamped packets (i.e., the number of * time-stamped packets must be the same as the number of packets), * and at least two time-stamped packets, in order for the elapsed * time to be valid. */ if (summary.packet_count_ts == summary.packet_count && summary.packet_count_ts >= 2) { if (seconds) g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes second: %.2f", (tot_invokes_size + tot_rr_size)/seconds); else g_snprintf(string_buff, SUM_STR_MAX, "Average number of bytes second: N/A"); add_string_to_box(string_buff, tot_box); } /* Button row. */ bbox = dlg_button_row_new(GTK_STOCK_CLOSE, NULL); gtk_box_pack_start(GTK_BOX(main_vb), bbox, TRUE, TRUE, 0); gtk_widget_show(bbox); close_bt = (GtkWidget *)g_object_get_data(G_OBJECT(bbox), GTK_STOCK_CLOSE); window_set_cancel_button(sum_open_w, close_bt, window_cancel_button_cb); g_signal_connect(sum_open_w, "delete_event", G_CALLBACK(window_delete_event_cb), NULL); gtk_widget_show(sum_open_w); window_present(sum_open_w); } void register_tap_listener_gtkgsm_map_summary(void) { }
P1sec/LTE_monitor_c2xx
wireshark/ui/gtk/gsm_map_summary.c
C
gpl-2.0
12,651
#include <linux/types.h> #include <linux/proc_fs.h> #include <asm/setup.h> #include <linux/pagemap.h> struct st_read_proc { char *name; int (*read_proc)(char *, char **, off_t, int, int *, void *); }; extern unsigned int get_pd_charge_flag(void); extern unsigned int get_boot_into_recovery_flag(void); extern unsigned int resetmode_is_normal(void); extern unsigned int get_boot_into_recovery_flag(void); /* same as in proc_misc.c */ static int proc_calc_metrics(char *page, char **start, off_t off, int count, int *eof, int len) { if (len <= off + count) *eof = 1; *start = page + off; len -= off; if (len > count) len = count; if (len < 0) len = 0; return len; } static int app_tag_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data) { int len = 0; u32 charge_flag = 0; u32 recovery_flag = 0; u32 reset_normal_flag = 0; recovery_flag = get_boot_into_recovery_flag(); charge_flag = get_pd_charge_flag(); reset_normal_flag = resetmode_is_normal(); len = snprintf(page, PAGE_SIZE, "recovery_flag:\n%d\n" "charge_flag:\n%d\n" "reset_normal_flag:\n%d\n", recovery_flag, charge_flag, reset_normal_flag); return proc_calc_metrics(page, start, off, count, eof, len); } static struct st_read_proc simple_ones[] = { {"app_info", app_tag_read_proc}, {NULL,} }; void __init proc_app_info_init(void) { struct st_read_proc *p; for (p = simple_ones; p->name; p++) create_proc_read_entry(p->name, 0, NULL, p->read_proc, NULL); }
Wonfee/huawei_u9508_kernel
fs/proc/app_info.c
C
gpl-2.0
1,527
obj-y := version_balong.o obj-y += sysfs_version.o
gabry3795/android_kernel_huawei_mt7_l09
drivers/hisi/modem_hi3xxx/drv/version/Makefile
Makefile
gpl-2.0
60
Template.reassign_modal.helpers({ fields: function() { var userOptions = null; var showOrg = true; var instance = WorkflowManager.getInstance(); var space = db.spaces.findOne(instance.space); var flow = db.flows.findOne({ '_id': instance.flow }); var curSpaceUser = db.space_users.findOne({ space: instance.space, 'user': Meteor.userId() }); var organizations = db.organizations.find({ _id: { $in: curSpaceUser.organizations } }).fetch(); if (space.admins.contains(Meteor.userId())) { } else if (WorkflowManager.canAdmin(flow, curSpaceUser, organizations)) { var currentStep = InstanceManager.getCurrentStep() userOptions = ApproveManager.getNextStepUsers(instance, currentStep._id).getProperty("id").join(",") showOrg = Session.get("next_step_users_showOrg") } else { userOptions = "0" showOrg = false } var multi = false; var c = InstanceManager.getCurrentStep(); if (c && c.step_type == "counterSign") { multi = true; } return new SimpleSchema({ reassign_users: { autoform: { type: "selectuser", userOptions: userOptions, showOrg: showOrg, multiple: multi }, optional: true, type: String, label: TAPi18n.__("instance_reassign_user") } }); }, values: function() { return {}; }, current_step_name: function() { var s = InstanceManager.getCurrentStep(); var name; if (s) { name = s.name; } return name || ''; } }) Template.reassign_modal.events({ 'show.bs.modal #reassign_modal': function(event) { var reassign_users = $("input[name='reassign_users']")[0]; reassign_users.value = ""; reassign_users.dataset.values = ''; $(reassign_users).change(); }, 'click #reassign_help': function(event, template) { Steedos.openWindow(t("reassign_help")); }, 'click #reassign_modal_ok': function(event, template) { var val = AutoForm.getFieldValue("reassign_users", "reassign"); if (!val) { toastr.error(TAPi18n.__("instance_reassign_error_users_required")); return; } var reason = $("#reassign_modal_text").val(); var user_ids = val.split(","); InstanceManager.reassignIns(user_ids, reason); Modal.hide(template); }, })
steedos/apps
packages/steedos-workflow/client/views/instance/reassign_modal.js
JavaScript
gpl-2.0
2,218
<html lang="en"> <head> <title>Meta Options - Using as</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Using as"> <meta name="generator" content="makeinfo 4.8"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Meta_002dDependent.html#Meta_002dDependent" title="Meta-Dependent"> <link rel="next" href="Meta-Syntax.html#Meta-Syntax" title="Meta Syntax"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This file documents the GNU Assembler "as". Copyright (C) 1991-2013 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="Meta-Options"></a> Next:&nbsp;<a rel="next" accesskey="n" href="Meta-Syntax.html#Meta-Syntax">Meta Syntax</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Meta_002dDependent.html#Meta_002dDependent">Meta-Dependent</a> <hr> </div> <h4 class="subsection">9.25.1 Options</h4> <p><a name="index-options-for-Meta-1361"></a><a name="index-Meta-options-1362"></a><a name="index-architectures_002c-Meta-1363"></a><a name="index-Meta-architectures-1364"></a> The Imagination Technologies Meta architecture is implemented in a number of versions, with each new version adding new features such as instructions and registers. For precise details of what instructions each core supports, please see the chip's technical reference manual. <p>The following table lists all available Meta options. <!-- man begin OPTIONS --> <dl> <dt><code>-mcpu=metac11</code><dd>Generate code for Meta 1.1. <br><dt><code>-mcpu=metac12</code><dd>Generate code for Meta 1.2. <br><dt><code>-mcpu=metac21</code><dd>Generate code for Meta 2.1. <br><dt><code>-mfpu=metac21</code><dd>Allow code to use FPU hardware of Meta 2.1. </dl> <!-- man end --> </body></html>
jocelynmass/nrf51
toolchain/deprecated/arm_cm0_4.9/share/doc/gcc-arm-none-eabi/html/as.html/Meta-Options.html
HTML
gpl-2.0
2,767
#ifndef _PLOT_H_ #define _PLOT_H_ 1 #include <qwt_plot.h> class RectItem; class QwtInterval; class Plot: public QwtPlot { Q_OBJECT public: Plot( QWidget *parent, const QwtInterval & ); virtual void updateLayout(); void setRectOfInterest( const QRectF & ); Q_SIGNALS: void resized( double xRatio, double yRatio ); private: RectItem *d_rectOfInterest; }; #endif
iclosure/jdataanalyse
source/core/3rdpart/qwt/playground/rescaler/plot.h
C
gpl-2.0
422
#pragma checksum "C:\Users\INDIA\Desktop\SpeechKit-WP7-1.4.0\SampleVoiceApp\hotel.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "06F22895AB29E6AF87DE067810A1DD2E" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Microsoft.Phone.Controls; using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Resources; using System.Windows.Shapes; using System.Windows.Threading; namespace SampleVoiceApp { public partial class hotel : Microsoft.Phone.Controls.PhoneApplicationPage { internal System.Windows.Controls.Grid LayoutRoot; internal System.Windows.Controls.TextBlock textBlock1; internal System.Windows.Controls.TextBlock textBlock2; internal System.Windows.Controls.TextBlock textBlock3; internal System.Windows.Controls.TextBlock textBlock4; internal System.Windows.Controls.TextBlock textBlock5; internal System.Windows.Controls.TextBlock textBlock6; internal System.Windows.Controls.TextBlock textBlock7; internal System.Windows.Controls.TextBlock textBlock8; internal System.Windows.Controls.TextBlock textBlock9; internal System.Windows.Controls.TextBlock textBlock11; internal System.Windows.Controls.TextBlock textBlock12; internal System.Windows.Controls.TextBlock textBlock13; internal System.Windows.Controls.TextBlock textBlock14; internal System.Windows.Controls.TextBlock textBlock15; internal System.Windows.Controls.TextBlock textBlock16; internal System.Windows.Controls.TextBlock textBlock17; internal System.Windows.Controls.TextBlock textBlock18; internal System.Windows.Controls.TextBlock textBlock19; private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/SampleVoiceApp;component/hotel.xaml", System.UriKind.Relative)); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.textBlock1 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock1"))); this.textBlock2 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock2"))); this.textBlock3 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock3"))); this.textBlock4 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock4"))); this.textBlock5 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock5"))); this.textBlock6 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock6"))); this.textBlock7 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock7"))); this.textBlock8 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock8"))); this.textBlock9 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock9"))); this.textBlock11 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock11"))); this.textBlock12 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock12"))); this.textBlock13 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock13"))); this.textBlock14 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock14"))); this.textBlock15 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock15"))); this.textBlock16 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock16"))); this.textBlock17 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock17"))); this.textBlock18 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock18"))); this.textBlock19 = ((System.Windows.Controls.TextBlock)(this.FindName("textBlock19"))); } } }
chahalarora/R.S.C-WindowsPhone
Speak My Voice/obj/Debug/hotel.g.i.cs
C#
gpl-2.0
5,165
<?php namespace Kbize\Sdk\Response; class ProjectAndBoards { /** * * { * "projects":[ * {"name":"Project","id":"1","boards":[ * {"name":"Service\/Merchant Integrations","id":"4"}, * {"name":"Tech Operations","id":"3"}, * {"name":"Main development","id":"2"} * ]} * ] * } */ public static function fromArrayResponse(array $response) { return new self($response['projects']); } private function __construct(array $data) { $this->data = $data; } public function projects() { $projects = []; foreach($this->data as $project) { $projects[] = [ 'name' => $project['name'], 'id' => $project['id'], ]; } return $projects; } public function boards($projectId) { $projects = []; foreach($this->data as $project) { if ($project['id'] == $projectId) { return $project['boards']; } } throw new \Exception("Project: `$projectId` does not exists"); //TODO:! custom exception } }
silvadanilo/kbize
test/unit/Kbize/Sdk/Response/ProjectAndBoards.php
PHP
gpl-2.0
1,183
/* * 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. */ package java.sql; public class SQLTransactionRollbackException extends SQLTransientException { private static final long serialVersionUID = 5246680841170837229L; /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to null, the SQLState string is set to null and the Error Code is set * to 0. */ public SQLTransactionRollbackException() { super(); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to null and * the Error Code is set to 0. * * @param reason * the string to use as the Reason string */ public SQLTransactionRollbackException(String reason) { super(reason, null, 0); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to the given * SQLState string and the Error Code is set to 0. * * @param reason * the string to use as the Reason string * @param sqlState * the string to use as the SQLState string */ public SQLTransactionRollbackException(String reason, String sqlState) { super(reason, sqlState, 0); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to the given * SQLState string and the Error Code is set to the given error code value. * * @param reason * the string to use as the Reason string * @param sqlState * the string to use as the SQLState string * @param vendorCode * the integer value for the error code */ public SQLTransactionRollbackException(String reason, String sqlState, int vendorCode) { super(reason, sqlState, vendorCode); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the null if cause == null or cause.toString() if cause!=null,and * the cause Throwable object is set to the given cause Throwable object. * * @param cause * the Throwable object for the underlying reason this * SQLException */ public SQLTransactionRollbackException(Throwable cause) { super(cause); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given and the cause Throwable object is set to the given cause * Throwable object. * * @param reason * the string to use as the Reason string * @param cause * the Throwable object for the underlying reason this * SQLException */ public SQLTransactionRollbackException(String reason, Throwable cause) { super(reason, cause); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to the given * SQLState string and the cause Throwable object is set to the given cause * Throwable object. * * @param reason * the string to use as the Reason string * @param sqlState * the string to use as the SQLState string * @param cause * the Throwable object for the underlying reason this * SQLException */ public SQLTransactionRollbackException(String reason, String sqlState, Throwable cause) { super(reason, sqlState, cause); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to the given * SQLState string , the Error Code is set to the given error code value, * and the cause Throwable object is set to the given cause Throwable * object. * * @param reason * the string to use as the Reason string * @param sqlState * the string to use as the SQLState string * @param vendorCode * the integer value for the error code * @param cause * the Throwable object for the underlying reason this * SQLException */ public SQLTransactionRollbackException(String reason, String sqlState, int vendorCode, Throwable cause) { super(reason, sqlState, vendorCode, cause); } }
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/sql/src/main/java/java/sql/SQLTransactionRollbackException.java
Java
gpl-2.0
5,553
#!/usr/bin/env python # # 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. See http://www.gnu.org/copyleft/gpl.html for # the full text of the license. # query.py: Perform a few varieties of queries from __future__ import print_function import time import bugzilla # public test instance of bugzilla.redhat.com. It's okay to make changes URL = "partner-bugzilla.redhat.com" bzapi = bugzilla.Bugzilla(URL) # build_query is a helper function that handles some bugzilla version # incompatibility issues. All it does is return a properly formatted # dict(), and provide friendly parameter names. The param names map # to those accepted by XMLRPC Bug.search: # https://bugzilla.readthedocs.io/en/latest/api/core/v1/bug.html#search-bugs query = bzapi.build_query( product="Fedora", component="python-bugzilla") # Since 'query' is just a dict, you could set your own parameters too, like # if your bugzilla had a custom field. This will set 'status' for example, # but for common opts it's better to use build_query query["status"] = "CLOSED" # query() is what actually performs the query. it's a wrapper around Bug.search t1 = time.time() bugs = bzapi.query(query) t2 = time.time() print("Found %d bugs with our query" % len(bugs)) print("Query processing time: %s" % (t2 - t1)) # Depending on the size of your query, you can massively speed things up # by telling bugzilla to only return the fields you care about, since a # large chunk of the return time is transmitting the extra bug data. You # tweak this with include_fields: # https://wiki.mozilla.org/Bugzilla:BzAPI#Field_Control # Bugzilla will only return those fields listed in include_fields. query = bzapi.build_query( product="Fedora", component="python-bugzilla", include_fields=["id", "summary"]) t1 = time.time() bugs = bzapi.query(query) t2 = time.time() print("Quicker query processing time: %s" % (t2 - t1)) # bugzilla.redhat.com, and bugzilla >= 5.0 support queries using the same # format as is used for 'advanced' search URLs via the Web UI. For example, # I go to partner-bugzilla.redhat.com -> Search -> Advanced Search, select # Classification=Fedora # Product=Fedora # Component=python-bugzilla # Unselect all bug statuses (so, all status values) # Under Custom Search # Creation date -- is less than or equal to -- 2010-01-01 # # Run that, copy the URL and bring it here, pass it to url_to_query to # convert it to a dict(), and query as usual query = bzapi.url_to_query("https://partner-bugzilla.redhat.com/" "buglist.cgi?classification=Fedora&component=python-bugzilla&" "f1=creation_ts&o1=lessthaneq&order=Importance&product=Fedora&" "query_format=advanced&v1=2010-01-01") query["include_fields"] = ["id", "summary"] bugs = bzapi.query(query) print("The URL query returned 22 bugs... " "I know that without even checking because it shouldn't change!... " "(count is %d)" % len(bugs)) # One note about querying... you can get subtley different results if # you are not logged in. Depending on your bugzilla setup it may not matter, # but if you are dealing with private bugs, check bzapi.logged_in setting # to ensure your cached credentials are up to date. See update.py for # an example usage
abn/python-bugzilla
examples/query.py
Python
gpl-2.0
3,441
/* Initialize */ var isMobile = { Android: function() { return navigator.userAgent.match(/Android/i); }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function() { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function() { return navigator.userAgent.match(/IEMobile/i); }, any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; jQuery(document).ready(function ($) { // Bootstrap Init $("[rel=tooltip]").tooltip(); $('[data-toggle=tooltip]').tooltip(); $("[rel=popover]").popover(); $('#authorTab a').click(function (e) {e.preventDefault(); $(this).tab('show'); }); $('.sc_tabs a').click(function (e) {e.preventDefault(); $(this).tab('show'); }); $(".videofit").fitVids(); $(".embed-youtube").fitVids(); $('.kad-select').customSelect(); $('.woocommerce-ordering select').customSelect(); $('.collapse-next').click(function (e) { //e.preventDefault(); var $target = $(this).siblings('.sf-dropdown-menu'); if($target.hasClass('in') ) { $target.collapse('toggle'); $(this).removeClass('toggle-active'); } else { $target.collapse('toggle'); $(this).addClass('toggle-active'); } }); // Lightbox function kt_check_images( index, element ) { return /(png|jpg|jpeg|gif|tiff|bmp)$/.test( $( element ).attr( 'href' ).toLowerCase().split( '?' )[0].split( '#' )[0] ); } function kt_find_images() { $( 'a[href]' ).filter( kt_check_images ).attr( 'data-rel', 'lightbox' ); } kt_find_images(); $.extend(true, $.magnificPopup.defaults, { tClose: '', tLoading: light_load, // Text that is displayed during loading. Can contain %curr% and %total% keys gallery: { tPrev: '', // Alt text on left arrow tNext: '', // Alt text on right arrow tCounter: light_of // Markup for "1 of 7" counter }, image: { tError: light_error, // Error message when image could not be loaded titleSrc: function(item) { return item.el.find('img').attr('alt'); } } }); $("a[rel^='lightbox']").magnificPopup({type:'image'}); $("a[data-rel^='lightbox']").magnificPopup({type:'image'}); $('.kad-light-gallery').each(function(){ $(this).find('a[rel^="lightbox"]').magnificPopup({ type: 'image', gallery: { enabled:true }, image: { titleSrc: 'title' } }); }); $('.kad-light-gallery').each(function(){ $(this).find("a[data-rel^='lightbox']").magnificPopup({ type: 'image', gallery: { enabled:true }, image: { titleSrc: 'title' } }); }); $('.kad-light-wp-gallery').each(function(){ $(this).find('a[rel^="lightbox"]').magnificPopup({ type: 'image', gallery: { enabled:true }, image: { titleSrc: function(item) { return item.el.find('img').attr('alt'); } } }); }); $('.kad-light-wp-gallery').each(function(){ $(this).find("a[data-rel^='lightbox']").magnificPopup({ type: 'image', gallery: { enabled:true }, image: { titleSrc: function(item) { return item.el.find('img').attr('alt'); } } }); }); //Superfish Menu $('ul.sf-menu').superfish({ delay: 200, // one second delay on mouseout animation: {opacity:'show',height:'show'}, // fade-in and slide-down animation speed: 'fast' // faster animation speed }); function kad_fullwidth_panel() { var margins = $(window).width() - $('#content').width(); $('.panel-row-style-wide-feature').each(function(){ $(this).css({'padding-left': margins/2 + 'px'}); $(this).css({'padding-right': margins/2 + 'px'}); $(this).css({'margin-left': '-' + margins/2 + 'px'}); $(this).css({'margin-right': '-' + margins/2 + 'px'}); $(this).css({'visibility': 'visible'}); }); } kad_fullwidth_panel(); $(window).on("debouncedresize", function( event ) {kad_fullwidth_panel();}); //init Flexslider $('.kt-flexslider').each(function(){ var flex_speed = $(this).data('flex-speed'), flex_animation = $(this).data('flex-animation'), flex_animation_speed = $(this).data('flex-anim-speed'), flex_auto = $(this).data('flex-auto'); $(this).flexslider({ animation:flex_animation, animationSpeed: flex_animation_speed, slideshow: flex_auto, slideshowSpeed: flex_speed, start: function ( slider ) { slider.removeClass( 'loading' ); } }); }); //init masonry $('.init-masonry').each(function(){ var masonrycontainer = $(this), masonry_selector = $(this).data('masonry-selector'); masonrycontainer.imagesLoadedn( function(){ masonrycontainer.masonry({itemSelector: masonry_selector}); }); }); //init carousel jQuery('.initcaroufedsel').each(function(){ var container = jQuery(this); var wcontainerclass = container.data('carousel-container'), cspeed = container.data('carousel-speed'), ctransition = container.data('carousel-transition'), cauto = container.data('carousel-auto'), carouselid = container.data('carousel-id'), ss = container.data('carousel-ss'), xs = container.data('carousel-xs'), sm = container.data('carousel-sm'), md = container.data('carousel-md'); var wcontainer = jQuery(wcontainerclass); function getUnitWidth() {var width; if(jQuery(window).width() <= 540) { width = wcontainer.width() / ss; } else if(jQuery(window).width() <= 768) { width = wcontainer.width() / xs; } else if(jQuery(window).width() <= 990) { width = wcontainer.width() / sm; } else { width = wcontainer.width() / md; } return width; } function setWidths() { var unitWidth = getUnitWidth() -1; container.children().css({ width: unitWidth }); } setWidths(); function initCarousel() { container.carouFredSel({ scroll: {items:1, easing: "swing", duration: ctransition, pauseOnHover : true}, auto: {play: cauto, timeoutDuration: cspeed}, prev: '#prevport-'+carouselid, next: '#nextport-'+carouselid, pagination: false, swipe: true, items: {visible: null} }); } container.imagesLoadedn( function(){ initCarousel(); }); wcontainer.animate({'opacity' : 1}); jQuery(window).on("debouncedresize", function( event ) { container.trigger("destroy"); setWidths(); initCarousel(); }); }); //init carouselslider jQuery('.initcarouselslider').each(function(){ var container = jQuery(this); var wcontainerclass = container.data('carousel-container'), cspeed = container.data('carousel-speed'), ctransition = container.data('carousel-transition'), cauto = container.data('carousel-auto'), carouselid = container.data('carousel-id'), carheight = container.data('carousel-height'), align = 'center'; var wcontainer = jQuery(wcontainerclass); function setWidths() { var unitWidth = container.width(); container.children().css({ width: unitWidth }); if(jQuery(window).width() <= 768) { carheight = null; container.children().css({ height: 'auto' }); } } setWidths(); function initCarouselslider() { container.carouFredSel({ width: '100%', height: carheight, align: align, auto: {play: cauto, timeoutDuration: cspeed}, scroll: {items : 1,easing: 'quadratic'}, items: {visible: 1,width: 'variable'}, prev: '#prevport-'+carouselid, next: '#nextport-'+carouselid, swipe: {onMouse: false,onTouch: true}, }); } container.imagesLoadedn( function(){ initCarouselslider(); wcontainer.animate({'opacity' : 1}); wcontainer.css({ height: 'auto' }); wcontainer.parent().removeClass('loading'); }); jQuery(window).on("debouncedresize", function( event ) { container.trigger("destroy"); setWidths(); initCarouselslider(); }); }); }); if( isMobile.any() ) { jQuery(document).ready(function ($) { $('.caroufedselclass').tswipe({ excludedElements:"button, input, select, textarea, .noSwipe", tswipeLeft: function() { $('.caroufedselclass').trigger('next', 1); }, tswipeRight: function() { $('.caroufedselclass').trigger('prev', 1); }, tap: function(event, target) { window.open(jQuery(target).closest('.grid_item').find('a').attr('href'), '_self'); } }); }); }
BellarmineBTDesigns/mashariki
wp-content/themes/pinnacle/assets/js/kt_main.js
JavaScript
gpl-2.0
9,445
<!DOCTYPE html> <html><head> <meta http-equiv="content-type" content="text/html; charset=windows-1252"> <meta charset="US-ASCII"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>ASN.1 JavaScript decoder</title> <link rel="stylesheet" href="ASN.1%20JavaScript%20decoder_files/index.css" type="text/css"> <script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/hex.js"></script> <script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/base64.js"></script> <script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/oids.js"></script> <script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/int10.js"></script> <script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/asn1.js"></script> <script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/dom.js"></script> <script type="text/javascript" src="ASN.1%20JavaScript%20decoder_files/index.js"></script> </head> <body> <h1>ASN.1 JavaScript decoder</h1> <div style="position: relative; padding-bottom: 1em;"> <div id="dump" style="position: absolute; right: 0px;"></div> <div id="tree"></div> </div> <form> <textarea id="pem" style="width: 100%;" rows="8">MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIAwggHvMIIB WKADAgECAhAvoXazbunwSfREtACZZhlFMA0GCSqGSIb3DQEBBQUAMAwxCjAIBgNVBAMMAWEwHhcN MDgxMDE1MTUwMzQxWhcNMDkxMDE1MTUwMzQxWjAMMQowCAYDVQQDDAFhMIGfMA0GCSqGSIb3DQEB AQUAA4GNADCBiQKBgQCJUwlwhu5hR8X01f+vG0mKPRHsVRjpZNxSEmsmFPdDiD9kylE3ertTDf0g RkpIvWfNJ+eymuxoXF0Qgl5gXAVuSrjupGD6J+VapixJiwLXJHokmDihLs3zfGARz08O3qnO5ofB y0pRxq5isu/bAAcjoByZ1sI/g0iAuotC1UFObwIDAQABo1IwUDAOBgNVHQ8BAf8EBAMCBPAwHQYD VR0OBBYEFEIGXQB4h+04Z3y/n7Nv94+CqPitMB8GA1UdIwQYMBaAFEIGXQB4h+04Z3y/n7Nv94+C qPitMA0GCSqGSIb3DQEBBQUAA4GBAE0G7tAiaacJxvP3fhEj+yP9VDxL0omrRRAEaMXwWaBf/Ggk 1T/u+8/CDAdjuGNCiF6ctooKc8u8KpnZJsGqnpGQ4n6L2KjTtRUDh+hija0eJRBFdirPQe2HAebQ GFnmOk6Mn7KiQfBIsOzXim/bFqaBSbf06bLTQNwFouSO+jwOAAAxggElMIIBIQIBATAgMAwxCjAI BgNVBAMMAWECEC+hdrNu6fBJ9ES0AJlmGUUwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkq hkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTA4MTAxNTE1MDM0M1owIwYJKoZIhvcNAQkEMRYEFAAA AAAAAAAAAAAAAAAAAAAAAAAAMA0GCSqGSIb3DQEBAQUABIGAdB7ShyMGf5lVdZtvwKlnYLHMUqJW uBnFk7aQwHAmg3JnH6OcgId2F+xfg6twXm8hhUBkhHPlHGoWa5kQtN9n8rz3NorzvcM/1Xv9+0Ea l7NYSn2Hb0C0DMj2XNIYH2C6CLIHkmy1egzUvzsomZPTkx5nGDWm+8WHCjWb9A6lyrMAAAAAAAA= </textarea> <br> <label title="can be slow with big files"><input id="wantHex" checked="checked" type="checkbox"> with hex dump</label> <input value="decode" onclick="decodeArea();" type="button"> <input value="clear" onclick="clearAll();" type="button"> <input style="display: block;" id="file" type="file"> </form> <div id="help"> <h2>Instructions</h2> <p>This page contains a JavaScript generic ASN.1 parser that can decode any valid ASN.1 DER or BER structure whether Base64-encoded (raw base64, PEM armoring and <span class="tt">begin-base64</span> are recognized) or Hex-encoded. </p> <p>This tool can be used online at the address <a href="http://lapo.it/asn1js/"><span class="tt">http://lapo.it/asn1js/</span></a> or offline, unpacking <a href="http://lapo.it/asn1js/asn1js.zip">the ZIP file</a> in a directory and opening <span class="tt">index.html</span> in a browser</p> <p>On the left of the page will be printed a tree representing the hierarchical structure, on the right side an hex dump will be shown. <br> Hovering on the tree highlights ancestry (the hovered node and all its ancestors get colored) and the position of the hovered node gets highlighted in the hex dump (with header and content in a different colors). <br> Clicking a node in the tree will hide its sub-nodes (collapsed nodes can be noticed because they will become <i>italic</i>).</p> <div class="license"> <h3>Copyright</h3> <div class="ref"><p class="hidden"> ASN.1 JavaScript decoder<br> Copyright © 2008-2014 Lapo Luchini &lt;lapo@lapo.it&gt;<br> <br> 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.<br> <br> 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. </p></div> <p>ASN.1 JavaScript decoder Copyright © 2008-2014 <a href="http://lapo.it/">Lapo Luchini</a>; released as <a href="http://opensource.org/licenses/isc-license.txt">opensource</a> under the <a href="http://en.wikipedia.org/wiki/ISC_licence">ISC license</a>.</p> </div> <p><span class="tt">OBJECT&nbsp;IDENTIFIER</span> values are recognized using data taken from Peter Gutmann's <a href="http://www.cs.auckland.ac.nz/%7Epgut001/#standards">dumpasn1</a> program.</p> <h3>Links</h3> <ul> <li><a href="http://lapo.it/asn1js/">official website</a></li> <li><a href="http://idf.lapo.it/p/asn1js/">InDefero tracker</a></li> <li><a href="https://github.com/lapo-luchini/asn1js">github mirror</a></li> <li><a href="https://www.ohloh.net/p/asn1js">Ohloh code stats</a></li> </ul> </div> </body></html>
vjeantet/goldap
doc/asn1js/ASN.1 JavaScript decoder.html
HTML
gpl-2.0
5,603
<?php /** * sh404SEF - SEO extension for Joomla! * * @author Yannick Gaultier * @copyright (c) Yannick Gaultier 2014 * @package sh404SEF * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @version 4.4.0.1725 * @date 2014-04-09 */ // Security check to ensure this file is being included by a parent file. if (!defined('_JEXEC')) die('Direct Access to this location is not allowed.'); $title = JText::_('COM_SH404SEF_ANALYTICS_REPORT_SOURCES') . '::' . JText::_('COM_SH404SEF_ANALYTICS_DATA_SOURCES_DESC_RAW'); ?> <div class="hasAnalyticsTip width-100" title="<?php echo $title; ?>"> <fieldset class="adminform"> <legend> <?php echo JText::_('COM_SH404SEF_ANALYTICS_REPORT_SOURCES') . JText::_( 'COM_SH404SEF_ANALYTICS_REPORT_BY_LABEL') . Sh404sefHelperAnalytics::getDataTypeTitle(); ?> </legend> <ul class="adminformlist"> <li> <div class="analytics-report-image"><img src="<?php echo $this->analytics->analyticsData->images['sources']; ?>" /></div> </li> </ul> </fieldset> </div>
LarsMog/elesbjerg.dk
administrator/components/com_sh404sef/views/analytics/tmpl/default_j2_sources.php
PHP
gpl-2.0
1,165
using System.IO; using Nequeo.Cryptography.Key.Utilities.IO; namespace Nequeo.Cryptography.Key.Asn1 { public class BerGenerator : Asn1Generator { private bool _tagged = false; private bool _isExplicit; private int _tagNo; protected BerGenerator( Stream outStream) : base(outStream) { } public BerGenerator( Stream outStream, int tagNo, bool isExplicit) : base(outStream) { _tagged = true; _isExplicit = isExplicit; _tagNo = tagNo; } public override void AddObject( Asn1Encodable obj) { new BerOutputStream(Out).WriteObject(obj); } public override Stream GetRawOutputStream() { return Out; } public override void Close() { WriteBerEnd(); } private void WriteHdr( int tag) { Out.WriteByte((byte) tag); Out.WriteByte(0x80); } protected void WriteBerHeader( int tag) { if (_tagged) { int tagNum = _tagNo | Asn1Tags.Tagged; if (_isExplicit) { WriteHdr(tagNum | Asn1Tags.Constructed); WriteHdr(tag); } else { if ((tag & Asn1Tags.Constructed) != 0) { WriteHdr(tagNum | Asn1Tags.Constructed); } else { WriteHdr(tagNum); } } } else { WriteHdr(tag); } } protected void WriteBerBody( Stream contentStream) { Streams.PipeAll(contentStream, Out); } protected void WriteBerEnd() { Out.WriteByte(0x00); Out.WriteByte(0x00); if (_tagged && _isExplicit) // write extra end for tag header { Out.WriteByte(0x00); Out.WriteByte(0x00); } } } }
drazenzadravec/nequeo
Source/Components/Cryptography/Nequeo.Cryptography/Nequeo.Cryptography.Key/asn1/BERGenerator.cs
C#
gpl-2.0
2,356
/* GStreamer * Copyright (C) <2009> Руслан Ижбулатов <lrn1986 _at_ gmail _dot_ com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/gst-i18n-plugin.h> #include "gstvideomeasure.h" #include "gstvideomeasure_ssim.h" #include "gstvideomeasure_collector.h" GstEvent * gst_event_new_measured (guint64 framenumber, GstClockTime timestamp, const gchar * metric, const GValue * mean, const GValue * lowest, const GValue * highest) { GstStructure *str = gst_structure_new (GST_EVENT_VIDEO_MEASURE, "event", G_TYPE_STRING, "frame-measured", "offset", G_TYPE_UINT64, framenumber, "timestamp", GST_TYPE_CLOCK_TIME, timestamp, "metric", G_TYPE_STRING, metric, NULL); gst_structure_set_value (str, "mean", mean); gst_structure_set_value (str, "lowest", lowest); gst_structure_set_value (str, "highest", highest); return gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, str); } static gboolean plugin_init (GstPlugin * plugin) { gboolean res; #ifdef ENABLE_NLS GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE, LOCALEDIR); bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); #endif res = gst_element_register (plugin, "ssim", GST_RANK_NONE, GST_TYPE_SSIM); res &= gst_element_register (plugin, "measurecollector", GST_RANK_NONE, GST_TYPE_MEASURE_COLLECTOR); return res; } GST_PLUGIN_DEFINE2 (GST_VERSION_MAJOR, GST_VERSION_MINOR, videomeasure, "Various video measurers", plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);
freedesktop-unofficial-mirror/gstreamer-sdk__gst-plugins-bad
gst/videomeasure/gstvideomeasure.c
C
gpl-2.0
2,378
<div class="wrap shopp"> <div class="icon32"></div> <?php shopp_admin_screen_tabs(); do_action('shopp_admin_notices'); ?> <?php if (count(shopp_setting('target_markets')) == 0) echo '<div class="error"><p>'.__('No target markets have been selected in your store setup.','Shopp').'</p></div>'; ?> <?php $this->taxes_menu(); ?> <form action="<?php echo esc_url($this->url); ?>" id="taxrates" method="post" enctype="multipart/form-data" accept="text/plain,text/xml"> <div> <?php wp_nonce_field('shopp-settings-taxrates'); ?> </div> <div class="tablenav"> <div class="actions"> <button type="submit" name="addrate" id="addrate" class="button-secondary" tabindex="9999" <?php if (empty($countries)) echo 'disabled="disabled"'; ?>><?php _e('Add Tax Rate','Shopp'); ?></button> </div> </div> <script id="property-menu" type="text/x-jquery-tmpl"><?php $propertymenu = array( 'product-name' => __('Product name is','Shopp'), 'product-tags' => __('Product is tagged','Shopp'), 'product-category' => __('Product in category','Shopp'), 'customer-type' => __('Customer type is','Shopp') ); echo Shopp::menuoptions($propertymenu,false,true); ?></script> <script id="countries-menu" type="text/x-jquery-tmpl"><?php echo Shopp::menuoptions($countries,false,true); ?></script> <script id="conditional" type="text/x-jquery-tmpl"> <?php ob_start(); ?> <li> <?php echo ShoppUI::button('delete','deleterule'); ?> <select name="settings[taxrates][${id}][rules][${ruleid}][p]" class="property">${property_menu}</select>&nbsp;<input type="text" name="settings[taxrates][${id}][rules][${ruleid}][v]" size="25" class="value" value="${rulevalue}" /> <?php echo ShoppUI::button('add','addrule'); ?></li> <?php $conditional = ob_get_contents(); ob_end_clean(); echo str_replace(array("\n","\t"),'',$conditional); ?> </script> <script id="localrate" type="text/x-jquery-tmpl"> <?php ob_start(); ?> <li><label title="${localename}"><input type="text" name="settings[taxrates][${id}][locals][${localename}]" size="6" value="${localerate}" />&nbsp;${localename}</label></li> <?php $localrateui = ob_get_contents(); ob_end_clean(); echo $localrateui; ?> </script> <script id="editor" type="text/x-jquery-tmpl"> <?php ob_start(); ?> <tr class="inline-edit-row ${classnames}" id="${id}"> <td colspan="5"><input type="hidden" name="id" value="${id}" /><input type="hidden" name="editing" value="true" /> <table id="taxrate-editor"> <tr> <td scope="row" valign="top" class="rate"><input type="text" name="settings[taxrates][${id}][rate]" id="tax-rate" value="${rate}" size="7" class="selectall" tabindex="1" /><br /><label for="tax-rate"><?php _e('Tax Rate','Shopp'); ?></label><br /> <input type="hidden" name="settings[taxrates][${id}][compound]" value="off" /><label><input type="checkbox" id="tax-compound" name="settings[taxrates][${id}][compound]" value="on" ${compounded} tabindex="4" />&nbsp;<?php Shopp::_e('Compound'); ?></label></td> <td scope="row" class="conditions"> <select name="settings[taxrates][${id}][country]" class="country" tabindex="2">${countries}</select><select name="settings[taxrates][${id}][zone]" class="zone no-zones" tabindex="3">${zones}</select> <?php echo ShoppUI::button('add','addrule'); ?> <?php $options = array('any' => Shopp::__('any'), 'all' => strtolower(Shopp::__('All'))); $menu = '<select name="settings[taxrates][${id}][logic]" class="logic">'.menuoptions($options,false,true).'</select>'; ?> <div class="conditionals no-conditions"> <p><label><?php printf(__('Apply tax rate when %s of the following conditions match','Shopp'),$menu); ?>:</label></p> <ul> ${conditions} </ul> </div> </td> <td> <div class="local-rates panel subpanel no-local-rates"> <div class="label"><label><?php _e('Local Rates','Shopp'); echo ShoppAdmin()->boxhelp('settings-taxes-localrates'); ?> <span class="counter"></span><input type="hidden" name="settings[taxrates][${id}][haslocals]" value="${haslocals}" class="has-locals" /></label></div> <div class="ui"> <p class="instructions"><?php Shopp::_e('No local regions have been setup for this location. Local regions can be specified by uploading a formatted local rates file.'); ?></p> ${errors} <ul>${localrates}</ul> <div class="upload"> <h3><?php Shopp::_e('Upload Local Tax Rates'); ?></h3> <input type="hidden" name="MAX_FILE_SIZE" value="1048576" /> <input type="file" name="ratefile" class="hide-if-js" /> <button type="submit" name="upload" class="button-secondary upload"><?php Shopp::_e('Upload'); ?></button> </div> </div> </div> </td> </tr> <tr> <td colspan="3"> <p class="textright"> <a href="<?php echo $this->url; ?>" class="button-secondary cancel alignleft"><?php Shopp::_e('Cancel'); ?></a> <button type="submit" name="add-locals" class="button-secondary locals-toggle add-locals has-local-rates"><?php Shopp::_e('Add Local Rates'); ?></button> <button type="submit" name="remove-locals" class="button-secondary locals-toggle rm-locals no-local-rates"><?php Shopp::_e('Remove Local Rates'); ?></button> <input type="submit" class="button-primary" name="submit" value="<?php Shopp::_e('Save Changes'); ?>" /> </p> </td> </tr> </table> </td> </tr> <?php $editor = ob_get_contents(); ob_end_clean(); echo str_replace(array("\n","\t"),'',$editor); ?> </script> <table class="widefat" cellspacing="0"> <thead> <tr><?php print_column_headers('shopp_page_shopp-settings-taxrates'); ?></tr> </thead> <tfoot> <tr><?php print_column_headers('shopp_page_shopp-settings-taxrates',false); ?></tr> </tfoot> <tbody id="taxrates-table" class="list"> <?php if ($edit !== false && !isset($rates[$edit])) { $defaults = array( 'rate' => 0, 'country' => false, 'zone' => false, 'rules' => array(), 'locals' => array(), 'haslocals' => false, 'compound' => false ); extract($defaults); echo ShoppUI::template($editor,array( '${id}' => $edit, '${rate}' => percentage($rate,array('precision'=>4)), '${countries}' => menuoptions($countries,$country,true), '${zones}' => !empty($zones[$country])?menuoptions($zones[$country],$zone,true):'', '${conditions}' => join('',$conditions), '${haslocals}' => $haslocals, '${localrates}' => join('',$localrates), '${instructions}' => $localerror ? '<p class="error">'.$localerror.'</p>' : $instructions, '${compounded}' => Shopp::str_true($compound) ? 'checked="checked"' : '' )); } if (count($rates) == 0 && $edit === false): ?> <tr id="no-taxrates"><td colspan="5"><?php _e('No tax rates, yet.','Shopp'); ?></td></tr> <?php endif; $hidden = get_hidden_columns('shopp_page_shopp-settings-taxrates'); $even = false; foreach ($rates as $index => $taxrate): $defaults = array( 'rate' => 0, 'country' => false, 'zone' => false, 'rules' => array(), 'locals' => array(), 'haslocals' => false ); $taxrate = array_merge($defaults,$taxrate); extract($taxrate); $rate = Shopp::percentage(Shopp::floatval($rate), array('precision'=>4)); $location = $countries[ $country ]; if (isset($zone) && !empty($zone)) $location = $zones[$country][$zone].", $location"; $editurl = wp_nonce_url(add_query_arg(array('id'=>$index),$this->url)); $deleteurl = wp_nonce_url(add_query_arg(array('delete'=>$index),$this->url),'shopp_delete_taxrate'); $classes = array(); if (!$even) $classes[] = 'alternate'; $even = !$even; if ($edit !== false && $edit === $index) { $conditions = array(); foreach ($rules as $ruleid => $rule) { $condition_template_data = array( '${id}' => $edit, '${ruleid}' => $ruleid, '${property_menu}' => menuoptions($propertymenu,$rule['p'],true), '${rulevalue}' => esc_attr($rule['v']) ); $conditions[] = str_replace(array_keys($condition_template_data),$condition_template_data,$conditional); } $localrates = array(); foreach ($locals as $localename => $localerate) { $localrateui_data = array( '${id}' => $edit, '${localename}' => $localename, '${localerate}' => (float)$localerate, ); $localrates[] = str_replace(array_keys($localrateui_data),$localrateui_data,$localrateui); } $data = array( '${id}' => $edit, '${rate}' => $rate, '${countries}' => menuoptions($countries,$country,true), '${zones}' => !empty($zones[$country])?menuoptions(array_merge(array(''=>''),$zones[$country]),$zone,true):'', '${conditions}' => join('',$conditions), '${haslocals}' => $haslocals, '${localrates}' => join('',$localrates), '${errors}' => $localerror ? '<p class="error">'.$localerror.'</p>' : '', '${compounded}' => Shopp::str_true($compound) ? 'checked="checked"' : '', '${cancel_href}' => $this->url ); if ($conditions) $data['no-conditions'] = ''; if (!empty($zones[$country])) $data['no-zones'] = ''; if ($haslocals) $data['no-local-rates'] = ''; else $data['has-local-rates'] = ''; if (count($locals) > 0) $data['instructions'] = 'hidden'; echo ShoppUI::template($editor,$data); if ($edit === $index) continue; } $label = "$rate &mdash; $location"; ?> <tr class="<?php echo join(' ',$classes); ?>" id="taxrates-<?php echo $index; ?>"> <td class="name column-name"><a href="<?php echo esc_url($editurl); ?>" title="<?php _e('Edit','Shopp'); ?> &quot;<?php echo esc_attr($rate); ?>&quot;" class="edit row-title"><?php echo esc_html($label); ?></a> <div class="row-actions"> <span class='edit'><a href="<?php echo esc_url($editurl); ?>" title="<?php _e('Edit','Shopp'); ?> &quot;<?php echo esc_attr($label); ?>&quot;" class="edit"><?php _e('Edit','Shopp'); ?></a> | </span><span class='delete'><a href="<?php echo esc_url($deleteurl); ?>" title="<?php _e('Delete','Shopp'); ?> &quot;<?php echo esc_attr($label); ?>&quot;" class="delete"><?php _e('Delete','Shopp'); ?></a></span> </div> </td> <td class="local column-local"> <div class="checkbox <?php if ( $haslocals ) echo 'checked'; ?>">&nbsp;</div> </td> <td class="conditional column-conditional"> <div class="checkbox <?php if ( count($rules) > 0 ) echo 'checked'; ?>">&nbsp;</div> </td> </tr> <?php endforeach; ?> </tbody> </table> </form> </div> <script type="text/javascript"> /* <![CDATA[ */ var suggurl = '<?php echo wp_nonce_url(admin_url('admin-ajax.php'),'wp_ajax_shopp_suggestions'); ?>', rates = <?php echo json_encode($rates); ?>, base = <?php echo json_encode($base); ?>, zones = <?php echo json_encode($zones); ?>, localities = <?php echo json_encode(Lookup::localities()); ?>, taxrates = []; /* ]]> */ </script>
sharpmachine/greaterworkshealing.com
wp-content/plugins/shopp/core/ui/settings/taxrates.php
PHP
gpl-2.0
10,968
/******************************************************************************/ /* Mednafen Fast SNES Emulation Module */ /******************************************************************************/ /* input.cpp: ** Copyright (C) 2015-2019 Mednafen Team ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of the GNU General Public License ** as published by the Free Software Foundation; either version 2 ** of the License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software Foundation, Inc., ** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "snes.h" #include "input.h" namespace MDFN_IEN_SNES_FAUST { class InputDevice { public: InputDevice() MDFN_COLD; virtual ~InputDevice() MDFN_COLD; virtual void Power(void) MDFN_COLD; virtual void MDFN_FASTCALL UpdatePhysicalState(const uint8* data); virtual uint8 MDFN_FASTCALL Read(bool IOB) MDFN_HOT; virtual void MDFN_FASTCALL SetLatch(bool state) MDFN_HOT; virtual void StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix); }; InputDevice::InputDevice() { } InputDevice::~InputDevice() { } void InputDevice::Power(void) { } void InputDevice::UpdatePhysicalState(const uint8* data) { } uint8 InputDevice::Read(bool IOB) { return 0; } void InputDevice::SetLatch(bool state) { } void InputDevice::StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix) { } class InputDevice_MTap final : public InputDevice { public: InputDevice_MTap() MDFN_COLD; virtual ~InputDevice_MTap() override MDFN_COLD; virtual void Power(void) override MDFN_COLD; virtual uint8 MDFN_FASTCALL Read(bool IOB) override MDFN_HOT; virtual void MDFN_FASTCALL SetLatch(bool state) override MDFN_HOT; virtual void StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix) override; void SetSubDevice(const unsigned mport, InputDevice* device); private: InputDevice* MPorts[4]; bool pls; }; void InputDevice_MTap::Power(void) { for(unsigned mport = 0; mport < 4; mport++) MPorts[mport]->Power(); } void InputDevice_MTap::StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix) { SFORMAT StateRegs[] = { SFVAR(pls), SFEND }; char sname[64] = "MT_"; strncpy(sname + 3, sname_prefix, sizeof(sname) - 3); sname[sizeof(sname) - 1] = 0; if(!MDFNSS_StateAction(sm, load, data_only, StateRegs, sname, true) && load) Power(); else { for(unsigned mport = 0; mport < 4; mport++) { sname[2] = '0' + mport; MPorts[mport]->StateAction(sm, load, data_only, sname); } if(load) { } } } InputDevice_MTap::InputDevice_MTap() { for(unsigned mport = 0; mport < 4; mport++) MPorts[mport] = nullptr; pls = false; } InputDevice_MTap::~InputDevice_MTap() { } uint8 InputDevice_MTap::Read(bool IOB) { uint8 ret; ret = ((MPorts[(!IOB << 1) + 0]->Read(false) & 0x1) << 0) | ((MPorts[(!IOB << 1) + 1]->Read(false) & 0x1) << 1); if(pls) ret = 0x2; return ret; } void InputDevice_MTap::SetLatch(bool state) { for(unsigned mport = 0; mport < 4; mport++) MPorts[mport]->SetLatch(state); pls = state; } void InputDevice_MTap::SetSubDevice(const unsigned mport, InputDevice* device) { MPorts[mport] = device; } class InputDevice_Gamepad final : public InputDevice { public: InputDevice_Gamepad() MDFN_COLD; virtual ~InputDevice_Gamepad() override MDFN_COLD; virtual void Power(void) override MDFN_COLD; virtual void MDFN_FASTCALL UpdatePhysicalState(const uint8* data) override; virtual uint8 MDFN_FASTCALL Read(bool IOB) override MDFN_HOT; virtual void MDFN_FASTCALL SetLatch(bool state) override MDFN_HOT; virtual void StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix) override; private: uint16 buttons; uint32 latched; bool pls; }; InputDevice_Gamepad::InputDevice_Gamepad() { pls = false; buttons = 0; } InputDevice_Gamepad::~InputDevice_Gamepad() { } void InputDevice_Gamepad::StateAction(StateMem* sm, const unsigned load, const bool data_only, const char* sname_prefix) { SFORMAT StateRegs[] = { SFVAR(buttons), SFVAR(latched), SFVAR(pls), SFEND }; char sname[64] = "GP_"; strncpy(sname + 3, sname_prefix, sizeof(sname) - 3); sname[sizeof(sname) - 1] = 0; //printf("%s\n", sname); if(!MDFNSS_StateAction(sm, load, data_only, StateRegs, sname, true) && load) Power(); else if(load) { } } void InputDevice_Gamepad::Power(void) { latched = ~0U; } void InputDevice_Gamepad::UpdatePhysicalState(const uint8* data) { buttons = MDFN_de16lsb(data); if(pls) latched = buttons | 0xFFFF0000; } uint8 InputDevice_Gamepad::Read(bool IOB) { uint8 ret = latched & 1; if(!pls) latched = (int32)latched >> 1; return ret; } void InputDevice_Gamepad::SetLatch(bool state) { if(pls && !state) latched = buttons | 0xFFFF0000; pls = state; } // // // // // static struct { InputDevice_Gamepad gamepad; } PossibleDevices[8]; static InputDevice NoneDevice; static InputDevice_MTap PossibleMTaps[2]; static bool MTapEnabled[2]; // Mednafen virtual static InputDevice* Devices[8]; static uint8* DeviceData[8]; // SNES physical static InputDevice* Ports[2]; static uint8 WRIO; static bool JoyLS; static uint8 JoyARData[8]; static DEFREAD(Read_JoyARData) { if(MDFN_UNLIKELY(DBG_InHLRead)) { return JoyARData[A & 0x7]; } CPUM.timestamp += MEMCYC_FAST; //printf("Read: %08x\n", A); return JoyARData[A & 0x7]; } static DEFREAD(Read_4016) { if(MDFN_UNLIKELY(DBG_InHLRead)) { return CPUM.mdr & 0xFC; // | TODO! } CPUM.timestamp += MEMCYC_XSLOW; uint8 ret = CPUM.mdr & 0xFC; ret |= Ports[0]->Read(WRIO & (0x40 << 0)); //printf("Read 4016: %02x\n", ret); return ret; } static DEFWRITE(Write_4016) { CPUM.timestamp += MEMCYC_XSLOW; JoyLS = V & 1; for(unsigned sport = 0; sport < 2; sport++) Ports[sport]->SetLatch(JoyLS); //printf("Write 4016: %02x\n", V); } static DEFREAD(Read_4017) { if(MDFN_UNLIKELY(DBG_InHLRead)) { return (CPUM.mdr & 0xE0) | 0x1C; // | TODO! } CPUM.timestamp += MEMCYC_XSLOW; uint8 ret = (CPUM.mdr & 0xE0) | 0x1C; ret |= Ports[1]->Read(WRIO & (0x40 << 1)); //printf("Read 4017: %02x\n", ret); return ret; } static DEFWRITE(Write_WRIO) { CPUM.timestamp += MEMCYC_FAST; WRIO = V; } static DEFREAD(Read_4213) { if(MDFN_UNLIKELY(DBG_InHLRead)) { return WRIO; } CPUM.timestamp += MEMCYC_FAST; return WRIO; } void INPUT_AutoRead(void) { for(unsigned sport = 0; sport < 2; sport++) { Ports[sport]->SetLatch(true); Ports[sport]->SetLatch(false); unsigned ard[2] = { 0 }; for(unsigned b = 0; b < 16; b++) { uint8 rv = Ports[sport]->Read(WRIO & (0x40 << sport)); ard[0] = (ard[0] << 1) | ((rv >> 0) & 1); ard[1] = (ard[1] << 1) | ((rv >> 1) & 1); } for(unsigned ai = 0; ai < 2; ai++) MDFN_en16lsb(&JoyARData[sport * 2 + ai * 4], ard[ai]); } JoyLS = false; } static MDFN_COLD void MapDevices(void) { for(unsigned sport = 0, vport = 0; sport < 2; sport++) { if(MTapEnabled[sport]) { Ports[sport] = &PossibleMTaps[sport]; for(unsigned mport = 0; mport < 4; mport++) PossibleMTaps[sport].SetSubDevice(mport, Devices[vport++]); } else Ports[sport] = Devices[vport++]; } } void INPUT_Init(void) { for(unsigned bank = 0x00; bank < 0x100; bank++) { if(bank <= 0x3F || (bank >= 0x80 && bank <= 0xBF)) { Set_A_Handlers((bank << 16) | 0x4016, Read_4016, Write_4016); Set_A_Handlers((bank << 16) | 0x4017, Read_4017, OBWrite_XSLOW); Set_A_Handlers((bank << 16) | 0x4201, OBRead_FAST, Write_WRIO); Set_A_Handlers((bank << 16) | 0x4213, Read_4213, OBWrite_FAST); Set_A_Handlers((bank << 16) | 0x4218, (bank << 16) | 0x421F, Read_JoyARData, OBWrite_FAST); } } for(unsigned vport = 0; vport < 8; vport++) { DeviceData[vport] = nullptr; Devices[vport] = &NoneDevice; } for(unsigned sport = 0; sport < 2; sport++) for(unsigned mport = 0; mport < 4; mport++) PossibleMTaps[sport].SetSubDevice(mport, &NoneDevice); MTapEnabled[0] = MTapEnabled[1] = false; MapDevices(); } void INPUT_SetMultitap(const bool (&enabled)[2]) { for(unsigned sport = 0; sport < 2; sport++) { if(enabled[sport] != MTapEnabled[sport]) { PossibleMTaps[sport].SetLatch(JoyLS); PossibleMTaps[sport].Power(); MTapEnabled[sport] = enabled[sport]; } } MapDevices(); } void INPUT_Kill(void) { } void INPUT_Reset(bool powering_up) { JoyLS = false; for(unsigned sport = 0; sport < 2; sport++) Ports[sport]->SetLatch(JoyLS); memset(JoyARData, 0x00, sizeof(JoyARData)); if(powering_up) { WRIO = 0xFF; for(unsigned sport = 0; sport < 2; sport++) Ports[sport]->Power(); } } void INPUT_Set(unsigned vport, const char* type, uint8* ptr) { InputDevice* nd = &NoneDevice; DeviceData[vport] = ptr; if(!strcmp(type, "gamepad")) nd = &PossibleDevices[vport].gamepad; else if(strcmp(type, "none")) abort(); if(Devices[vport] != nd) { Devices[vport] = nd; Devices[vport]->SetLatch(JoyLS); Devices[vport]->Power(); } MapDevices(); } void INPUT_StateAction(StateMem* sm, const unsigned load, const bool data_only) { SFORMAT StateRegs[] = { SFVAR(JoyARData), SFVAR(JoyLS), SFVAR(WRIO), SFEND }; MDFNSS_StateAction(sm, load, data_only, StateRegs, "INPUT"); for(unsigned sport = 0; sport < 2; sport++) { char sprefix[32] = "PORTn"; sprefix[4] = '0' + sport; Ports[sport]->StateAction(sm, load, data_only, sprefix); } } void INPUT_UpdatePhysicalState(void) { for(unsigned vport = 0; vport < 8; vport++) Devices[vport]->UpdatePhysicalState(DeviceData[vport]); } static const IDIISG GamepadIDII = { IDIIS_ButtonCR("b", "B (center, lower)", 7, NULL), IDIIS_ButtonCR("y", "Y (left)", 6, NULL), IDIIS_Button("select", "SELECT", 4, NULL), IDIIS_Button("start", "START", 5, NULL), IDIIS_Button("up", "UP ↑", 0, "down"), IDIIS_Button("down", "DOWN ↓", 1, "up"), IDIIS_Button("left", "LEFT ←", 2, "right"), IDIIS_Button("right", "RIGHT →", 3, "left"), IDIIS_ButtonCR("a", "A (right)", 9, NULL), IDIIS_ButtonCR("x", "X (center, upper)", 8, NULL), IDIIS_Button("l", "Left Shoulder", 10, NULL), IDIIS_Button("r", "Right Shoulder", 11, NULL), }; static const std::vector<InputDeviceInfoStruct> InputDeviceInfo = { // None { "none", "none", NULL, IDII_Empty }, // Gamepad { "gamepad", "Gamepad", NULL, GamepadIDII }, }; const std::vector<InputPortInfoStruct> INPUT_PortInfo = { { "port1", "Virtual Port 1", InputDeviceInfo, "gamepad" }, { "port2", "Virtual Port 2", InputDeviceInfo, "gamepad" }, { "port3", "Virtual Port 3", InputDeviceInfo, "gamepad" }, { "port4", "Virtual Port 4", InputDeviceInfo, "gamepad" }, { "port5", "Virtual Port 5", InputDeviceInfo, "gamepad" }, { "port6", "Virtual Port 6", InputDeviceInfo, "gamepad" }, { "port7", "Virtual Port 7", InputDeviceInfo, "gamepad" }, { "port8", "Virtual Port 8", InputDeviceInfo, "gamepad" } }; }
libretro-mirrors/mednafen-git
src/snes_faust/input.cpp
C++
gpl-2.0
11,450
/* * CDE - Common Desktop Environment * * Copyright (c) 1993-2012, The Open Group. All rights reserved. * * These libraries and programs are free software; you can * redistribute them and/or modify them under the terms of the GNU * Lesser General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * These libraries and programs are distributed in the hope that * they 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 these librararies and programs; if not, write * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth * Floor, Boston, MA 02110-1301 USA */ /* $TOG: EditAreaData.c /main/6 1998/03/03 16:18:13 mgreess $ */ /**********************************<+>************************************* *************************************************************************** ** ** File: EditAreaData.c ** ** Project: DtEditor widget for editing services ** ** Description: Contains functions for getting and setting the data ** on which the editor operates. ** ----------- ** ******************************************************************* * * (c) Copyright 1993, 1994 Unix System Labs, Inc., a subsidiary of Novell, Inc. * (c) Copyright 1996 Digital Equipment Corporation. * (c) Copyright 1993, 1994, 1996 Hewlett-Packard Company. * (c) Copyright 1993, 1994, 1996 International Business Machines Corp. * (c) Copyright 1993, 1994, 1996 Sun Microsystems, Inc. * (c) Copyright 1996 Novell, Inc. * (c) Copyright 1996 FUJITSU LIMITED. * (c) Copyright 1996 Hitachi. * ******************************************************************** ** ** ************************************************************************** **********************************<+>*************************************/ #include "EditorP.h" #include <X11/Xutil.h> #include <Xm/TextP.h> #include <unistd.h> #include "DtWidgetI.h" typedef enum _LoadActionType { LOAD_DATA, INSERT_DATA, APPEND_DATA, REPLACE_DATA } LoadActionType; static DtEditorErrorCode Check4EnoughMemory( int numBytes); static DtEditorErrorCode StripEmbeddedNulls( char *stringData, int *length); static DtEditorErrorCode LoadFile( Widget w, char *fileName, LoadActionType action, XmTextPosition startReplace, XmTextPosition endReplace ); #ifdef NEED_STRCASECMP /* * in case strcasecmp is not provided by the system here is one * which does the trick */ static int strcasecmp(s1, s2) register char *s1, *s2; { register int c1, c2; while (*s1 && *s2) { c1 = isupper(*s1) ? tolower(*s1) : *s1; c2 = isupper(*s2) ? tolower(*s2) : *s2; if (c1 != c2) return (1); s1++; s2++; } if (*s1 || *s2) return (1); return (0); } #endif /***************************************************************************** * * Check4EnoughMemory - estimates whether there is enough memory to malloc * "numBytes" of memory. This routine doubles the amount needed because the * routines that use it are putting data into the text widget & we must make * sure the widget will have room, too. * * Returns DtEDITOR_NO_ERRORS * DtEDITOR_ILLEGAL_SIZE * DtEDITOR_INSUFFICIENT_MEMORY * *****************************************************************************/ static DtEditorErrorCode Check4EnoughMemory( int numBytes) { DtEditorErrorCode returnVal = DtEDITOR_ILLEGAL_SIZE; if (numBytes > 0) { char *tmpString = (char *)malloc((2 * numBytes) + (numBytes/10)); if(tmpString == (char *)NULL) returnVal = DtEDITOR_INSUFFICIENT_MEMORY; else { returnVal = DtEDITOR_NO_ERRORS; free(tmpString); } } return( returnVal ); } /* end Check4EnoughMemory */ /***************************************************************************** * * StripEmbeddedNulls - removes any embedded NULLs (\0) in a string of length * 'length'. The removal occurs in place, with 'length' set to the * new, stripped length. The resulting string is terminated with a * trailing NULL. * * Returns DtEDITOR_NO_ERRORS - the string did not contain any embedded NULLs * DtEDITOR_NULLS_REMOVED - the string did contain embedded * NULLs that were removed. * *****************************************************************************/ static DtEditorErrorCode StripEmbeddedNulls( char *stringData, int *length) { DtEditorErrorCode returnVal = DtEDITOR_NO_ERRORS; if (strlen(stringData) != *length) { int firstNull; returnVal = DtEDITOR_NULLS_REMOVED; /* * The file contains NULL characters, so we strip them out and * report that we have done so. */ while((firstNull = strlen(stringData)) != *length) { int lastNull = firstNull; while((lastNull + 1) < *length && stringData[lastNull + 1] == (char)'\0') lastNull++; memcpy(&stringData[firstNull], &stringData[lastNull + 1], *length - lastNull); *length -= 1 + lastNull - firstNull; } } return( returnVal); } /* end StripEmbeddedNulls */ /***************************************************************************** * * Retrieves the current location of the insert cursor * *****************************************************************************/ XmTextPosition DtEditorGetInsertionPosition( Widget widget) { DtEditorWidget editor = (DtEditorWidget) widget; XmTextPosition result; _DtWidgetToAppContext(widget); _DtAppLock(app); result = XmTextGetInsertionPosition(M_text(editor)); _DtAppUnlock(app); return result; } /***************************************************************************** * * Retrieves the current location of the last character in the widget * *****************************************************************************/ XmTextPosition DtEditorGetLastPosition( Widget widget) { DtEditorWidget editor = (DtEditorWidget) widget; XmTextPosition result; _DtWidgetToAppContext(widget); _DtAppLock(app); result = XmTextGetLastPosition(M_text(editor)); _DtAppUnlock(app); return result; } /***************************************************************************** * * Changes the current location of the insert cursor * *****************************************************************************/ void DtEditorSetInsertionPosition( Widget widget, XmTextPosition position) { DtEditorWidget editor = (DtEditorWidget) widget; _DtWidgetToAppContext(widget); _DtAppLock(app); XmTextSetInsertionPosition(M_text(editor), position); _DtAppUnlock(app); } static DtEditorErrorCode setStringValue( DtEditorWidget editor, char *data) { /* * Tell _DtEditorModifyVerifyCB() that we're replacing the entire * contents, so it doesn't try to save the current document in an * undo structure for a later undo. */ M_loadingAllNewData(editor) = True; XmTextSetString( M_text(editor), data ); /* * If the _DtEditorModifyVerifyCB() did not get called, reset the * things which usually get reset there. The modifyVerify callback * will not get called if the contents are being set to a null string * and the widget is already empty. */ if (M_loadingAllNewData(editor) == True) { M_loadingAllNewData(editor) = False; M_unreadChanges(editor) = False; _DtEditorResetUndo(editor); } return( DtEDITOR_NO_ERRORS ); } /* end setStringValue */ static DtEditorErrorCode setDataValue( DtEditorWidget widget, void *rawData, int length) { DtEditorErrorCode status = DtEDITOR_NULL_ITEM, tmpError; /* * Validate input */ if (rawData != (void *)NULL) { /* * Check to see if we have a valid buffer size & enough memory to * load the buffer into the text widget. This is only an estimate * of our needs. * Check4EnoughMemory() returns DtEDITOR_NO_ERRORS, * DtEDITOR_ILLEGAL_SIZE, or DtEDITOR_INSUFFICIENT_MEMORY. */ status = Check4EnoughMemory( length ); if (status == DtEDITOR_NO_ERRORS) { /* * Convert the data buffer into a string & insert into the widget */ char *textData = (char *)XtMalloc(length + 1); memcpy( textData, rawData, length ); textData[length] = '\0'; /* * Strip out any embedded NULLs because the text widget will only * accept data up to the first NULL. * * StripEmbeddedNulls() returns DtEDITOR_NO_ERRORS or * DtEDITOR_NULLS_REMOVED */ status = StripEmbeddedNulls( textData, &length ); /* * Now, insert the converted string into the text widget */ tmpError = setStringValue( widget, textData ); if (tmpError != DtEDITOR_NO_ERRORS) status = tmpError; XtFree( (char *)textData ); } } return( status ); } /* end setDataValue */ static DtEditorErrorCode setWcharValue( DtEditorWidget editor, wchar_t *data) { DtEditorErrorCode status; wchar_t *tmp_wc; int result, num_chars=0; char *mb_value = (char *)NULL; /* * Convert the wide char string to a multi-byte string & stick it in * the text widget. */ /* * Determine how big the resulting mb string may be */ for (num_chars = 0, tmp_wc = data; *tmp_wc != (wchar_t)0L; num_chars++) tmp_wc++; /* * Check to see if we have enough memory to load the string * into the text widget. This is only an estimate of our needs. * status will be set to DtEDITOR_NO_ERRORS, DtEDITOR_ILLEGAL_SIZE, or * DtEDITOR_INSUFFICIENT_MEMORY. */ status = Check4EnoughMemory( (num_chars + 1) * MB_CUR_MAX ); if (status != DtEDITOR_NO_ERRORS) return status; mb_value = XtMalloc( (unsigned)(num_chars + 1) * MB_CUR_MAX ); /* * Convert the wchar string * If wcstombs fails it returns (size_t) -1, so pass in empty * string. */ result = wcstombs( mb_value, data, (num_chars + 1) * MB_CUR_MAX ); if (result == (size_t)-1) result = 0; /* * wcstombs doesn't guarantee string is NULL terminated */ mb_value[result] = 0; status = setStringValue( editor, mb_value ); XtFree(mb_value); return( status ); } /* end setWcharValue */ static DtEditorErrorCode insertStringValue( DtEditorWidget editor, char *data, LoadActionType typeOfInsert, XmTextPosition beginInsert, XmTextPosition endInsert) { int numInserted; switch( typeOfInsert ) { case INSERT_DATA: { beginInsert = endInsert = XmTextGetInsertionPosition( M_text(editor) ); break; } case APPEND_DATA: { beginInsert = endInsert = XmTextGetLastPosition( M_text(editor) ); break; } case REPLACE_DATA: { break; } default: { } } /* end switch */ /* * Insert/Replace/Append the data and move the insertion cursor to * the end of the inserted data. */ numInserted = _DtEditor_CountCharacters( data, strlen(data) ); XmTextReplace(M_text(editor), beginInsert, endInsert, data); XmTextSetInsertionPosition( M_text(editor), (XmTextPosition)(beginInsert + numInserted) ); return( DtEDITOR_NO_ERRORS ); } /* insertStringValue */ static DtEditorErrorCode insertDataValue( DtEditorWidget widget, void *rawData, int length, LoadActionType typeOfInsert, XmTextPosition beginInsert, XmTextPosition endInsert) { DtEditorErrorCode status = DtEDITOR_NULL_ITEM, loadError; /* * Validate input */ if (rawData != (void *) NULL) { /* * Check to see if we have a valid buffer size & enough memory to * insert the buffer into the text widget. This is only an estimate * of our needs. * status will be set to DtEDITOR_NO_ERRORS, DtEDITOR_ILLEGAL_SIZE, or * DtEDITOR_INSUFFICIENT_MEMORY. */ status = Check4EnoughMemory( length ); if (status == DtEDITOR_NO_ERRORS) { /* * Convert the data buffer into a string & insert into the widget */ char *textData = (char *)XtMalloc(length + 1); memcpy( textData, rawData, length ); textData[length] = '\0'; /* * Strip out any embedded NULLs because the text widget will only * accept data up to the first NULL. * * StripEmbeddedNulls() returns DtEDITOR_NO_ERRORS or * DtEDITOR_NULLS_REMOVED */ status = StripEmbeddedNulls( textData, &length ); /* * Now, insert the converted string into the text widget */ loadError = insertStringValue( widget, textData, typeOfInsert, beginInsert, endInsert ); if (loadError != DtEDITOR_NO_ERRORS) status = loadError; XtFree( (char *)textData ); } } return( status ); } /* insertDataValue */ static DtEditorErrorCode insertWcharValue( DtEditorWidget editor, wchar_t *data, LoadActionType typeOfInsert, XmTextPosition beginInsert, XmTextPosition endInsert) { wchar_t *tmp_wc; int result, num_chars=0; char *mb_value = (char *)NULL; DtEditorErrorCode status; /* * Convert the wide char string to a multi-byte string & insert it into * the text widget. */ /* * Determine how big the resulting mb string may be */ for (num_chars = 0, tmp_wc = data; *tmp_wc != (wchar_t)0L; num_chars++) tmp_wc++; /* * Check to see if we have enough memory to insert the string * into the text widget. This is only an estimate of our needs. * status will be set to DtEDITOR_NO_ERRORS, DtEDITOR_ILLEGAL_SIZE, or * DtEDITOR_INSUFFICIENT_MEMORY. */ status = Check4EnoughMemory( (num_chars + 1) * MB_CUR_MAX ); if(status != DtEDITOR_NO_ERRORS) return status; mb_value = XtMalloc( (unsigned)(num_chars + 1) * MB_CUR_MAX ); /* * Convert the wchar string. * If wcstombs fails it returns (size_t) -1, so pass in empty * string. */ result = wcstombs( mb_value, data, (num_chars + 1) * MB_CUR_MAX ); if (result == (size_t)-1) result = 0; /* * wcstombs doesn't guarantee string is NULL terminated */ mb_value[result] = 0; status = insertStringValue( editor, mb_value, typeOfInsert, beginInsert, endInsert ); XtFree( mb_value ); return( status ); } /* insertWcharValue */ /*************************************************************************** * * DtEditorSetContents - sets the contents of the DtEditor widget. * * Inputs: widget to set the contents * * a data structure containing the data to put into the * widget. Depending upon the type of data being set, this * structure will contain various fields: * * string - \0-terminated string of characters * data - the data, the size of the data * * Returns 0 - contents were set sucessfully * !0 - an error occured while setting the contents * ***************************************************************************/ extern DtEditorErrorCode DtEditorSetContents( Widget widget, DtEditorContentRec *data ) { DtEditorErrorCode error = DtEDITOR_INVALID_TYPE; DtEditorWidget editor = (DtEditorWidget) widget; _DtWidgetToAppContext(widget); _DtAppLock(app); switch( data->type ) { case DtEDITOR_TEXT: { error = setStringValue ( editor, data->value.string ); break; } case DtEDITOR_DATA: { error = setDataValue ( editor, data->value.data.buf, data->value.data.length); break; } case DtEDITOR_WCHAR: { error = setWcharValue ( editor, data->value.wchar ); break; } default : { error = DtEDITOR_INVALID_TYPE; } } /* end switch */ /* * Update the current-line-display in the status line */ if (error == DtEDITOR_NO_ERRORS) _DtEditorUpdateLineDisplay(editor, 1, False ); _DtAppUnlock(app); return( error ); } /*************************************************************************** * * DtEditorSetContentsFromFile - read a data file, putting the contents * into a DtEditor widget. * * Inputs: widget to load the file into * * to indicate the type of contents loaded from the file: * string - a \0-terminated string of characters * data - untyped data * * filename - name of the file to read * * Returns 0 - contents were loaded sucessfully * !0 - an error occured while loading the contents * ***************************************************************************/ extern DtEditorErrorCode DtEditorSetContentsFromFile( Widget widget, char *fileName) { DtEditorErrorCode result; _DtWidgetToAppContext(widget); _DtAppLock(app); result = LoadFile(widget, fileName, LOAD_DATA, 0, 0); _DtAppUnlock(app); return result; } /*************************************************************************** * * DtEditorAppend - append data to the contents of the DtEditor widget. * * Inputs: widget to add to the contents * * a data structure containing the data to append to the * widget. Depending upon the type of data being set, this * structure will contain various fields: * * string - \0-terminated string of characters * data - the data, the size of the data * * Returns 0 - contents were set sucessfully * !0 - an error occured while setting the contents * ***************************************************************************/ extern DtEditorErrorCode DtEditorAppend( Widget widget, DtEditorContentRec *data ) { DtEditorErrorCode error = DtEDITOR_INVALID_TYPE; DtEditorWidget editor = (DtEditorWidget) widget; _DtWidgetToAppContext(widget); _DtAppLock(app); switch( data->type ) { case DtEDITOR_TEXT: { error = insertStringValue ( editor, data->value.string, APPEND_DATA, 0, 0 ); break; } case DtEDITOR_DATA: { error = insertDataValue ( editor, data->value.data.buf, data->value.data.length, APPEND_DATA, 0,0); break; } case DtEDITOR_WCHAR: { error = insertWcharValue ( editor, data->value.wchar, APPEND_DATA, 0, 0 ); break; } default: { error = DtEDITOR_INVALID_TYPE; } } /* end switch */ _DtAppUnlock(app); return( error ); } /*************************************************************************** * * DtEditorAppendFromFile - read a data file, appending the contents * into a DtEditor widget. * * Inputs: widget to append the file to * * to indicate the type of contents appended from the file: * string - a \0-terminated string of characters * data - untyped data * * filename - name of the file to read * * Returns 0 - contents were appended sucessfully * !0 - an error occured while appending the contents * ***************************************************************************/ extern DtEditorErrorCode DtEditorAppendFromFile( Widget widget, char *fileName) { DtEditorErrorCode result; _DtWidgetToAppContext(widget); _DtAppLock(app); result = LoadFile(widget, fileName, APPEND_DATA, 0, 0); _DtAppUnlock(app); return result; } /*************************************************************************** * * DtEditorInsert - insert data into the contents of the DtEditor widget. * * Inputs: widget to add to the contents * * a data structure containing the data to insert into the * widget. Depending upon the type of data being set, this * structure will contain various fields: * * string - \0-terminated string of characters * data - the data, the size of the data * * Returns 0 - contents were set sucessfully * !0 - an error occured while setting the contents * ***************************************************************************/ extern DtEditorErrorCode DtEditorInsert( Widget widget, DtEditorContentRec *data ) { DtEditorErrorCode error = DtEDITOR_INVALID_TYPE; DtEditorWidget editor = (DtEditorWidget) widget; _DtWidgetToAppContext(widget); _DtAppLock(app); switch( data->type ) { case DtEDITOR_TEXT: { error = insertStringValue ( editor, data->value.string, INSERT_DATA, 0, 0 ); break; } case DtEDITOR_DATA: { error = insertDataValue ( editor, data->value.data.buf, data->value.data.length, INSERT_DATA, 0,0); break; } case DtEDITOR_WCHAR: { error = insertWcharValue ( editor, data->value.wchar, INSERT_DATA, 0, 0 ); break; } default : { error = DtEDITOR_INVALID_TYPE; } } /* end switch */ _DtAppUnlock(app); return( error ); } /*************************************************************************** * * DtEditorInsertFromFile - read a data file, inserting the contents * into a DtEditor widget. * * Inputs: widget to insert the file to * * to indicate the type of contents inserted from the file: * string - a \0-terminated string of characters * data - untyped data * * filename - name of the file to read * * Returns 0 - contents were inserted sucessfully * !0 - an error occured while inserting the contents * ***************************************************************************/ extern DtEditorErrorCode DtEditorInsertFromFile( Widget widget, char *fileName) { DtEditorErrorCode result; _DtWidgetToAppContext(widget); _DtAppLock(app); result = LoadFile(widget, fileName, INSERT_DATA, 0, 0); _DtAppUnlock(app); return result; } /*************************************************************************** * * DtEditorReplace - replace a specified portion of the contents of the * DtEditor widget with the supplied data. * * Inputs: widget to replace a portion of its contents * * starting character position of the portion to replace * * ending character position of the portion to replace * * a data structure containing the data to replace some data * in the widget. Depending upon the type of data being set, * this structure will contain various fields: * * string - \0-terminated string of characters * data - the data, the size of the data * * * Returns 0 - the portion was replaced sucessfully * !0 - an error occured while replacing the portion * ***************************************************************************/ extern DtEditorErrorCode DtEditorReplace( Widget widget, XmTextPosition startPos, XmTextPosition endPos, DtEditorContentRec *data) { DtEditorErrorCode error = DtEDITOR_INVALID_TYPE; DtEditorWidget editor = (DtEditorWidget) widget; XmTextWidget tw; _DtWidgetToAppContext(widget); _DtAppLock(app); tw = (XmTextWidget) M_text(editor); if( startPos < 0 ) startPos = 0; if( startPos > tw->text.last_position ) startPos = tw->text.last_position; if( endPos < 0 ) endPos = 0; if( endPos > tw->text.last_position ) endPos = tw->text.last_position; if( startPos > endPos ) { error = DtEDITOR_INVALID_RANGE; } else { switch( data->type ) { case DtEDITOR_TEXT: { error = insertStringValue ( editor, data->value.string, REPLACE_DATA, startPos, endPos ); break; } case DtEDITOR_DATA: { error = insertDataValue ( editor, data->value.data.buf, data->value.data.length, REPLACE_DATA, startPos, endPos ); break; } case DtEDITOR_WCHAR: { error = insertWcharValue ( editor, data->value.wchar, REPLACE_DATA, startPos, endPos ); break; } default : { error = DtEDITOR_INVALID_TYPE; } } /* end switch */ } _DtAppUnlock(app); return( error ); } /*************************************************************************** * * DtEditorReplaceFromFile - read a data file, using the contents to replace * a specified portion of the contntes of a * DtEditor widget. * * Inputs: widget to insert the file to * * starting character position of the portion to replace * * ending character position of the portion to replace * * to indicate the type of contents inserted from the file: * string - a \0-terminated string of characters * data - untyped data * * filename - local name of the file to read * * Returns 0 - contents were inserted sucessfully * !0 - an error occured while inserting the contents * ***************************************************************************/ extern DtEditorErrorCode DtEditorReplaceFromFile( Widget widget, XmTextPosition startPos, XmTextPosition endPos, char *fileName) { DtEditorWidget editor = (DtEditorWidget) widget; XmTextWidget tw; DtEditorErrorCode result; _DtWidgetToAppContext(widget); _DtAppLock(app); tw = (XmTextWidget) M_text(editor); if( startPos < 0) startPos = 0; if( startPos > tw->text.last_position ) startPos = tw->text.last_position; if( endPos < 0 ) endPos = 0; if( endPos > tw->text.last_position ) endPos = tw->text.last_position; if(startPos > endPos) { result = DtEDITOR_INVALID_RANGE; } else { result = LoadFile(widget, fileName, REPLACE_DATA, startPos, endPos); } _DtAppUnlock(app); return result; } /*************************************************************************** * * _DtEditorValidateFileAccess - check to see if file exists, whether we * can get to it, and whether it is readable * or writable. * * Note: does not check whether files for reading are read only. * * Inputs: filename - name of the local file to read * flag indicating whether we want to read or write * the file. * * Returns 0 file exists & we have read or write permissions. * * >0 if file cannot be read from/written to. * errno is set to one of the following values: * * General errors: * DtEDITOR_INVALID_FILENAME - 0 length filename * DtEDITOR_NONEXISTENT_FILE - file does not exist * (Note: this may not be considered an error when saving * to a file. The file may just need to be created.) * DtEDITOR_NO_FILE_ACCESS - cannot stat existing file * DtEDITOR_DIRECTORY - file is a directory * DtEDITOR_CHAR_SPECIAL_FILE - file is a device special file * DtEDITOR_BLOCK_MODE_FILE - file is a block mode file * * additional READ_ACCESS errors: * DtEDITOR_UNREADABLE_FILE - * * additional WRITE_ACCESS errors: * DtEDITOR_UNWRITABLE_FILE - * file or directory is write protected for * another reason * ***************************************************************************/ extern DtEditorErrorCode _DtEditorValidateFileAccess( char *fileName, int accessType ) { struct stat statbuf; /* Information on a file. */ DtEditorErrorCode error = DtEDITOR_INVALID_FILENAME; /* * First, make sure we were given a name */ if (fileName && *fileName ) { /* * Does the file already exist? */ if ( access(fileName, F_OK) != 0 ) error = DtEDITOR_NONEXISTENT_FILE; else { error = DtEDITOR_NO_ERRORS; /* * The file exists, so lets do some type checking */ if( stat(fileName, &statbuf) != 0 ) error = DtEDITOR_NO_FILE_ACCESS; else { /* if its a directory - can't save */ if( (statbuf.st_mode & S_IFMT) == S_IFDIR ) { error = DtEDITOR_DIRECTORY; return( error ); } /* if its a character special device - can't save */ if( (statbuf.st_mode & S_IFMT) == S_IFCHR ) { error = DtEDITOR_CHAR_SPECIAL_FILE; return( error ); } /* if its a block mode device - can't save */ if((statbuf.st_mode & S_IFMT) == S_IFBLK) { error = DtEDITOR_BLOCK_MODE_FILE; return( error ); } /* * We now know that it's a regular file so check to whether we * can read or write to it, as appropriate. */ switch( accessType ) { case READ_ACCESS: { if( access(fileName, R_OK) != 0 ) error = DtEDITOR_UNREADABLE_FILE; break; } case WRITE_ACCESS: { if( access(fileName, W_OK) == 0 ) { /* * Can write to it. */ error = DtEDITOR_WRITABLE_FILE; } else { /* * Can't write to it. */ error = DtEDITOR_UNWRITABLE_FILE; } /* end no write permission */ break; } default: { break; } } /* end switch */ } /* end stat suceeded */ } /* end file exists */ } /* end filename passed in */ return( error ); } /* end _DtEditorValidateFileAccess */ /************************************************************************ * * LoadFile - Check if file exists, whether we can get to it, etc. * If so, type and read its contents. * * Inputs: widget to set, add, or insert contents of file into * * name of file to read * * type of file (NULL). This will be set by LoadFile * * action to perform with the data (load, append, insert, * replace a portion, attach) * * The following information will be used if the file * contents will replace a portion of the widget's contents: * * starting character position of the portion to replace * * ending character position of the portion to replace * * Returns: DtEDITOR_NO_ERRORS - file was read sucessfully * DtEDITOR_READ_ONLY_FILE - file was read sucessfully but * is read only * DtEDITOR_DIRECTORY - the file is a directory * DtEDITOR_CHAR_SPECIAL_FILE - the file is a character * special device * DtEDITOR_BLOCK_MODE_FILE - the file is a block mode device * DtEDITOR_NONEXISTENT_FILE - file does not exist * DtEDITOR_NULLS_REMOVED - file contained embedded NULLs * that were removed * DtEDITOR_INSUFFICIENT_MEMORY - unable to allocate * enough memory for contents of file * ************************************************************************/ static DtEditorErrorCode LoadFile( Widget w, char *fileName, LoadActionType action, XmTextPosition startReplace, XmTextPosition endReplace ) { DtEditorContentRec cr; /* Structure for passing data to widget */ struct stat statbuf; /* Information on a file. */ int file_length; /* Length of file. */ FILE *fp = NULL; /* Pointer to open file */ DtEditorErrorCode returnVal = DtEDITOR_NONEXISTENT_FILE; /* Error accessing file & reading contents */ DtEditorErrorCode loadError=DtEDITOR_NO_ERRORS; /* Error from placing bits into text widget */ /* * First, make sure we were given a name */ if (fileName && *fileName ) { /* * Can we read the file? */ returnVal = _DtEditorValidateFileAccess( fileName, READ_ACCESS ); if( returnVal == DtEDITOR_NO_ERRORS ) { /* * Open the file for reading. If we can read/write, then we're * cool, otherwise we might need to tell the user that the * file's read-only, or that we can't even read from it. */ if( (fp = fopen(fileName, "r+")) == NULL ) { /* * We can't update (read/write) the file so try opening read- * only */ if( (fp = fopen(fileName, "r")) == NULL ) { /* * We can't read from the file. */ return ( DtEDITOR_UNREADABLE_FILE ); } else { /* * Tell the application that the file's read-only. * Becareful not to overwrite this value with one of the calls * to set the widget's contents. */ returnVal = DtEDITOR_READ_ONLY_FILE; } } /* end open for read/write */ } /* end try to read the file */ } /* end if no filename */ /* If a file is open, get the bytes */ if ( fp ) { stat( fileName, &statbuf ); file_length = statbuf.st_size; /* * Check to see if we have enough memory to load the file contents * into the text widget. This is only an estimate of our needs. * Check4EnoughMemory() returns DtEDITOR_NO_ERRORS, * DtEDITOR_ILLEGAL_SIZE, or DtEDITOR_INSUFFICIENT_MEMORY. */ loadError = Check4EnoughMemory( file_length ); if (loadError == DtEDITOR_INSUFFICIENT_MEMORY) returnVal = loadError; else { /* * Read the file contents (with room for null) & convert to a * string. We want to use a string because the * DtEditorSetContents/Append/Insert/... functions create another * copy of the data before actually putting it into the widget. */ char *file_string = (char*) XtMalloc(file_length + 1); file_length = fread(file_string, sizeof(char), file_length, fp); file_string[file_length] = '\0'; /* * Strip out any embedded NULLs because the text widget will only * accept data up to the first NULL. * * StripEmbeddedNulls() returns DtEDITOR_NO_ERRORS or * DtEDITOR_NULLS_REMOVED */ loadError = StripEmbeddedNulls( file_string, &file_length ); if ( loadError != DtEDITOR_NO_ERRORS ) returnVal = loadError; /* * Insert it as a string, otherwise the following DtEditor*() * functions will make another copy of the data. */ cr.type = DtEDITOR_TEXT; cr.value.string = file_string; /* * Load, insert, append, or attach the file, as specified */ switch( action ) { case LOAD_DATA: { loadError = DtEditorSetContents ( w, &cr ); break; } case INSERT_DATA: { loadError = DtEditorInsert ( w, &cr ); break; } case APPEND_DATA: { loadError = DtEditorAppend ( w, &cr ); break; } case REPLACE_DATA: { loadError = DtEditorReplace(w, startReplace, endReplace, &cr); break; } default: { } } /* end switch */ if ( loadError != DtEDITOR_NO_ERRORS ) returnVal = loadError; /* * The file is loaded, clean up. */ XtFree( file_string ); } /* end there is enough memory */ /* Close the file */ fclose(fp); } /* end if a file is open */ return( returnVal ); } /* end LoadFile */ static char * StringAdd( char *destination, char *source, int number) { memcpy(destination, source, number); destination[number] = (char)'\0'; destination += number; return destination; } /*************************************************************************** * * CopySubstring - copies out a portion of the text, optionally * adding newlines at any and all wordwrap-caused * "virtual" lines. * * Inputs: widget from which we get the data to write; * startPos determines the first character to write out; * endPos determines the last character to write out; * buf is the character buffer into which we write. It * is assumed to be large enough - be careful. * addNewlines specifies whether to add '/n' to "virtual" lines. * Returns Nuthin' * * ***************************************************************************/ static char * CopySubstring( XmTextWidget widget, XmTextPosition startPos, XmTextPosition endPos, char *buf, Boolean addNewlines) { register XmTextLineTable line_table = widget->text.line_table; int currLine, firstLine; char *pString, *pCurrChar, *pLastChar; int numToCopy; if(startPos < 0) startPos = 0; if(startPos > widget->text.last_position) startPos = widget->text.last_position; if(endPos < 0) endPos = 0; if(endPos > widget->text.last_position) endPos = widget->text.last_position; if(startPos > endPos) return buf; pString = XmTextGetString((Widget)widget); if(addNewlines == False) { pCurrChar = _DtEditorGetPointer(pString, startPos); pLastChar = _DtEditorGetPointer(pString, endPos); numToCopy = pLastChar - pCurrChar + mblen(pLastChar, MB_CUR_MAX); buf = StringAdd(buf, pCurrChar, numToCopy); } else { int *mb_str_loc, total, z, siz; char *bptr; mb_str_loc = (int *) XtMalloc(sizeof(int) * ((endPos-startPos)+1)); if (NULL == mb_str_loc) { /* Should figure out some way to pass back an error code. */ buf = CopySubstring(widget, startPos, endPos, buf, False); return buf; } /* * mb_str_loc[] is being used to replace the call * to _DtEditorGetPointer. That function used * mbtowc() to count the number of chars between the * beginning of pString and startChar. The problem * was that it sat in a loop and was also called for * every line, so it was SLOW. Now, we count once * and store the results in mb_str_loc[]. */ /* Because startPos may not always == 0: */ /* mb_str_loc[0] = startPos */ /* mb_str_loc[endPos - startPos] = endPos */ /* */ /* So when accessing items, dereference off of */ /* startPos. */ mb_str_loc[0] = 0; for(total=0, bptr=pString, z=1; z <= (endPos - startPos); bptr += siz, z++) { if (MB_CUR_MAX > 1) { if ( (siz = mblen(bptr, MB_CUR_MAX)) < 0) { siz = 1; total += 1; } else total += siz; } else { siz = 1; total += 1; } mb_str_loc[z] = total; } firstLine = currLine = _DtEditorGetLineIndex(widget, startPos); do { if(startPos > (XmTextPosition)line_table[currLine].start_pos) pCurrChar = pString + mb_str_loc[0]; else { z = line_table[currLine].start_pos; pCurrChar = pString + mb_str_loc[z - startPos]; } if(addNewlines == True && currLine > firstLine && line_table[currLine].virt_line != 0) { buf[0] = (char)'\n'; buf[1] = (char)'\0'; buf++; } if(currLine >= (widget->text.total_lines - 1)) pLastChar = pString + mb_str_loc[endPos - startPos]; else if((XmTextPosition)line_table[currLine + 1].start_pos <= endPos) { z = line_table[currLine+1].start_pos - 1; pLastChar = pString + mb_str_loc[z - startPos]; } else pLastChar = pString + mb_str_loc[endPos - startPos]; numToCopy = pLastChar - pCurrChar + mblen(pLastChar, MB_CUR_MAX); buf = StringAdd(buf, pCurrChar, numToCopy); currLine++; } while(currLine < widget->text.total_lines && (XmTextPosition)line_table[currLine].start_pos <= endPos); XtFree((char*)mb_str_loc); } XtFree(pString); return buf; } /************************************************************************* * * _DtEditorCopyDataOut - Writes the entire text editor buffer contents to * the specified character array. * * Inputs: tw, to supply the data. * buf, specifying the array to which to write the data. * *************************************************************************/ static char * _DtEditorCopyDataOut( XmTextWidget tw, char *buf, Boolean addNewlines) { buf = CopySubstring(tw, 0, tw->text.last_position, buf, addNewlines); return buf; } static DtEditorErrorCode getStringValue( DtEditorWidget editor, char **buf, Boolean insertNewlines) { XmTextWidget tw = (XmTextWidget) M_text(editor); int bufSize; char *lastChar; DtEditorErrorCode returnVal = DtEDITOR_NO_ERRORS; /* * Calculate the size of the buffer we need for the data. * 1. Start with MB_CUR_MAX for each char in the text. * 3. Add in 1 char for each line, if we have to insert newlines. * 4. Add 1 for a terminating NULL. */ bufSize = tw->text.last_position * MB_CUR_MAX; if(insertNewlines == True) bufSize += tw->text.total_lines; bufSize += 1; returnVal = Check4EnoughMemory(bufSize); if (DtEDITOR_NO_ERRORS != returnVal) return returnVal; *buf = (char *) XtMalloc(bufSize); lastChar = _DtEditorCopyDataOut(tw, *buf, insertNewlines); return returnVal; } /* end getStringValue */ static DtEditorErrorCode getDataValue( DtEditorWidget editor, void **buf, unsigned int *size, Boolean insertNewlines) { DtEditorErrorCode error; error = getStringValue(editor, (char **)buf, insertNewlines); *size = strlen( *buf ); /* remember, strlen doesn't count \0 at end */ return( error ); } /* end getDataValue */ static DtEditorErrorCode getWcharValue( DtEditorWidget editor, wchar_t **data, Boolean insertNewlines) { DtEditorErrorCode error; char *mb_value; wchar_t *pWchar_value; int num_char, result; size_t nbytes; error = getStringValue(editor, &mb_value, insertNewlines); if (error == DtEDITOR_NO_ERRORS) { /* * Allocate space for the wide character string */ num_char = _DtEditor_CountCharacters(mb_value, strlen(mb_value)) + 1; nbytes = (size_t) num_char * sizeof(wchar_t); error = Check4EnoughMemory(nbytes); if (DtEDITOR_NO_ERRORS != error) return error; pWchar_value = (wchar_t*) XtMalloc(nbytes); /* * Convert the multi-byte string to wide character */ result = mbstowcs(pWchar_value, mb_value, num_char*sizeof(wchar_t) ); if (result < 0) pWchar_value[0] = 0L; *data = pWchar_value; XtFree( mb_value ); } return( error ); } /* end getWcharValue */ /*************************************************************************** * * DtEditorGetContents - gets the contents of the DtEditor widget. * * Inputs: widget to retrieve the contents * * pointer to a data structure indicating how the retrieved * data should be formatted. Depending upon the type of format, * this structure will contain various fields: * string - a NULL pointer (char *) to hold the data * a new container will be created. * data - void pointer to hold the data, unsigned int for the * size of the data, * a Boolean indicating whether Newline characters should be * inserted at the end of each line, in string format. * a Boolean indicating whether the the unsaved changes * flag should be cleared. There may be times when an * application will want to request a copy of the contents * without effecting whether DtEditorCheckForUnsavedChanges * reports there are unsaved changes. * * Returns 0 - contents were retrieved sucessfully * !0 - an error occured while retrieving the contents * * The structure passed in will be set according to the * requested format: * string - a \0-terminated string of characters with * optional Newlines * container - handle to a Bento container * data - the data, the size of the data * * The application is responsible for free'ing any data in the * above structure. * ***************************************************************************/ extern DtEditorErrorCode DtEditorGetContents( Widget widget, DtEditorContentRec *data, Boolean hardCarriageReturns, Boolean markContentsAsSaved ) { DtEditorErrorCode error = DtEDITOR_INVALID_TYPE; DtEditorWidget editor = (DtEditorWidget) widget; _DtWidgetToAppContext(widget); _DtAppLock(app); switch( data->type ) { case DtEDITOR_TEXT: { error = getStringValue( editor, &(data->value.string), hardCarriageReturns ); break; } case DtEDITOR_DATA: { error = getDataValue( editor, &(data->value.data.buf), &(data->value.data.length), hardCarriageReturns ); break; } case DtEDITOR_WCHAR: { error = getWcharValue( editor, &(data->value.wchar), hardCarriageReturns ); break; } default : { error = DtEDITOR_INVALID_TYPE; } } /* end switch */ /* * If there were no errors, mark there are now no unsaved changes (unless * we were told not to). */ if ( error == DtEDITOR_NO_ERRORS && markContentsAsSaved == True ) M_unreadChanges( editor ) = False; _DtAppUnlock(app); return( error ); } /*************************************************************************** * * DtEditorSaveContentsToFile - saves the contents of the DtEditor * widget to a disc file as string/data * or a CDE Document (Bento container). * * Inputs: widget to retrieve the contents * * filename - name of the file to read * a Boolean indicating whether the file should be * overwritten if it currently exists. * a Boolean indicating whether Newline characters should be * inserted at the end of each line (string format only). * a Boolean indicating whether the the unsaved changes * flag should be cleared. There may be times when an * application will want to request a copy of the contents * without effecting whether DtEditorCheckForUnsavedChanges * reports there are unsaved changes. * * Returns DtEDITOR_NO_ERRORS - contents were saved sucessfully * DtEDITOR_UNWRITABLE_FILE - file is write protected * DtEDITOR_WRITABLE_FILE - file exists and the * overwriteIfExists parameter is False. * DtEDITOR_SAVE_FAILED - write to the file failed; check * disk space, etc. * OR any errors from DtEditorGetContents * ***************************************************************************/ extern DtEditorErrorCode DtEditorSaveContentsToFile( Widget widget, char *fileName, Boolean overwriteIfExists, Boolean hardCarriageReturns, Boolean markContentsAsSaved ) { FILE *pFile; DtEditorContentRec cr; /* Structure for retrieving contents of widget */ DtEditorWidget editor = (DtEditorWidget) widget; DtEditorErrorCode error = DtEDITOR_INVALID_FILENAME; _DtWidgetToAppContext(widget); _DtAppLock(app); /* * First, make sure we were given a name */ if (fileName && *fileName ) { /* * Can we save to the file? */ error = _DtEditorValidateFileAccess( fileName, WRITE_ACCESS ); if( error == DtEDITOR_NO_ERRORS || error == DtEDITOR_NONEXISTENT_FILE || error == DtEDITOR_WRITABLE_FILE ) { /* * Don't overwrite an existing file if we've been told not to */ if( error == DtEDITOR_WRITABLE_FILE && overwriteIfExists == False ) { _DtAppUnlock(app); return( error ); } /* * Open the file for writing */ if ( (pFile = fopen(fileName, "w")) == NULL ) { _DtAppUnlock(app); return( DtEDITOR_UNWRITABLE_FILE ); } else { /* * Save the unsaved changes flag so we can restore it if the write * to the file fails. */ Boolean saved_state = M_unreadChanges( editor ); /* * Now, get the contents of the widget and write it to the file, * depending upon the format requested. */ cr.type = DtEDITOR_DATA; error = DtEditorGetContents( widget, &cr, hardCarriageReturns, markContentsAsSaved ); if ( error == DtEDITOR_NO_ERRORS ) { /* * Write it to the file */ size_t size_written = fwrite( cr.value.data.buf, 1, cr.value.data.length, pFile ); if( cr.value.data.length != size_written ) error = DtEDITOR_SAVE_FAILED; XtFree( cr.value.data.buf ); } fclose(pFile); if( error == DtEDITOR_SAVE_FAILED ) { /* * Restore the unsaved changes flag since the save failed */ M_unreadChanges( editor ) = saved_state; } } /* end file is writable */ } /* end filename is valid */ } _DtAppUnlock(app); return( error ); } /* end DtEditorSaveContentsToFile */ /* * _DtEditorGetPointer returns a pointer to the _character_ * numbered by startChar within the string pString. * It accounts for possible multibyte chars. */ char * _DtEditorGetPointer( char *pString, int startChar) { char *bptr; int curChar, char_size; if(MB_CUR_MAX > 1) { for(bptr = pString, curChar = 0; curChar < startChar && *bptr != (char)'\0'; curChar++, bptr += char_size) { if ( (char_size = mblen(bptr, MB_CUR_MAX)) < 0) char_size = 1; } } else { bptr = pString + startChar; } return bptr; } /* end _DtEditorGetPointer */
sTeeLM/MINIME
toolkit/srpm/SOURCES/cde-2.2.4/lib/DtWidget/EditAreaData.c
C
gpl-2.0
49,947
#pragma once /* * Copyright (C) 2005-2015 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include <memory> #include <string> #include <vector> class CEvent; namespace KODI { namespace MESSAGING { class CApplicationMessenger; class ThreadMessage { friend CApplicationMessenger; public: ThreadMessage() : ThreadMessage{ 0, -1, -1, nullptr } { } explicit ThreadMessage(uint32_t messageId) : ThreadMessage{ messageId, -1, -1, nullptr } { } ThreadMessage(uint32_t messageId, int p1, int p2, void* payload) : dwMessage{ messageId } , param1{ p1 } , param2{ p2 } , lpVoid{ payload } { } ThreadMessage(uint32_t messageId, int p1, int p2, void* payload, std::string param, std::vector<std::string> vecParams) : dwMessage{ messageId } , param1{ p1 } , param2{ p2 } , lpVoid{ payload } , strParam( param ) , params( vecParams ) { } ThreadMessage(const ThreadMessage& other) : dwMessage(other.dwMessage), param1(other.param1), param2(other.param2), lpVoid(other.lpVoid), strParam(other.strParam), params(other.params), waitEvent(other.waitEvent), result(other.result) { } ThreadMessage(ThreadMessage&& other) : dwMessage(other.dwMessage), param1(other.param1), param2(other.param2), lpVoid(other.lpVoid), strParam(std::move(other.strParam)), params(std::move(other.params)), waitEvent(std::move(other.waitEvent)), result(std::move(other.result)) { } ThreadMessage& operator=(const ThreadMessage& other) { if (this == &other) return *this; dwMessage = other.dwMessage; param1 = other.param1; param2 = other.param2; lpVoid = other.lpVoid; strParam = other.strParam; params = other.params; waitEvent = other.waitEvent; result = other.result; return *this; } ThreadMessage& operator=(ThreadMessage&& other) { if (this == &other) return *this; dwMessage = other.dwMessage; param1 = other.param1; param2 = other.param2; lpVoid = other.lpVoid; strParam = std::move(other.strParam); params = std::move(other.params); waitEvent = std::move(other.waitEvent); result = std::move(other.result); return *this; } uint32_t dwMessage; int param1; int param2; void* lpVoid; std::string strParam; std::vector<std::string> params; void SetResult(int res) { //On posted messages result will be zero, since they can't //retrieve the response we silently ignore this to let message //handlers not have to worry about it if (result) *result = res; } protected: std::shared_ptr<CEvent> waitEvent; std::shared_ptr<int> result; }; } }
hackthis02/xbmc
xbmc/messaging/ThreadMessage.h
C
gpl-2.0
3,352
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>oRTP: /Users/huyheo/Documents/Linphone/linphone-iphone/submodules/linphone/oRTP/src Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">oRTP &#160;<span id="projectnumber">0.22.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_2a7dcbd79b844734b273b7fb1d7d705c.html">linphone</a></li><li class="navelem"><a class="el" href="dir_ce0874cbbf4173a48245befc1202b926.html">oRTP</a></li><li class="navelem"><a class="el" href="dir_12068a0eb9ea07e5ea5c12c7c6d7e94f.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">src Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:avprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>avprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b64_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="b64_8c.html">b64.c</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:dll__entry_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>dll_entry.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:event_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>event.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.h</b> <a href="jitterctl_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:logging_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>logging.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:netsim_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>netsim.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ortp-config-win32_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>ortp-config-win32.h</b> <a href="ortp-config-win32_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ortp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>ortp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ortp__srtp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>ortp_srtp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:payloadtype_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>payloadtype.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:port_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>port.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:posixtimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>posixtimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__inet_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_inet.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__priv_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_priv.h</b> <a href="rtpsession__priv_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsignaltable_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsignaltable.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.h</b> <a href="rtptimer_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.h</b> <a href="scheduler_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:sessionset_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>sessionset.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:str__utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>str_utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:stun_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>stun.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:stun__udp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>stun_udp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:telephonyevents_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>telephonyevents.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.h</b> <a href="utils_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:winrttimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>winrttimer.h</b> <a href="winrttimer_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:zrtp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>zrtp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Jul 31 2013 14:43:09 for oRTP by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
helloiloveit/VkxPhoneProject
submodules/build-i386-apple-darwin/linphone/oRTP/doc/html/dir_12068a0eb9ea07e5ea5c12c7c6d7e94f.html
HTML
gpl-2.0
11,345
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.3.1"> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="enumvalues_6a.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
vertexclique/travertine
qwt/doc/html/search/enumvalues_6a.html
HTML
gpl-2.0
1,021
<?php class woocsvImport { public $importLog; public $options; public $header; public $message; public $options_default = array ( 'seperator'=>',', 'skipfirstline'=>1, 'upload_dir' => '/csvimport/', 'blocksize' => 1, 'language' => 'EN', 'add_to_gallery' => 1, 'merge_products'=>1, 'add_to_categories'=>1, 'debug'=>0, 'match_by' => 'sku', 'roles' => array('shop_manager'), 'match_author_by' => 'login', ); public $fields = array ( 0 => 'sku', 1 => 'post_name', 2 => 'post_status', 3 => 'post_title', 4 => 'post_content', 5 => 'post_excerpt', 6 => 'category', 7 => 'tags', 8 => 'stock', 9 => 'price', /* ! 2.0.0 deprecated. Use regular_price or/and sale_price */ 10 => 'regular_price', 11 => 'sale_price', 12 => 'weight' , 13 => 'length', 14 => 'width' , 15 => 'height' , //2.1.0 16 => 'images', //deprecated since 1.2.0, will be removed in 1.4.0 17 => 'tax_status', 18 => 'tax_class' , 19 => 'stock_status', // instock, outofstock 20 => 'visibility', // visible, catelog, search, hidden 21 => 'backorders', // yes,no 22 => 'featured', // yes,no 23 => 'manage_stock', // yes,no 24 => 'featured_image', 25 => 'product_gallery', 26 => 'shipping_class', 27 => 'comment_status', //closed, open 28 => 'change_stock', // +1 -1 + 5 -8 29 =>'ID', 30 =>'ping_status', 31 => 'menu_order', // open,closed 32 => 'post_author', //user name or nice name of an user ); public function __construct() { // activation hook register_activation_hook( __FILE__, array($this, 'install' )); //check install $this->checkInstall(); //load options $this->checkOptions(); //fill header $this->fillHeader(); } /* !1.2.7 plugins url */ public function plugin_url() { if ( $this->plugin_url ) return $this->plugin_url; return $this->plugin_url = untrailingslashit( plugins_url( '/', __FILE__ ) ); } public function install() { $upload_dir = wp_upload_dir(); $dir = $upload_dir['basedir'] .'/csvimport/'; @mkdir($dir); } public function fillHeader() { $header = get_option('woocsv-header'); if (!empty($header)) $this->header = $header; } public function checkOptions() { $update = false; $options = get_option('woocsv-options'); $options_default = $this->options_default; foreach ($options_default as $key=>$value) { if (!isset($options[$key])) { $options[$key] = $value; $update = true; } } if ($update) { update_option('woocsv-options',$options); } $options = get_option('woocsv-options'); $this->options = $options; } public function checkInstall() { $message = $this->message; if (!get_option('woocsv-options')) $message .= __('Please save your settings!','woocsv-import'); $upload_dir = wp_upload_dir(); $dir = $upload_dir['basedir'] .'/csvimport/'; if (!is_dir($dir)) @mkdir($dir); if (!is_writable($upload_dir['basedir'] .'/csvimport/')) $message .= __('Upload directory is not writable, please check you permissions','woocsv-import'); $this->message = $message; if ($message) add_action( 'admin_notices', array($this, 'showWarning')); } public function showWarning() { global $current_screen; if ($current_screen->parent_base == 'woocsv_import' ) echo '<div class="error"><p>'.$this->message.'</p></div>'; } }
ilfungo/bts
wp-content/plugins/woocommerce-csvimport/include/class-woocsv-csvimport.php
PHP
gpl-2.0
3,360
########################## NOTES ############################################### # This files goal is to take CMake options found in kokkos_options.cmake but # possibly set from elsewhere # (see: trilinos/cmake/ProjectCOmpilerPostConfig.cmake) # using CMake idioms and map them onto the KOKKOS_SETTINGS variables that gets # passed to the kokkos makefile configuration: # make -f ${CMAKE_SOURCE_DIR}/core/src/Makefile ${KOKKOS_SETTINGS} build-makefile-cmake-kokkos # that generates KokkosCore_config.h and kokkos_generated_settings.cmake # To understand how to form KOKKOS_SETTINGS, see # <KOKKOS_PATH>/Makefile.kokkos #------------------------------------------------------------------------------- #------------------------------- GENERAL OPTIONS ------------------------------- #------------------------------------------------------------------------------- # Ensure that KOKKOS_ARCH is in the ARCH_LIST if (KOKKOS_ARCH MATCHES ",") message("-- Detected a comma in: KOKKOS_ARCH=${KOKKOS_ARCH}") message("-- Although we prefer KOKKOS_ARCH to be semicolon-delimited, we do allow") message("-- comma-delimited values for compatibility with scripts (see github.com/trilinos/Trilinos/issues/2330)") string(REPLACE "," ";" KOKKOS_ARCH "${KOKKOS_ARCH}") message("-- Commas were changed to semicolons, now KOKKOS_ARCH=${KOKKOS_ARCH}") endif() foreach(arch ${KOKKOS_ARCH}) list(FIND KOKKOS_ARCH_LIST ${arch} indx) if (indx EQUAL -1) message(FATAL_ERROR "${arch} is not an accepted value for KOKKOS_ARCH." " Please pick from these choices: ${KOKKOS_INTERNAL_ARCH_DOCSTR}") endif () endforeach() # KOKKOS_SETTINGS uses KOKKOS_ARCH string(REPLACE ";" "," KOKKOS_GMAKE_ARCH "${KOKKOS_ARCH}") # From Makefile.kokkos: Options: yes,no if(${KOKKOS_ENABLE_DEBUG}) set(KOKKOS_GMAKE_DEBUG yes) else() set(KOKKOS_GMAKE_DEBUG no) endif() #------------------------------- KOKKOS_DEVICES -------------------------------- # Can have multiple devices set(KOKKOS_DEVICESl) foreach(devopt ${KOKKOS_DEVICES_LIST}) string(TOUPPER ${devopt} devoptuc) if (${KOKKOS_ENABLE_${devoptuc}}) list(APPEND KOKKOS_DEVICESl ${devopt}) endif () endforeach() # List needs to be comma-delmitted string(REPLACE ";" "," KOKKOS_GMAKE_DEVICES "${KOKKOS_DEVICESl}") #------------------------------- KOKKOS_OPTIONS -------------------------------- # From Makefile.kokkos: Options: aggressive_vectorization,disable_profiling,disable_deprecated_code #compiler_warnings, aggressive_vectorization, disable_profiling, disable_dualview_modify_check, enable_profile_load_print set(KOKKOS_OPTIONSl) if(${KOKKOS_ENABLE_COMPILER_WARNINGS}) list(APPEND KOKKOS_OPTIONSl compiler_warnings) endif() if(${KOKKOS_ENABLE_AGGRESSIVE_VECTORIZATION}) list(APPEND KOKKOS_OPTIONSl aggressive_vectorization) endif() if(NOT ${KOKKOS_ENABLE_PROFILING}) list(APPEND KOKKOS_OPTIONSl disable_profiling) endif() if(NOT ${KOKKOS_ENABLE_DEPRECATED_CODE}) list(APPEND KOKKOS_OPTIONSl disable_deprecated_code) endif() if(NOT ${KOKKOS_ENABLE_DEBUG_DUALVIEW_MODIFY_CHECK}) list(APPEND KOKKOS_OPTIONSl disable_dualview_modify_check) endif() if(${KOKKOS_ENABLE_PROFILING_LOAD_PRINT}) list(APPEND KOKKOS_OPTIONSl enable_profile_load_print) endif() # List needs to be comma-delimitted string(REPLACE ";" "," KOKKOS_GMAKE_OPTIONS "${KOKKOS_OPTIONSl}") #------------------------------- KOKKOS_USE_TPLS ------------------------------- # Construct the Makefile options set(KOKKOS_USE_TPLSl) foreach(tplopt ${KOKKOS_USE_TPLS_LIST}) if (${KOKKOS_ENABLE_${tplopt}}) list(APPEND KOKKOS_USE_TPLSl ${KOKKOS_INTERNAL_${tplopt}}) endif () endforeach() # List needs to be comma-delimitted string(REPLACE ";" "," KOKKOS_GMAKE_USE_TPLS "${KOKKOS_USE_TPLSl}") #------------------------------- KOKKOS_CUDA_OPTIONS --------------------------- # Construct the Makefile options set(KOKKOS_CUDA_OPTIONSl) foreach(cudaopt ${KOKKOS_CUDA_OPTIONS_LIST}) if (${KOKKOS_ENABLE_CUDA_${cudaopt}}) list(APPEND KOKKOS_CUDA_OPTIONSl ${KOKKOS_INTERNAL_${cudaopt}}) endif () endforeach() # List needs to be comma-delmitted string(REPLACE ";" "," KOKKOS_GMAKE_CUDA_OPTIONS "${KOKKOS_CUDA_OPTIONSl}") #------------------------------- PATH VARIABLES -------------------------------- # Want makefile to use same executables specified which means modifying # the path so the $(shell ...) commands in the makefile see the right exec # Also, the Makefile's use FOO_PATH naming scheme for -I/-L construction #TODO: Makefile.kokkos allows this to be overwritten? ROCM_HCC_PATH set(KOKKOS_INTERNAL_PATHS) set(addpathl) foreach(kvar IN LISTS KOKKOS_USE_TPLS_LIST ITEMS CUDA QTHREADS) if(${KOKKOS_ENABLE_${kvar}}) if(DEFINED KOKKOS_${kvar}_DIR) set(KOKKOS_INTERNAL_PATHS ${KOKKOS_INTERNAL_PATHS} "${kvar}_PATH=${KOKKOS_${kvar}_DIR}") if(IS_DIRECTORY ${KOKKOS_${kvar}_DIR}/bin) list(APPEND addpathl ${KOKKOS_${kvar}_DIR}/bin) endif() endif() endif() endforeach() # Path env is : delimitted string(REPLACE ";" ":" KOKKOS_INTERNAL_ADDTOPATH "${addpathl}") ######################### SET KOKKOS_SETTINGS ################################## # Set the KOKKOS_SETTINGS String -- this is the primary communication with the # makefile configuration. See Makefile.kokkos set(KOKKOS_SETTINGS KOKKOS_SRC_PATH=${KOKKOS_SRC_PATH}) set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} KOKKOS_PATH=${KOKKOS_PATH}) set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} KOKKOS_INSTALL_PATH=${CMAKE_INSTALL_PREFIX}) # Form of KOKKOS_foo=$KOKKOS_foo foreach(kvar ARCH;DEVICES;DEBUG;OPTIONS;CUDA_OPTIONS;USE_TPLS) if(DEFINED KOKKOS_GMAKE_${kvar}) if (NOT "${KOKKOS_GMAKE_${kvar}}" STREQUAL "") set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} KOKKOS_${kvar}=${KOKKOS_GMAKE_${kvar}}) endif() endif() endforeach() # Form of VAR=VAL #TODO: Makefile supports MPICH_CXX, OMPI_CXX as well foreach(ovar CXX;CXXFLAGS;LDFLAGS) if(DEFINED ${ovar}) if (NOT "${${ovar}}" STREQUAL "") set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} ${ovar}=${${ovar}}) endif() endif() endforeach() # Finally, do the paths if (NOT "${KOKKOS_INTERNAL_PATHS}" STREQUAL "") set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} ${KOKKOS_INTERNAL_PATHS}) endif() if (NOT "${KOKKOS_INTERNAL_ADDTOPATH}" STREQUAL "") set(KOKKOS_SETTINGS ${KOKKOS_SETTINGS} "PATH=\"${KOKKOS_INTERNAL_ADDTOPATH}:$ENV{PATH}\"") endif() # Final form that gets passed to make set(KOKKOS_SETTINGS env ${KOKKOS_SETTINGS}) ############################ PRINT CONFIGURE STATUS ############################ if(KOKKOS_CMAKE_VERBOSE) message(STATUS "") message(STATUS "****************** Kokkos Settings ******************") message(STATUS "Execution Spaces") if(KOKKOS_ENABLE_CUDA) message(STATUS " Device Parallel: Cuda") else() message(STATUS " Device Parallel: None") endif() if(KOKKOS_ENABLE_OPENMP) message(STATUS " Host Parallel: OpenMP") elseif(KOKKOS_ENABLE_PTHREAD) message(STATUS " Host Parallel: Pthread") elseif(KOKKOS_ENABLE_QTHREADS) message(STATUS " Host Parallel: Qthreads") else() message(STATUS " Host Parallel: None") endif() if(KOKKOS_ENABLE_SERIAL) message(STATUS " Host Serial: Serial") else() message(STATUS " Host Serial: None") endif() message(STATUS "") message(STATUS "Architectures:") message(STATUS " ${KOKKOS_GMAKE_ARCH}") message(STATUS "") message(STATUS "Enabled options") if(KOKKOS_SEPARATE_LIBS) message(STATUS " KOKKOS_SEPARATE_LIBS") endif() foreach(opt IN LISTS KOKKOS_INTERNAL_ENABLE_OPTIONS_LIST) string(TOUPPER ${opt} OPT) if (KOKKOS_ENABLE_${OPT}) message(STATUS " KOKKOS_ENABLE_${OPT}") endif() endforeach() if(KOKKOS_ENABLE_CUDA) if(KOKKOS_CUDA_DIR) message(STATUS " KOKKOS_CUDA_DIR: ${KOKKOS_CUDA_DIR}") endif() endif() if(KOKKOS_QTHREADS_DIR) message(STATUS " KOKKOS_QTHREADS_DIR: ${KOKKOS_QTHREADS_DIR}") endif() if(KOKKOS_HWLOC_DIR) message(STATUS " KOKKOS_HWLOC_DIR: ${KOKKOS_HWLOC_DIR}") endif() if(KOKKOS_MEMKIND_DIR) message(STATUS " KOKKOS_MEMKIND_DIR: ${KOKKOS_MEMKIND_DIR}") endif() message(STATUS "") message(STATUS "Final kokkos settings variable:") message(STATUS " ${KOKKOS_SETTINGS}") message(STATUS "*****************************************************") message(STATUS "") endif()
aurix/lammps-induced-dipole-polarization-pair-style
lib/kokkos/cmake/kokkos_settings.cmake
CMake
gpl-2.0
8,373
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\FormError; use Symfony\Component\Intl\Util\IntlTestHelper; class DateTypeTest extends BaseTypeTest { const TESTED_TYPE = 'date'; private $defaultTimezone; protected function setUp() { parent::setUp(); $this->defaultTimezone = date_default_timezone_get(); } protected function tearDown() { date_default_timezone_set($this->defaultTimezone); \Locale::setDefault('en'); } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException */ public function testInvalidWidgetOption() { $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'fake_widget', )); } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException */ public function testInvalidInputOption() { $this->factory->create(static::TESTED_TYPE, null, array( 'input' => 'fake_input', )); } public function testSubmitFromSingleTextDateTimeWithDefaultFormat() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'single_text', 'input' => 'datetime', )); $form->submit('2010-06-02'); $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData()); $this->assertEquals('2010-06-02', $form->getViewData()); } public function testSubmitFromSingleTextDateTimeWithCustomFormat() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'single_text', 'input' => 'datetime', 'format' => 'yyyy', )); $form->submit('2010'); $this->assertDateTimeEquals(new \DateTime('2010-01-01 UTC'), $form->getData()); $this->assertEquals('2010', $form->getViewData()); } public function testSubmitFromSingleTextDateTime() { // we test against "de_DE", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_DE'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => \IntlDateFormatter::MEDIUM, 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'single_text', 'input' => 'datetime', )); $form->submit('2.6.2010'); $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData()); $this->assertEquals('02.06.2010', $form->getViewData()); } public function testSubmitFromSingleTextString() { // we test against "de_DE", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_DE'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => \IntlDateFormatter::MEDIUM, 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'single_text', 'input' => 'string', )); $form->submit('2.6.2010'); $this->assertEquals('2010-06-02', $form->getData()); $this->assertEquals('02.06.2010', $form->getViewData()); } public function testSubmitFromSingleTextTimestamp() { // we test against "de_DE", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_DE'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => \IntlDateFormatter::MEDIUM, 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'single_text', 'input' => 'timestamp', )); $form->submit('2.6.2010'); $dateTime = new \DateTime('2010-06-02 UTC'); $this->assertEquals($dateTime->format('U'), $form->getData()); $this->assertEquals('02.06.2010', $form->getViewData()); } public function testSubmitFromSingleTextRaw() { // we test against "de_DE", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_DE'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => \IntlDateFormatter::MEDIUM, 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'single_text', 'input' => 'array', )); $form->submit('2.6.2010'); $output = array( 'day' => '2', 'month' => '6', 'year' => '2010', ); $this->assertEquals($output, $form->getData()); $this->assertEquals('02.06.2010', $form->getViewData()); } public function testSubmitFromText() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'text', )); $text = array( 'day' => '2', 'month' => '6', 'year' => '2010', ); $form->submit($text); $dateTime = new \DateTime('2010-06-02 UTC'); $this->assertDateTimeEquals($dateTime, $form->getData()); $this->assertEquals($text, $form->getViewData()); } public function testSubmitFromChoice() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'choice', 'years' => array(2010), )); $text = array( 'day' => '2', 'month' => '6', 'year' => '2010', ); $form->submit($text); $dateTime = new \DateTime('2010-06-02 UTC'); $this->assertDateTimeEquals($dateTime, $form->getData()); $this->assertEquals($text, $form->getViewData()); } public function testSubmitFromChoiceEmpty() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'choice', 'required' => false, )); $text = array( 'day' => '', 'month' => '', 'year' => '', ); $form->submit($text); $this->assertNull($form->getData()); $this->assertEquals($text, $form->getViewData()); } public function testSubmitFromInputDateTimeDifferentPattern() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'format' => 'MM*yyyy*dd', 'widget' => 'single_text', 'input' => 'datetime', )); $form->submit('06*2010*02'); $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData()); $this->assertEquals('06*2010*02', $form->getViewData()); } public function testSubmitFromInputStringDifferentPattern() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'format' => 'MM*yyyy*dd', 'widget' => 'single_text', 'input' => 'string', )); $form->submit('06*2010*02'); $this->assertEquals('2010-06-02', $form->getData()); $this->assertEquals('06*2010*02', $form->getViewData()); } public function testSubmitFromInputTimestampDifferentPattern() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'format' => 'MM*yyyy*dd', 'widget' => 'single_text', 'input' => 'timestamp', )); $form->submit('06*2010*02'); $dateTime = new \DateTime('2010-06-02 UTC'); $this->assertEquals($dateTime->format('U'), $form->getData()); $this->assertEquals('06*2010*02', $form->getViewData()); } public function testSubmitFromInputRawDifferentPattern() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'format' => 'MM*yyyy*dd', 'widget' => 'single_text', 'input' => 'array', )); $form->submit('06*2010*02'); $output = array( 'day' => '2', 'month' => '6', 'year' => '2010', ); $this->assertEquals($output, $form->getData()); $this->assertEquals('06*2010*02', $form->getViewData()); } /** * @dataProvider provideDateFormats */ public function testDatePatternWithFormatOption($format, $pattern) { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => $format, )) ->createView(); $this->assertEquals($pattern, $view->vars['date_pattern']); } public function provideDateFormats() { return array( array('dMy', '{{ day }}{{ month }}{{ year }}'), array('d-M-yyyy', '{{ day }}-{{ month }}-{{ year }}'), array('M d y', '{{ month }} {{ day }} {{ year }}'), ); } /** * This test is to check that the strings '0', '1', '2', '3' are not accepted * as valid IntlDateFormatter constants for FULL, LONG, MEDIUM or SHORT respectively. * * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException */ public function testThrowExceptionIfFormatIsNoPattern() { $this->factory->create(static::TESTED_TYPE, null, array( 'format' => '0', 'widget' => 'single_text', 'input' => 'string', )); } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException * @expectedExceptionMessage The "format" option should contain the letters "y", "M" and "d". Its current value is "yy". */ public function testThrowExceptionIfFormatDoesNotContainYearMonthAndDay() { $this->factory->create(static::TESTED_TYPE, null, array( 'months' => array(6, 7), 'format' => 'yy', )); } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException * @expectedExceptionMessage The "format" option should contain the letters "y", "M" or "d". Its current value is "wrong". */ public function testThrowExceptionIfFormatMissesYearMonthAndDayWithSingleTextWidget() { $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'single_text', 'format' => 'wrong', )); } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException */ public function testThrowExceptionIfFormatIsNoConstant() { $this->factory->create(static::TESTED_TYPE, null, array( 'format' => 105, )); } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException */ public function testThrowExceptionIfFormatIsInvalid() { $this->factory->create(static::TESTED_TYPE, null, array( 'format' => array(), )); } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException */ public function testThrowExceptionIfYearsIsInvalid() { $this->factory->create(static::TESTED_TYPE, null, array( 'years' => 'bad value', )); } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException */ public function testThrowExceptionIfMonthsIsInvalid() { $this->factory->create(static::TESTED_TYPE, null, array( 'months' => 'bad value', )); } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException */ public function testThrowExceptionIfDaysIsInvalid() { $this->factory->create(static::TESTED_TYPE, null, array( 'days' => 'bad value', )); } public function testSetDataWithNegativeTimezoneOffsetStringInput() { // we test against "de_DE", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_DE'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => \IntlDateFormatter::MEDIUM, 'model_timezone' => 'UTC', 'view_timezone' => 'America/New_York', 'input' => 'string', 'widget' => 'single_text', )); $form->setData('2010-06-02'); // 2010-06-02 00:00:00 UTC // 2010-06-01 20:00:00 UTC-4 $this->assertEquals('01.06.2010', $form->getViewData()); } public function testSetDataWithNegativeTimezoneOffsetDateTimeInput() { // we test against "de_DE", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_DE'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => \IntlDateFormatter::MEDIUM, 'model_timezone' => 'UTC', 'view_timezone' => 'America/New_York', 'input' => 'datetime', 'widget' => 'single_text', )); $dateTime = new \DateTime('2010-06-02 UTC'); $form->setData($dateTime); // 2010-06-02 00:00:00 UTC // 2010-06-01 20:00:00 UTC-4 $this->assertDateTimeEquals($dateTime, $form->getData()); $this->assertEquals('01.06.2010', $form->getViewData()); } public function testYearsOption() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'years' => array(2010, 2011), )); $view = $form->createView(); $this->assertEquals(array( new ChoiceView('2010', '2010', '2010'), new ChoiceView('2011', '2011', '2011'), ), $view['year']->vars['choices']); } public function testMonthsOption() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'months' => array(6, 7), 'format' => \IntlDateFormatter::SHORT, )); $view = $form->createView(); $this->assertEquals(array( new ChoiceView(6, '6', '06'), new ChoiceView(7, '7', '07'), ), $view['month']->vars['choices']); } public function testMonthsOptionShortFormat() { // we test against "de_AT", so we need the full implementation IntlTestHelper::requireFullIntl($this, '57.1'); \Locale::setDefault('de_AT'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'months' => array(1, 4), 'format' => 'dd.MMM.yy', )); $view = $form->createView(); $this->assertEquals(array( new ChoiceView(1, '1', 'Jän.'), new ChoiceView(4, '4', 'Apr.'), ), $view['month']->vars['choices']); } public function testMonthsOptionLongFormat() { // we test against "de_AT", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_AT'); $view = $this->factory->create(static::TESTED_TYPE, null, array( 'months' => array(1, 4), 'format' => 'dd.MMMM.yy', )) ->createView(); $this->assertEquals(array( new ChoiceView(1, '1', 'Jänner'), new ChoiceView(4, '4', 'April'), ), $view['month']->vars['choices']); } public function testMonthsOptionLongFormatWithDifferentTimezone() { // we test against "de_AT", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_AT'); $view = $this->factory->create(static::TESTED_TYPE, null, array( 'months' => array(1, 4), 'format' => 'dd.MMMM.yy', )) ->createView(); $this->assertEquals(array( new ChoiceView(1, '1', 'Jänner'), new ChoiceView(4, '4', 'April'), ), $view['month']->vars['choices']); } public function testIsDayWithinRangeReturnsTrueIfWithin() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'days' => array(6, 7), )) ->createView(); $this->assertEquals(array( new ChoiceView(6, '6', '06'), new ChoiceView(7, '7', '07'), ), $view['day']->vars['choices']); } public function testIsSynchronizedReturnsTrueIfChoiceAndCompletelyEmpty() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'choice', )); $form->submit(array( 'day' => '', 'month' => '', 'year' => '', )); $this->assertTrue($form->isSynchronized()); } public function testIsSynchronizedReturnsTrueIfChoiceAndCompletelyFilled() { $form = $this->factory->create(static::TESTED_TYPE, new \DateTime(), array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'choice', )); $form->submit(array( 'day' => '1', 'month' => '6', 'year' => '2010', )); $this->assertTrue($form->isSynchronized()); } public function testIsSynchronizedReturnsFalseIfChoiceAndDayEmpty() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'choice', )); $form->submit(array( 'day' => '', 'month' => '6', 'year' => '2010', )); $this->assertFalse($form->isSynchronized()); } public function testPassDatePatternToView() { // we test against "de_AT", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_AT'); $view = $this->factory->create(static::TESTED_TYPE) ->createView(); $this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']); } public function testPassDatePatternToViewDifferentFormat() { // we test against "de_AT", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('de_AT'); $view = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => \IntlDateFormatter::LONG, )) ->createView(); $this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']); } public function testPassDatePatternToViewDifferentPattern() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => 'MMyyyydd', )) ->createView(); $this->assertSame('{{ month }}{{ year }}{{ day }}', $view->vars['date_pattern']); } public function testPassDatePatternToViewDifferentPatternWithSeparators() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'format' => 'MM*yyyy*dd', )) ->createView(); $this->assertSame('{{ month }}*{{ year }}*{{ day }}', $view->vars['date_pattern']); } public function testDontPassDatePatternIfText() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'single_text', )) ->createView(); $this->assertFalse(isset($view->vars['date_pattern'])); } public function testDatePatternFormatWithQuotedStrings() { // we test against "es_ES", so we need the full implementation IntlTestHelper::requireFullIntl($this, false); \Locale::setDefault('es_ES'); $view = $this->factory->create(static::TESTED_TYPE, null, array( // EEEE, d 'de' MMMM 'de' y 'format' => \IntlDateFormatter::FULL, )) ->createView(); $this->assertEquals('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']); } public function testPassWidgetToView() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'single_text', )) ->createView(); $this->assertSame('single_text', $view->vars['widget']); } public function testInitializeWithDateTime() { // Throws an exception if "data_class" option is not explicitly set // to null in the type $this->assertInstanceOf('Symfony\Component\Form\FormInterface', $this->factory->create(static::TESTED_TYPE, new \DateTime())); } public function testSingleTextWidgetShouldUseTheRightInputType() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'single_text', )) ->createView(); $this->assertEquals('date', $view->vars['type']); } public function testPassDefaultPlaceholderToViewIfNotRequired() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'required' => false, )) ->createView(); $this->assertSame('', $view['year']->vars['placeholder']); $this->assertSame('', $view['month']->vars['placeholder']); $this->assertSame('', $view['day']->vars['placeholder']); } public function testPassNoPlaceholderToViewIfRequired() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'required' => true, )) ->createView(); $this->assertNull($view['year']->vars['placeholder']); $this->assertNull($view['month']->vars['placeholder']); $this->assertNull($view['day']->vars['placeholder']); } public function testPassPlaceholderAsString() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'placeholder' => 'Empty', )) ->createView(); $this->assertSame('Empty', $view['year']->vars['placeholder']); $this->assertSame('Empty', $view['month']->vars['placeholder']); $this->assertSame('Empty', $view['day']->vars['placeholder']); } /** * @group legacy */ public function testPassEmptyValueBC() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'empty_value' => 'Empty', )) ->createView(); $this->assertSame('Empty', $view['year']->vars['placeholder']); $this->assertSame('Empty', $view['month']->vars['placeholder']); $this->assertSame('Empty', $view['day']->vars['placeholder']); $this->assertSame('Empty', $view['year']->vars['empty_value']); $this->assertSame('Empty', $view['month']->vars['empty_value']); $this->assertSame('Empty', $view['day']->vars['empty_value']); } public function testPassPlaceholderAsArray() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'placeholder' => array( 'year' => 'Empty year', 'month' => 'Empty month', 'day' => 'Empty day', ), )) ->createView(); $this->assertSame('Empty year', $view['year']->vars['placeholder']); $this->assertSame('Empty month', $view['month']->vars['placeholder']); $this->assertSame('Empty day', $view['day']->vars['placeholder']); } public function testPassPlaceholderAsPartialArrayAddEmptyIfNotRequired() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'required' => false, 'placeholder' => array( 'year' => 'Empty year', 'day' => 'Empty day', ), )) ->createView(); $this->assertSame('Empty year', $view['year']->vars['placeholder']); $this->assertSame('', $view['month']->vars['placeholder']); $this->assertSame('Empty day', $view['day']->vars['placeholder']); } public function testPassPlaceholderAsPartialArrayAddNullIfRequired() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'required' => true, 'placeholder' => array( 'year' => 'Empty year', 'day' => 'Empty day', ), )) ->createView(); $this->assertSame('Empty year', $view['year']->vars['placeholder']); $this->assertNull($view['month']->vars['placeholder']); $this->assertSame('Empty day', $view['day']->vars['placeholder']); } public function testPassHtml5TypeIfSingleTextAndHtml5Format() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'single_text', )) ->createView(); $this->assertSame('date', $view->vars['type']); } public function testDontPassHtml5TypeIfHtml5NotAllowed() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'single_text', 'html5' => false, )) ->createView(); $this->assertFalse(isset($view->vars['type'])); } public function testDontPassHtml5TypeIfNotHtml5Format() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'single_text', 'format' => \IntlDateFormatter::MEDIUM, )) ->createView(); $this->assertFalse(isset($view->vars['type'])); } public function testDontPassHtml5TypeIfNotSingleText() { $view = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'text', )) ->createView(); $this->assertFalse(isset($view->vars['type'])); } public function provideCompoundWidgets() { return array( array('text'), array('choice'), ); } /** * @dataProvider provideCompoundWidgets */ public function testYearErrorsBubbleUp($widget) { $error = new FormError('Invalid!'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => $widget, )); $form['year']->addError($error); $this->assertSame(array(), iterator_to_array($form['year']->getErrors())); $this->assertSame(array($error), iterator_to_array($form->getErrors())); } /** * @dataProvider provideCompoundWidgets */ public function testMonthErrorsBubbleUp($widget) { $error = new FormError('Invalid!'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => $widget, )); $form['month']->addError($error); $this->assertSame(array(), iterator_to_array($form['month']->getErrors())); $this->assertSame(array($error), iterator_to_array($form->getErrors())); } /** * @dataProvider provideCompoundWidgets */ public function testDayErrorsBubbleUp($widget) { $error = new FormError('Invalid!'); $form = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => $widget, )); $form['day']->addError($error); $this->assertSame(array(), iterator_to_array($form['day']->getErrors())); $this->assertSame(array($error), iterator_to_array($form->getErrors())); } public function testYearsFor32BitsMachines() { if (4 !== PHP_INT_SIZE) { $this->markTestSkipped('PHP 32 bit is required.'); } $view = $this->factory->create(static::TESTED_TYPE, null, array( 'years' => range(1900, 2040), )) ->createView(); $listChoices = array(); foreach (range(1902, 2037) as $y) { $listChoices[] = new ChoiceView($y, $y, $y); } $this->assertEquals($listChoices, $view['year']->vars['choices']); } public function testSubmitNull($expected = null, $norm = null, $view = null) { parent::testSubmitNull($expected, $norm, array('year' => '', 'month' => '', 'day' => '')); } public function testSubmitNullWithSingleText() { $form = $this->factory->create(static::TESTED_TYPE, null, array( 'widget' => 'single_text', )); $form->submit(null); $this->assertNull($form->getData()); $this->assertNull($form->getNormData()); $this->assertSame('', $form->getViewData()); } }
kikutou/rentalmotor
vendor/symfony/form/Tests/Extension/Core/Type/DateTypeTest.php
PHP
gpl-2.0
29,797
/* * CCITT Fax Group 3 and 4 decompression * Copyright (c) 2008 Konstantin Shishkov * * This file is part of Libav. * * Libav 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. * * Libav 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 Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * CCITT Fax Group 3 and 4 decompression * @file * @author Konstantin Shishkov */ #ifndef AVCODEC_FAXCOMPR_H #define AVCODEC_FAXCOMPR_H #include "avcodec.h" #include "tiff.h" /** * initialize upacker code */ void ff_ccitt_unpack_init(void); /** * unpack data compressed with CCITT Group 3 1/2-D or Group 4 method */ int ff_ccitt_unpack(AVCodecContext *avctx, const uint8_t *src, int srcsize, uint8_t *dst, int height, int stride, enum TiffCompr compr, int opts); #endif /* AVCODEC_FAXCOMPR_H */
heiher/gst-ffmpeg
gst-libs/ext/libav/libavcodec/faxcompr.h
C
gpl-2.0
1,416
module Katello module UINotifications module Subscriptions class SCADisableSuccess < UINotifications::AbstractNotification private def blueprint @blueprint ||= NotificationBlueprint.find_by(name: 'sca_disable_success') end end end end end
snagoor/katello
app/services/katello/ui_notifications/subscriptions/sca_disable_success.rb
Ruby
gpl-2.0
298
<?php namespace TYPO3\CMS\Workspaces\Controller; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Backend\Utility\BackendUtility; use TYPO3\CMS\Core\Imaging\Icon; use TYPO3\CMS\Core\Utility\ExtensionManagementUtility; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Mvc\View\ViewInterface; use TYPO3\CMS\Workspaces\Service\WorkspaceService; /** * Review controller. */ class ReviewController extends AbstractController { /** * Set up the doc header properly here * * @param ViewInterface $view */ protected function initializeView(ViewInterface $view) { parent::initializeView($view); $this->registerButtons(); $this->view->getModuleTemplate()->setFlashMessageQueue($this->controllerContext->getFlashMessageQueue()); } /** * Registers the DocHeader buttons */ protected function registerButtons() { $buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar(); $currentRequest = $this->request; $moduleName = $currentRequest->getPluginName(); $getVars = $this->request->getArguments(); $extensionName = $currentRequest->getControllerExtensionName(); if (count($getVars) === 0) { $modulePrefix = strtolower('tx_' . $extensionName . '_' . $moduleName); $getVars = array('id', 'M', $modulePrefix); } $shortcutButton = $buttonBar->makeShortcutButton() ->setModuleName($moduleName) ->setGetVariables($getVars); $buttonBar->addButton($shortcutButton); } /** * Renders the review module user dependent with all workspaces. * The module will show all records of one workspace. * * @return void */ public function indexAction() { /** @var WorkspaceService $wsService */ $wsService = GeneralUtility::makeInstance(WorkspaceService::class); $this->view->assign('showGrid', !($GLOBALS['BE_USER']->workspace === 0 && !$GLOBALS['BE_USER']->isAdmin())); $this->view->assign('showAllWorkspaceTab', true); $this->view->assign('pageUid', GeneralUtility::_GP('id')); if (GeneralUtility::_GP('id')) { $pageRecord = BackendUtility::getRecord('pages', GeneralUtility::_GP('id')); if ($pageRecord) { $this->view->getModuleTemplate()->getDocHeaderComponent()->setMetaInformation($pageRecord); $this->view->assign('pageTitle', BackendUtility::getRecordTitle('pages', $pageRecord)); } } $this->view->assign('showLegend', !($GLOBALS['BE_USER']->workspace === 0 && !$GLOBALS['BE_USER']->isAdmin())); $wsList = $wsService->getAvailableWorkspaces(); $activeWorkspace = $GLOBALS['BE_USER']->workspace; $performWorkspaceSwitch = false; // Only admins see multiple tabs, we decided to use it this // way for usability reasons. Regular users might be confused // by switching workspaces with the tabs in a module. if (!$GLOBALS['BE_USER']->isAdmin()) { $wsCur = array($activeWorkspace => true); $wsList = array_intersect_key($wsList, $wsCur); } else { if ((string)GeneralUtility::_GP('workspace') !== '') { $switchWs = (int)GeneralUtility::_GP('workspace'); if (in_array($switchWs, array_keys($wsList)) && $activeWorkspace != $switchWs) { $activeWorkspace = $switchWs; $GLOBALS['BE_USER']->setWorkspace($activeWorkspace); $performWorkspaceSwitch = true; BackendUtility::setUpdateSignal('updatePageTree'); } elseif ($switchWs == WorkspaceService::SELECT_ALL_WORKSPACES) { $this->redirect('fullIndex'); } } } $this->pageRenderer->addInlineSetting('Workspaces', 'isLiveWorkspace', (int)$GLOBALS['BE_USER']->workspace === 0); $this->pageRenderer->addInlineSetting('Workspaces', 'workspaceTabs', $this->prepareWorkspaceTabs($wsList, $activeWorkspace)); $this->pageRenderer->addInlineSetting('Workspaces', 'activeWorkspaceId', $activeWorkspace); $this->pageRenderer->addInlineSetting('FormEngine', 'moduleUrl', BackendUtility::getModuleUrl('record_edit')); $this->view->assign('performWorkspaceSwitch', $performWorkspaceSwitch); $this->view->assign('workspaceList', $wsList); $this->view->assign('activeWorkspaceUid', $activeWorkspace); $this->view->assign('activeWorkspaceTitle', WorkspaceService::getWorkspaceTitle($activeWorkspace)); if ($wsService->canCreatePreviewLink(GeneralUtility::_GP('id'), $activeWorkspace)) { $buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar(); $iconFactory = $this->view->getModuleTemplate()->getIconFactory(); $showButton = $buttonBar->makeLinkButton() ->setHref('#') ->setOnClick('TYPO3.Workspaces.Actions.generateWorkspacePreviewLinksForAllLanguages();return false;') ->setTitle($this->getLanguageService()->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang.xlf:tooltip.generatePagePreview')) ->setIcon($iconFactory->getIcon('module-workspaces-action-preview-link', Icon::SIZE_SMALL)); $buttonBar->addButton($showButton); } $this->view->assign('showPreviewLink', $wsService->canCreatePreviewLink(GeneralUtility::_GP('id'), $activeWorkspace)); $GLOBALS['BE_USER']->setAndSaveSessionData('tx_workspace_activeWorkspace', $activeWorkspace); } /** * Renders the review module user dependent. * The module will show all records of all workspaces. * * @return void */ public function fullIndexAction() { $wsService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\WorkspaceService::class); $wsList = $wsService->getAvailableWorkspaces(); if (!$GLOBALS['BE_USER']->isAdmin()) { $activeWorkspace = $GLOBALS['BE_USER']->workspace; $wsCur = array($activeWorkspace => true); $wsList = array_intersect_key($wsList, $wsCur); } $this->pageRenderer->addInlineSetting('Workspaces', 'workspaceTabs', $this->prepareWorkspaceTabs($wsList, WorkspaceService::SELECT_ALL_WORKSPACES)); $this->pageRenderer->addInlineSetting('Workspaces', 'activeWorkspaceId', WorkspaceService::SELECT_ALL_WORKSPACES); $this->view->assign('pageUid', GeneralUtility::_GP('id')); $this->view->assign('showGrid', true); $this->view->assign('showLegend', true); $this->view->assign('showAllWorkspaceTab', true); $this->view->assign('workspaceList', $wsList); $this->view->assign('activeWorkspaceUid', WorkspaceService::SELECT_ALL_WORKSPACES); $this->view->assign('showPreviewLink', false); $GLOBALS['BE_USER']->setAndSaveSessionData('tx_workspace_activeWorkspace', WorkspaceService::SELECT_ALL_WORKSPACES); // set flag for javascript $this->pageRenderer->addInlineSetting('Workspaces', 'allView', '1'); } /** * Renders the review module for a single page. This is used within the * workspace-preview frame. * * @return void */ public function singleIndexAction() { $wsService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\WorkspaceService::class); $wsList = $wsService->getAvailableWorkspaces(); $activeWorkspace = $GLOBALS['BE_USER']->workspace; $wsCur = array($activeWorkspace => true); $wsList = array_intersect_key($wsList, $wsCur); $backendDomain = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'); $this->view->assign('pageUid', GeneralUtility::_GP('id')); $this->view->assign('showGrid', true); $this->view->assign('showAllWorkspaceTab', false); $this->view->assign('workspaceList', $wsList); $this->view->assign('backendDomain', $backendDomain); // Setting the document.domain early before JavScript // libraries are loaded, try to access top frame reference // and possibly run into some CORS issue $this->pageRenderer->setMetaCharsetTag( $this->pageRenderer->getMetaCharsetTag() . LF . GeneralUtility::wrapJS('document.domain = ' . GeneralUtility::quoteJSvalue($backendDomain) . ';') ); $this->pageRenderer->addInlineSetting('Workspaces', 'singleView', '1'); } /** * Initializes the controller before invoking an action method. * * @return void */ protected function initializeAction() { parent::initializeAction(); $backendRelPath = ExtensionManagementUtility::extRelPath('backend'); $this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/ExtDirect.StateProvider.js'); if (WorkspaceService::isOldStyleWorkspaceUsed()) { $flashMessage = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessage::class, $GLOBALS['LANG']->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang.xlf:warning.oldStyleWorkspaceInUser'), '', \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING); /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */ $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class); /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */ $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier(); $defaultFlashMessageQueue->enqueue($flashMessage); } $this->pageRenderer->loadExtJS(); $states = $GLOBALS['BE_USER']->uc['moduleData']['Workspaces']['States']; $this->pageRenderer->addInlineSetting('Workspaces', 'States', $states); // Load JavaScript: $this->pageRenderer->addExtDirectCode(array( 'TYPO3.Workspaces' )); $this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/extjs/ux/Ext.grid.RowExpander.js'); $this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/extjs/ux/Ext.app.SearchField.js'); $this->pageRenderer->addJsFile($backendRelPath . 'Resources/Public/JavaScript/extjs/ux/Ext.ux.FitToParent.js'); $resourcePath = ExtensionManagementUtility::extRelPath('workspaces') . 'Resources/Public/JavaScript/'; // @todo Integrate additional stylesheet resources $this->pageRenderer->addCssFile($resourcePath . 'gridfilters/css/GridFilters.css'); $this->pageRenderer->addCssFile($resourcePath . 'gridfilters/css/RangeMenu.css'); $filters = array( $resourcePath . 'gridfilters/menu/RangeMenu.js', $resourcePath . 'gridfilters/menu/ListMenu.js', $resourcePath . 'gridfilters/GridFilters.js', $resourcePath . 'gridfilters/filter/Filter.js', $resourcePath . 'gridfilters/filter/StringFilter.js', $resourcePath . 'gridfilters/filter/DateFilter.js', $resourcePath . 'gridfilters/filter/ListFilter.js', $resourcePath . 'gridfilters/filter/NumericFilter.js', $resourcePath . 'gridfilters/filter/BooleanFilter.js', $resourcePath . 'gridfilters/filter/BooleanFilter.js', ); $custom = $this->getAdditionalResourceService()->getJavaScriptResources(); $resources = array( $resourcePath . 'Component/RowDetailTemplate.js', $resourcePath . 'Component/RowExpander.js', $resourcePath . 'Component/TabPanel.js', $resourcePath . 'Store/mainstore.js', $resourcePath . 'configuration.js', $resourcePath . 'helpers.js', $resourcePath . 'actions.js', $resourcePath . 'component.js', $resourcePath . 'toolbar.js', $resourcePath . 'grid.js', $resourcePath . 'workspaces.js' ); $javaScriptFiles = array_merge($filters, $custom, $resources); foreach ($javaScriptFiles as $javaScriptFile) { $this->pageRenderer->addJsFile($javaScriptFile); } foreach ($this->getAdditionalResourceService()->getLocalizationResources() as $localizationResource) { $this->pageRenderer->addInlineLanguageLabelFile($localizationResource); } $this->pageRenderer->addInlineSetting('FormEngine', 'moduleUrl', BackendUtility::getModuleUrl('record_edit')); $this->pageRenderer->addInlineSetting('RecordHistory', 'moduleUrl', BackendUtility::getModuleUrl('record_history')); } /** * Prepares available workspace tabs. * * @param array $workspaceList * @param int $activeWorkspace * @return array */ protected function prepareWorkspaceTabs(array $workspaceList, $activeWorkspace) { $tabs = array(); if ($activeWorkspace !== WorkspaceService::SELECT_ALL_WORKSPACES) { $tabs[] = array( 'title' => $workspaceList[$activeWorkspace], 'itemId' => 'workspace-' . $activeWorkspace, 'workspaceId' => $activeWorkspace, 'triggerUrl' => $this->getModuleUri($activeWorkspace), ); } $tabs[] = array( 'title' => 'All workspaces', 'itemId' => 'workspace-' . WorkspaceService::SELECT_ALL_WORKSPACES, 'workspaceId' => WorkspaceService::SELECT_ALL_WORKSPACES, 'triggerUrl' => $this->getModuleUri(WorkspaceService::SELECT_ALL_WORKSPACES), ); foreach ($workspaceList as $workspaceId => $workspaceTitle) { if ($workspaceId === $activeWorkspace) { continue; } $tabs[] = array( 'title' => $workspaceTitle, 'itemId' => 'workspace-' . $workspaceId, 'workspaceId' => $workspaceId, 'triggerUrl' => $this->getModuleUri($workspaceId), ); } return $tabs; } /** * Gets the module URI. * * @param int $workspaceId * @return string */ protected function getModuleUri($workspaceId) { $parameters = array( 'id' => (int)$this->pageId, 'workspace' => (int)$workspaceId, ); // The "all workspaces" tab is handled in fullIndexAction // which is required as additional GET parameter in the URI then if ($workspaceId === WorkspaceService::SELECT_ALL_WORKSPACES) { $this->uriBuilder->reset()->uriFor('fullIndex'); $parameters = array_merge($parameters, $this->uriBuilder->getArguments()); } return BackendUtility::getModuleUrl('web_WorkspacesWorkspaces', $parameters); } /** * @return \TYPO3\CMS\Lang\LanguageService */ protected function getLanguageService() { return $GLOBALS['LANG']; } }
liayn/TYPO3.CMS
typo3/sysext/workspaces/Classes/Controller/ReviewController.php
PHP
gpl-2.0
15,544
/* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef MDSS_DSI_H #define MDSS_DSI_H #include <linux/list.h> #include <linux/mdss_io_util.h> #include <mach/scm-io.h> #include <linux/irqreturn.h> #include <linux/pinctrl/consumer.h> #include "mdss_panel.h" #include "mdss_dsi_cmd.h" #define MMSS_SERDES_BASE_PHY 0x04f01000 /* mmss (De)Serializer CFG */ #define MIPI_OUTP(addr, data) writel_relaxed((data), (addr)) #define MIPI_INP(addr) readl_relaxed(addr) #define MIPI_OUTP_SECURE(addr, data) writel_relaxed((data), (addr)) #define MIPI_INP_SECURE(addr) readl_relaxed(addr) #define MIPI_DSI_PRIM 1 #define MIPI_DSI_SECD 2 #define MIPI_DSI_PANEL_VGA 0 #define MIPI_DSI_PANEL_WVGA 1 #define MIPI_DSI_PANEL_WVGA_PT 2 #define MIPI_DSI_PANEL_FWVGA_PT 3 #define MIPI_DSI_PANEL_WSVGA_PT 4 #define MIPI_DSI_PANEL_QHD_PT 5 #define MIPI_DSI_PANEL_WXGA 6 #define MIPI_DSI_PANEL_WUXGA 7 #define MIPI_DSI_PANEL_720P_PT 8 #define DSI_PANEL_MAX 8 enum { /* mipi dsi panel */ DSI_VIDEO_MODE, DSI_CMD_MODE, }; enum { ST_DSI_CLK_OFF, ST_DSI_SUSPEND, ST_DSI_RESUME, ST_DSI_PLAYING, ST_DSI_NUM }; enum { EV_DSI_UPDATE, EV_DSI_DONE, EV_DSI_TOUT, EV_DSI_NUM }; enum { LANDSCAPE = 1, PORTRAIT = 2, }; enum dsi_trigger_type { DSI_CMD_MODE_DMA, DSI_CMD_MODE_MDP, }; enum dsi_panel_bl_ctrl { UNKNOWN_CTRL, BL_PWM, BL_WLED, BL_DCS_CMD, BL_EXTERNAL, }; enum dsi_ctrl_op_mode { DSI_LP_MODE, DSI_HS_MODE, }; enum dsi_lane_map_type { DSI_LANE_MAP_0123, DSI_LANE_MAP_3012, DSI_LANE_MAP_2301, DSI_LANE_MAP_1230, DSI_LANE_MAP_0321, DSI_LANE_MAP_1032, DSI_LANE_MAP_2103, DSI_LANE_MAP_3210, }; #define CTRL_STATE_UNKNOWN 0x00 #define CTRL_STATE_PANEL_INIT BIT(0) #define CTRL_STATE_MDP_ACTIVE BIT(1) #define DSI_NON_BURST_SYNCH_PULSE 0 #define DSI_NON_BURST_SYNCH_EVENT 1 #define DSI_BURST_MODE 2 #define DSI_RGB_SWAP_RGB 0 #define DSI_RGB_SWAP_RBG 1 #define DSI_RGB_SWAP_BGR 2 #define DSI_RGB_SWAP_BRG 3 #define DSI_RGB_SWAP_GRB 4 #define DSI_RGB_SWAP_GBR 5 #define DSI_VIDEO_DST_FORMAT_RGB565 0 #define DSI_VIDEO_DST_FORMAT_RGB666 1 #define DSI_VIDEO_DST_FORMAT_RGB666_LOOSE 2 #define DSI_VIDEO_DST_FORMAT_RGB888 3 #define DSI_CMD_DST_FORMAT_RGB111 0 #define DSI_CMD_DST_FORMAT_RGB332 3 #define DSI_CMD_DST_FORMAT_RGB444 4 #define DSI_CMD_DST_FORMAT_RGB565 6 #define DSI_CMD_DST_FORMAT_RGB666 7 #define DSI_CMD_DST_FORMAT_RGB888 8 #define DSI_INTR_ERROR_MASK BIT(25) #define DSI_INTR_ERROR BIT(24) #define DSI_INTR_BTA_DONE_MASK BIT(21) #define DSI_INTR_BTA_DONE BIT(20) #define DSI_INTR_VIDEO_DONE_MASK BIT(17) #define DSI_INTR_VIDEO_DONE BIT(16) #define DSI_INTR_CMD_MDP_DONE_MASK BIT(9) #define DSI_INTR_CMD_MDP_DONE BIT(8) #define DSI_INTR_CMD_DMA_DONE_MASK BIT(1) #define DSI_INTR_CMD_DMA_DONE BIT(0) #define DSI_CMD_TRIGGER_NONE 0x0 /* mdp trigger */ #define DSI_CMD_TRIGGER_TE 0x02 #define DSI_CMD_TRIGGER_SW 0x04 #define DSI_CMD_TRIGGER_SW_SEOF 0x05 /* cmd dma only */ #define DSI_CMD_TRIGGER_SW_TE 0x06 #define DSI_VIDEO_TERM BIT(16) #define DSI_MDP_TERM BIT(8) #define DSI_BTA_TERM BIT(1) #define DSI_CMD_TERM BIT(0) extern struct device dsi_dev; extern u32 dsi_irq; extern struct mdss_dsi_ctrl_pdata *ctrl_list[]; struct dsiphy_pll_divider_config { u32 clk_rate; u32 fb_divider; u32 ref_divider_ratio; u32 bit_clk_divider; /* oCLK1 */ u32 byte_clk_divider; /* oCLK2 */ u32 analog_posDiv; u32 digital_posDiv; }; extern struct dsiphy_pll_divider_config pll_divider_config; struct dsi_clk_mnd_table { u8 lanes; u8 bpp; u8 pll_digital_posDiv; u8 pclk_m; u8 pclk_n; u8 pclk_d; }; static const struct dsi_clk_mnd_table mnd_table[] = { { 1, 2, 8, 1, 1, 0}, { 1, 3, 12, 1, 1, 0}, { 2, 2, 4, 1, 1, 0}, { 2, 3, 6, 1, 1, 0}, { 3, 2, 1, 3, 8, 4}, { 3, 3, 4, 1, 1, 0}, { 4, 2, 2, 1, 1, 0}, { 4, 3, 3, 1, 1, 0}, }; struct dsi_clk_desc { u32 src; u32 m; u32 n; u32 d; u32 mnd_mode; u32 pre_div_func; }; struct dsi_panel_cmds { char *buf; int blen; struct dsi_cmd_desc *cmds; int cmd_cnt; int link_state; }; struct dsi_kickoff_action { struct list_head act_entry; void (*action) (void *); void *data; }; struct dsi_drv_cm_data { struct regulator *vdd_vreg; struct regulator *vdd_io_vreg; struct regulator *vdda_vreg; int broadcast_enable; }; struct dsi_pinctrl_res { struct pinctrl *pinctrl; struct pinctrl_state *gpio_state_active; struct pinctrl_state *gpio_state_suspend; }; enum { DSI_CTRL_0, DSI_CTRL_1, DSI_CTRL_MAX, }; /* DSI controller #0 is always treated as a master in broadcast mode */ #define DSI_CTRL_MASTER DSI_CTRL_0 #define DSI_CTRL_SLAVE DSI_CTRL_1 #define DSI_BUS_CLKS BIT(0) #define DSI_LINK_CLKS BIT(1) #define DSI_ALL_CLKS ((DSI_BUS_CLKS) | (DSI_LINK_CLKS)) #define DSI_EV_PLL_UNLOCKED 0x0001 #define DSI_EV_MDP_FIFO_UNDERFLOW 0x0002 #define DSI_EV_MDP_BUSY_RELEASE 0x80000000 struct mdss_dsi_ctrl_pdata { int ndx; /* panel_num */ int (*on) (struct mdss_panel_data *pdata); int (*off) (struct mdss_panel_data *pdata); int (*partial_update_fnc) (struct mdss_panel_data *pdata); int (*check_status) (struct mdss_dsi_ctrl_pdata *pdata); int (*cmdlist_commit)(struct mdss_dsi_ctrl_pdata *ctrl, int from_mdp); struct mdss_panel_data panel_data; unsigned char *ctrl_base; struct dss_io_data ctrl_io; struct dss_io_data mmss_misc_io; struct dss_io_data phy_io; int reg_size; u32 bus_clk_cnt; u32 link_clk_cnt; u32 flags; struct clk *mdp_core_clk; struct clk *ahb_clk; struct clk *axi_clk; struct clk *mmss_misc_ahb_clk; struct clk *byte_clk; struct clk *esc_clk; struct clk *pixel_clk; u8 ctrl_state; int panel_mode; int irq_cnt; int rst_gpio; int disp_en_gpio; int disp_te_gpio; int bklt_en_gpio; int mode_gpio; int disp_te_gpio_requested; int bklt_ctrl; /* backlight ctrl */ int pwm_period; int pwm_pmic_gpio; int pwm_lpg_chan; int bklt_max; int new_fps; int pwm_enabled; int idle; bool blanked; struct pwm_device *pwm_bl; struct dsi_drv_cm_data shared_pdata; u32 pclk_rate; u32 byte_clk_rate; struct dss_module_power power_data; u32 dsi_irq_mask; struct mdss_hw *dsi_hw; struct mdss_panel_recovery *recovery; struct dsi_panel_cmds on_cmds; struct dsi_panel_cmds off_cmds; struct dsi_panel_cmds idle_on_cmds; struct dsi_panel_cmds idle_off_cmds; struct dsi_panel_cmds low_fps_mode_on_cmds; struct dsi_panel_cmds low_fps_mode_off_cmds; struct dcs_cmd_list cmdlist; struct completion dma_comp; struct completion mdp_comp; struct completion video_comp; struct completion bta_comp; spinlock_t irq_lock; spinlock_t mdp_lock; int mdp_busy; struct mutex mutex; struct mutex cmd_mutex; struct mutex suspend_mutex; bool ulps; struct mutex ulps_lock; unsigned int ulps_ref_count; struct dsi_buf tx_buf; struct dsi_buf rx_buf; struct dsi_pinctrl_res pin_res; }; int dsi_panel_device_register(struct device_node *pan_node, struct mdss_dsi_ctrl_pdata *ctrl_pdata); int mdss_dsi_cmds_tx(struct mdss_dsi_ctrl_pdata *ctrl, struct dsi_cmd_desc *cmds, int cnt); int mdss_dsi_cmds_rx(struct mdss_dsi_ctrl_pdata *ctrl, struct dsi_cmd_desc *cmds, int rlen); void mdss_dsi_host_init(struct mdss_panel_data *pdata); void mdss_dsi_op_mode_config(int mode, struct mdss_panel_data *pdata); void mdss_dsi_cmd_mode_ctrl(int enable); void mdp4_dsi_cmd_trigger(void); void mdss_dsi_cmd_mdp_start(struct mdss_dsi_ctrl_pdata *ctrl); void mdss_dsi_cmd_bta_sw_trigger(struct mdss_panel_data *pdata); void mdss_dsi_ack_err_status(struct mdss_dsi_ctrl_pdata *ctrl); int mdss_dsi_clk_ctrl(struct mdss_dsi_ctrl_pdata *ctrl, u8 clk_type, int enable); void mdss_dsi_clk_req(struct mdss_dsi_ctrl_pdata *ctrl, int enable); void mdss_dsi_controller_cfg(int enable, struct mdss_panel_data *pdata); void mdss_dsi_sw_reset(struct mdss_panel_data *pdata); irqreturn_t mdss_dsi_isr(int irq, void *ptr); void mdss_dsi_irq_handler_config(struct mdss_dsi_ctrl_pdata *ctrl_pdata); void mdss_dsi_set_tx_power_mode(int mode, struct mdss_panel_data *pdata); int mdss_dsi_clk_div_config(struct mdss_panel_info *panel_info, int frame_rate); int mdss_dsi_clk_init(struct platform_device *pdev, struct mdss_dsi_ctrl_pdata *ctrl_pdata); void mdss_dsi_clk_deinit(struct mdss_dsi_ctrl_pdata *ctrl_pdata); int mdss_dsi_enable_bus_clocks(struct mdss_dsi_ctrl_pdata *ctrl_pdata); void mdss_dsi_disable_bus_clocks(struct mdss_dsi_ctrl_pdata *ctrl_pdata); int mdss_dsi_panel_reset(struct mdss_panel_data *pdata, int enable); void mdss_dsi_phy_disable(struct mdss_dsi_ctrl_pdata *ctrl); void mdss_dsi_phy_init(struct mdss_panel_data *pdata); void mdss_dsi_phy_sw_reset(unsigned char *ctrl_base); void mdss_dsi_cmd_test_pattern(struct mdss_dsi_ctrl_pdata *ctrl); void mdss_dsi_video_test_pattern(struct mdss_dsi_ctrl_pdata *ctrl); void mdss_dsi_panel_pwm_cfg(struct mdss_dsi_ctrl_pdata *ctrl); void mdss_dsi_ctrl_init(struct mdss_dsi_ctrl_pdata *ctrl); void mdss_dsi_cmd_mdp_busy(struct mdss_dsi_ctrl_pdata *ctrl); void mdss_dsi_wait4video_done(struct mdss_dsi_ctrl_pdata *ctrl); int mdss_dsi_cmdlist_commit(struct mdss_dsi_ctrl_pdata *ctrl, int from_mdp); void mdss_dsi_cmdlist_kickoff(int intf); int mdss_dsi_bta_status_check(struct mdss_dsi_ctrl_pdata *ctrl); bool __mdss_dsi_clk_enabled(struct mdss_dsi_ctrl_pdata *ctrl, u8 clk_type); int mdss_dsi_ulps_config(struct mdss_dsi_ctrl_pdata *ctrl, int enable); int mdss_dsi_panel_init(struct device_node *node, struct mdss_dsi_ctrl_pdata *ctrl_pdata, bool cmd_cfg_cont_splash); void mdss_dsi_panel_low_fps_mode(struct mdss_dsi_ctrl_pdata *ctrl, int enable); static inline bool mdss_dsi_broadcast_mode_enabled(void) { return ctrl_list[DSI_CTRL_MASTER]->shared_pdata.broadcast_enable && ctrl_list[DSI_CTRL_SLAVE] && ctrl_list[DSI_CTRL_SLAVE]->shared_pdata.broadcast_enable; } static inline struct mdss_dsi_ctrl_pdata *mdss_dsi_get_master_ctrl(void) { if (mdss_dsi_broadcast_mode_enabled()) return ctrl_list[DSI_CTRL_MASTER]; else return NULL; } static inline struct mdss_dsi_ctrl_pdata *mdss_dsi_get_slave_ctrl(void) { if (mdss_dsi_broadcast_mode_enabled()) return ctrl_list[DSI_CTRL_SLAVE]; else return NULL; } static inline bool mdss_dsi_is_master_ctrl(struct mdss_dsi_ctrl_pdata *ctrl) { return mdss_dsi_broadcast_mode_enabled() && (ctrl->ndx == DSI_CTRL_MASTER); } static inline bool mdss_dsi_is_slave_ctrl(struct mdss_dsi_ctrl_pdata *ctrl) { return mdss_dsi_broadcast_mode_enabled() && (ctrl->ndx == DSI_CTRL_SLAVE); } static inline struct mdss_dsi_ctrl_pdata *mdss_dsi_get_ctrl_by_index(int ndx) { if (ndx >= DSI_CTRL_MAX) return NULL; return ctrl_list[ndx]; } #endif /* MDSS_DSI_H */
DC07/android_kernel_lge_dory
drivers/video/msm/mdss/mdss_dsi.h
C
gpl-2.0
11,076
using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.ComponentModel; namespace Lcc.Entrada.Articulos { public partial class DetalleComprobante : ControlSeleccionElemento { protected bool m_MostrarExistencias, m_DiscriminarIva = false, m_AplicarIva = true; protected Precios m_Precio = Precios.Pvp; protected ControlesSock m_ControlStock = ControlesSock.Ambos; protected Lbl.Articulos.ColeccionDatosSeguimiento m_DatosSeguimiento = new Lbl.Articulos.ColeccionDatosSeguimiento(); protected Lbl.Impuestos.Alicuota m_Alicuota = null; protected decimal m_ImporteUnitarioIva = 0m; new public event System.Windows.Forms.KeyEventHandler KeyDown; public event System.EventHandler ImportesChanged; public event System.EventHandler ObtenerDatosSeguimiento; public DetalleComprobante() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (Lfx.Workspace.Master != null) { switch (m_Precio) { case Precios.Costo: EntradaUnitario.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.DecimalesCosto; EntradaImporte.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.DecimalesCosto; break; case Precios.Pvp: EntradaUnitario.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales; EntradaImporte.DecimalPlaces = Lfx.Workspace.Master.CurrentConfig.Moneda.Decimales; break; } } } public ControlesSock ControlStock { get { return m_ControlStock; } set { m_ControlStock = value; PonerFiltros(); } } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] override public bool ShowChanged { set { base.ShowChanged = value; EntradaArticulo.ShowChanged = value; EntradaDescuento.ShowChanged = value; EntradaCantidad.ShowChanged = value; EntradaUnitario.ShowChanged = value; } } [EditorBrowsable(EditorBrowsableState.Never), System.ComponentModel.Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool AutoUpdate { get { return EntradaArticulo.AutoUpdate; } set { EntradaArticulo.AutoUpdate = value; } } public bool PermiteCrear { get { return EntradaArticulo.CanCreate; } set { EntradaArticulo.CanCreate = value; } } [EditorBrowsable(EditorBrowsableState.Never), System.ComponentModel.Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override bool IsEmpty { get { return EntradaArticulo.IsEmpty; } } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] new public int ValueInt { get { return EntradaArticulo.ValueInt; } set { if (EntradaArticulo.ValueInt != value) EntradaArticulo.ValueInt = value; } } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Lbl.Articulos.ColeccionDatosSeguimiento DatosSeguimiento { get { return m_DatosSeguimiento; } set { if (m_DatosSeguimiento != value) { this.Changed = true; } m_DatosSeguimiento = value; if (m_DatosSeguimiento == null || m_DatosSeguimiento.Count == 0) { LabelSerials.Visible = false; } else { LabelSerials.Text = "Seguimiento: " + m_DatosSeguimiento.ToString(); LabelSerials.Visible = true; if (this.Cantidad != m_DatosSeguimiento.CantidadTotal) this.Cantidad = m_DatosSeguimiento.CantidadTotal; } } } public bool MuestraPrecio { get { return EntradaUnitario.Visible; } set { EntradaUnitario.Visible = value; EntradaIva.Visible = value; EntradaCantidad.Visible = value; EntradaDescuento.Visible = value; EntradaImporte.Visible = value; if (value) EntradaArticulo.Width = EntradaUnitario.Left - 1; else EntradaArticulo.Width = this.Width; } } // Oculta al changed de abajo [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] new public bool Changed { get { return EntradaArticulo.Changed || EntradaCantidad.Changed || EntradaUnitario.Changed || EntradaDescuento.Changed; } set { EntradaArticulo.Changed = value; EntradaDescuento.Changed = value; EntradaCantidad.Changed = value; EntradaUnitario.Changed = value; } } public Precios UsarPrecio { get { return m_Precio; } set { m_Precio = value; this.CambiarArticulo(this.Articulo); this.Changed = false; } } public bool BloquearAtriculo { get { return EntradaArticulo.TemporaryReadOnly; } set { EntradaArticulo.TemporaryReadOnly = value; } } public bool BloquearCantidad { get { return EntradaCantidad.TemporaryReadOnly; } set { EntradaCantidad.TemporaryReadOnly = value; } } public bool BloquearPrecio { get { return EntradaUnitario.TemporaryReadOnly; } set { EntradaUnitario.ReadOnly = value; EntradaDescuento.ReadOnly = value || this.BloquearDescuento; } } public bool BloquearDescuento { get { return EntradaDescuento.TemporaryReadOnly; } set { EntradaDescuento.ReadOnly = value || this.BloquearPrecio; } } public bool MostrarExistencias { get { return m_MostrarExistencias; } set { m_MostrarExistencias = value; VerificarStock(); } } /// <summary> /// Indica si los precios se muestran con IVA discriminado. /// </summary> public bool DiscriminarIva { get { return m_DiscriminarIva; } set { bool AntesDiscriminaba = m_DiscriminarIva; m_DiscriminarIva = value; EntradaIva.Enabled = this.DiscriminarIva && this.AplicarIva; if (m_DiscriminarIva != AntesDiscriminaba && m_AplicarIva && m_Alicuota != null) { if (value) { // Antes no discriminaba y ahora sí this.EstablecerImporteUnitarioOriginal(this.ImporteUnitario / (1 + m_Alicuota.Porcentaje / 100m)); } else { // Antes discriminaba y ahora no this.EstablecerImporteUnitarioOriginal(this.ImporteUnitario); } this.RecalcularImporteFinal(); if (null != ImportesChanged) { ImportesChanged(this, null); } } this.RecalcularImporteFinal(); } } /// <summary> /// Indica si debe aplicar IVA al cliente. /// </summary> public bool AplicarIva { get { return m_AplicarIva; } set { bool AntesAplicaba = m_AplicarIva; m_AplicarIva = value; EntradaIva.Enabled = this.DiscriminarIva && this.AplicarIva; if (m_AplicarIva != AntesAplicaba && m_Alicuota != null) { decimal NuevoImporteUnitarioIva = this.ImporteUnitario * (m_Alicuota.Porcentaje / 100m); if (value) { // Antes no aplicaba y ahora sí this.EstablecerImporteUnitarioOriginal(this.ImporteUnitario); } else { // Antes aplicaba y ahora no this.EstablecerImporteUnitarioOriginal((this.ImporteUnitario + this.ImporteIvaDiscriminadoUnitario) / (1m + m_Alicuota.Porcentaje / 100m)); } this.RecalcularImporteFinal(); if (null != ImportesChanged) { ImportesChanged(this, null); } } } } public bool Required { get { return EntradaArticulo.Required; } set { EntradaArticulo.Required = value; } } [System.ComponentModel.Category("Datos")] public string FreeTextCode { get { return EntradaArticulo.FreeTextCode; } set { EntradaArticulo.FreeTextCode = value; } } public int UnitarioLeft { get { return EntradaUnitario.Left; } } public int DescuentoLeft { get { return EntradaDescuento.Left; } } public int CantidadLeft { get { return EntradaCantidad.Left; } } public int IvaLeft { get { return EntradaIva.Left; } } public int ImporteLeft { get { return EntradaImporte.Left; } } public override string Text { get { if (EntradaArticulo.Text == EntradaArticulo.FreeTextCode && EntradaArticulo.FreeTextCode.Length > 0) return EntradaArticulo.Text; else return EntradaArticulo.ValueInt.ToString(); } set { if (EntradaArticulo.Text != value) { EntradaArticulo.Text = value; } this.Changed = false; } } public string TextDetail { get { return EntradaArticulo.TextDetail; } set { EntradaArticulo.TextDetail = value; this.Changed = false; } } /// <summary> /// El importe final, con IVA, por cantidad y con descuento. /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public decimal ImporteFinal { get { return EntradaImporte.ValueDecimal; } set { EntradaImporte.ValueDecimal = value; this.Changed = false; } } /// <summary> /// El importe de IVA unitario (sin descuento). /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public decimal ImporteIvaUnitario { get { return this.m_ImporteUnitarioIva; } set { this.m_ImporteUnitarioIva = value; if(this.DiscriminarIva) { this.EntradaUnitarioIvaDescuentoCantidad_TextChanged(this, null); } this.Changed = false; } } /// <summary> /// El importe de IVA discriminado unitario (sin descuento), o 0 si el IVA no está discriminado. /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public decimal ImporteIvaDiscriminadoUnitario { get { return EntradaIva.ValueDecimal; } set { EntradaIva.ValueDecimal = value; this.Changed = false; } } /// <summary> /// El importe de IVA final, por cantidad y con descuento. /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public decimal ImporteIvaUnitarioFinal { get { return this.ImporteIvaUnitario * this.Cantidad * (1m - this.Descuento / 100m); } } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public decimal ImporteUnitario { get { return EntradaUnitario.ValueDecimal; } set { EntradaUnitario.ValueDecimal = value; this.Changed = false; } } /// <summary> /// El importe unitario final, por cantidad y con descuento. /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public decimal ImporteUnitarioFinal { get { return this.ImporteUnitario * this.Cantidad * (1m - this.Descuento / 100m); } } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public decimal Descuento { get { return EntradaDescuento.ValueDecimal; } set { EntradaDescuento.ValueDecimal = value; this.Changed = false; } } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Lbl.Articulos.Articulo Articulo { get { return EntradaArticulo.Elemento as Lbl.Articulos.Articulo; } set { EntradaArticulo.Elemento = value; this.Elemento = value; if(value == null) { this.m_Alicuota = null; } else { this.m_Alicuota = value.ObtenerAlicuota(); } EntradaArticulo_TextChanged(this, null); } } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Lbl.Impuestos.Alicuota Alicuota { get { return m_Alicuota; } } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public decimal Cantidad { get { if (this.EstoyUsandoUnidadPrimaria()) return EntradaCantidad.ValueDecimal; else return EntradaCantidad.ValueDecimal / Articulo.Rendimiento; } set { if (this.EstoyUsandoUnidadPrimaria()) EntradaCantidad.ValueDecimal = value; else EntradaCantidad.ValueDecimal = value * this.Articulo.Rendimiento; this.Changed = false; } } private bool EstoyUsandoUnidadPrimaria() { return (this.Articulo == null || Articulo.Unidad == null || EntradaCantidad.Sufijo == Articulo.Unidad || (EntradaCantidad.Sufijo.Length == 0 && Articulo.Unidad == "u") || Articulo.Rendimiento == 0); } private void EntradaArticulo_TextChanged(object sender, System.EventArgs e) { if (this.Connection == null) return; EntradaUnitario.TabStop = EntradaArticulo.IsFreeText; if (this.Elemento != EntradaArticulo.Elemento || EntradaArticulo.IsFreeText) { this.Elemento = EntradaArticulo.Elemento; if (this.Articulo != null) { this.m_Alicuota = this.Articulo.ObtenerAlicuota(); } this.CambiarArticulo(this.Articulo); } this.DatosSeguimiento = null; this.Changed = true; this.OnTextChanged(EventArgs.Empty); } private void EntradaUnitarioIvaDescuentoCantidad_TextChanged(object sender, System.EventArgs e) { if (this.Connection != null) { decimal ValorAnterior = EntradaImporte.ValueDecimal; this.RecalcularImporteFinal(); this.VerificarStock(); if (EntradaImporte.ValueDecimal != ValorAnterior) { this.Changed = true; if (null != ImportesChanged) { ImportesChanged(this, null); } } } } private void VerificarStock() { if (m_MostrarExistencias && Articulo != null) { if (this.TemporaryReadOnly == false && this.Articulo.TipoDeArticulo != Lbl.Articulos.TiposDeArticulo.Servicio && this.Articulo.Existencias < this.Cantidad) { if (this.Articulo.Existencias + this.Articulo.Pedido >= this.Cantidad) { //EntradaArticulo.Font = null; EntradaArticulo.ForeColor = Color.OrangeRed; } else { //EntradaArticulo.Font = new Font(this.Font, FontStyle.Strikeout); EntradaArticulo.ForeColor = Color.Red; } } else { //EntradaArticulo.Font = null; EntradaArticulo.ForeColor = this.DisplayStyle.TextColor; } } else { //EntradaArticulo.Font = null; EntradaArticulo.ForeColor = this.DisplayStyle.TextColor; } } public override bool TemporaryReadOnly { get { return base.TemporaryReadOnly; } set { base.TemporaryReadOnly = value; if (value) { EntradaArticulo.TemporaryReadOnly = true; EntradaUnitario.TemporaryReadOnly = true; EntradaDescuento.TemporaryReadOnly = true; EntradaCantidad.TemporaryReadOnly = true; } this.VerificarStock(); } } private void EntradaArticulo_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.Alt == false && e.Control == false && e.Shift == false) { switch (e.KeyCode) { case Keys.Right: case Keys.Return: e.Handled = true; if (EntradaUnitario.Visible && this.ReadOnly == false && this.TemporaryReadOnly == false) { if (this.BloquearPrecio) EntradaCantidad.Focus(); else EntradaUnitario.Focus(); } else { System.Windows.Forms.SendKeys.Send("{tab}"); } break; default: if (KeyDown != null) KeyDown(sender, e); this.AutoUpdate = true; break; } } if (e.Alt == false && e.Control == true && e.Shift == false) { switch (e.KeyCode) { case Keys.S: this.ObtenerDatosSeguimientoSiEsNecesario(); break; } } } protected void ObtenerDatosSeguimientoSiEsNecesario() { if (this.Articulo != null && this.Articulo.ObtenerSeguimiento() != Lbl.Articulos.Seguimientos.Ninguno && this.ObtenerDatosSeguimiento != null) this.ObtenerDatosSeguimiento(this, new EventArgs()); } protected override void OnLeave(EventArgs e) { Lbl.Articulos.Articulo Art = this.Elemento as Lbl.Articulos.Articulo; if (this.Cantidad != 0 && Art != null && Art.ObtenerSeguimiento() != Lbl.Articulos.Seguimientos.Ninguno && (this.DatosSeguimiento == null || this.DatosSeguimiento.Count != this.Cantidad)) { this.ObtenerDatosSeguimientoSiEsNecesario(); } base.OnLeave(e); } private void EntradaUnitario_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { switch (e.KeyCode) { case Keys.E: if (e.Control) { EntradaUnitario.SelectionLength = 0; EntradaUnitario.SelectionStart = EntradaUnitario.Text.Length; e.Handled = true; } break; case Keys.Left: if (EntradaUnitario.SelectionStart == 0) { e.Handled = true; EntradaArticulo.Focus(); } break; case Keys.Right: case Keys.Return: if (EntradaUnitario.SelectionStart >= EntradaUnitario.TextRaw.Length || EntradaUnitario.SelectionLength > 0) { e.Handled = true; EntradaCantidad.Focus(); } break; case Keys.Up: System.Windows.Forms.SendKeys.Send("+{tab}"); break; case Keys.Down: System.Windows.Forms.SendKeys.Send("{tab}"); break; default: if (null != KeyDown) KeyDown(sender, e); break; } } private void EntradaDescuento_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Left: if (EntradaDescuento.SelectionStart == 0) { e.Handled = true; EntradaCantidad.Focus(); } break; case Keys.Up: System.Windows.Forms.SendKeys.Send("+{tab}"); break; case Keys.Down: System.Windows.Forms.SendKeys.Send("{tab}"); break; default: if (null != KeyDown) KeyDown(sender, e); break; } } private void EntradaCantidad_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { switch (e.KeyCode) { case Keys.Left: e.Handled = true; if (this.BloquearPrecio) EntradaArticulo.Focus(); else EntradaUnitario.Focus(); break; case Keys.Right: case Keys.Return: if (EntradaCantidad.SelectionStart >= EntradaCantidad.TextRaw.Length || EntradaCantidad.SelectionLength > 0) { if (this.BloquearPrecio == false) { e.Handled = true; EntradaDescuento.Focus(); } } break; case Keys.Up: System.Windows.Forms.SendKeys.Send("+{tab}"); break; case Keys.Down: System.Windows.Forms.SendKeys.Send("{tab}"); break; case Keys.D0: case Keys.D1: case Keys.D2: case Keys.D3: case Keys.D4: case Keys.D5: case Keys.D6: case Keys.D7: case Keys.D8: case Keys.D9: case Keys.Space: e.Handled = true; this.ObtenerDatosSeguimientoSiEsNecesario(); break; default: if (KeyDown != null) KeyDown(sender, e); break; } } protected override void OnEnter(EventArgs e) { base.OnEnter(e); if (EntradaArticulo.Focused == false) EntradaArticulo.Focus(); } private void PonerFiltros() { string Filtros = ""; switch (m_ControlStock) { case ControlesSock.ConControlStock: Filtros += "control_stock=1"; break; case ControlesSock.SinControlStock: Filtros += "control_stock=0"; break; } EntradaArticulo.Filter = Filtros; } private void RecalcularAltura(object sender, System.EventArgs e) { LabelSerialsCruz.Visible = LabelSerials.Visible; if (LabelSerials.Visible) this.Height = this.LabelSerials.Bottom + this.EntradaArticulo.Top; else this.Height = this.EntradaArticulo.Bottom + this.EntradaArticulo.Top; } private void EntradaCantidad_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == ' ') { if (Articulo != null) { if (this.EstoyUsandoUnidadPrimaria()) { //Cambio a unidad secundaria EntradaCantidad.Sufijo = Articulo.UnidadRendimiento; EntradaCantidad.Text = Lfx.Types.Formatting.FormatStock(Lfx.Types.Parsing.ParseStock(EntradaCantidad.Text) * this.Articulo.Rendimiento); } else { //Cambio a unidad primaria EntradaCantidad.Sufijo = Articulo.Unidad == "u" ? "" : Articulo.Unidad; EntradaCantidad.Text = Lfx.Types.Formatting.FormatStock(Lfx.Types.Parsing.ParseStock(EntradaCantidad.Text) / this.Articulo.Rendimiento, 4); } e.Handled = true; } } } private void EntradaCantidad_Click(object sender, EventArgs e) { this.ObtenerDatosSeguimientoSiEsNecesario(); } protected void CambiarArticulo(Lbl.Articulos.Articulo articulo) { if (this.Articulo != null) { EntradaUnitario.Enabled = true; EntradaUnitario.Enabled = true; EntradaDescuento.Enabled = true; EntradaCantidad.Enabled = true; EntradaImporte.Enabled = true; EntradaCantidad.TemporaryReadOnly = this.Articulo.ObtenerSeguimiento() != Lbl.Articulos.Seguimientos.Ninguno || this.TemporaryReadOnly; EntradaUnitario.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio; EntradaDescuento.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio; if (this.AutoUpdate) { if (this.Articulo == null) { return; } if (this.Articulo.Unidad != "u") { EntradaCantidad.Sufijo = Articulo.Unidad; } else { EntradaCantidad.Sufijo = ""; } decimal UnitarioMostrar; if (m_Precio == Precios.Costo) { UnitarioMostrar = Articulo.Costo; } else { UnitarioMostrar = Articulo.Pvp; } if (this.Cantidad == 0) { this.Cantidad = 1; } this.EstablecerImporteUnitarioOriginal(UnitarioMostrar); this.RecalcularImporteFinal(); } } else if (EntradaArticulo.IsFreeText) { EntradaUnitario.Enabled = true; EntradaDescuento.Enabled = true; EntradaCantidad.Enabled = true; EntradaCantidad.TemporaryReadOnly = this.TemporaryReadOnly; EntradaUnitario.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio; EntradaDescuento.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio; EntradaImporte.Enabled = true; if (this.AutoUpdate) { if (this.Cantidad == 0) { this.Cantidad = 1; } } } else if (EntradaArticulo.Text.Length == 0 || (EntradaArticulo.Text.IsNumericInt() && EntradaArticulo.ValueInt == 0)) { EntradaUnitario.Enabled = false; EntradaDescuento.Enabled = false; EntradaCantidad.Enabled = false; EntradaCantidad.TemporaryReadOnly = this.TemporaryReadOnly; EntradaUnitario.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio; EntradaDescuento.TemporaryReadOnly = this.TemporaryReadOnly || this.BloquearPrecio; EntradaImporte.Enabled = false; if (this.AutoUpdate) { EntradaCantidad.ValueDecimal = 0m; EntradaImporte.ValueDecimal = 0m; this.EstablecerImporteUnitarioOriginal(0m); EntradaDescuento.ValueDecimal = 0m; } } } /// <summary> /// Cambia el importe unitario original (sin IVA), y además recalcula el IVA y lo muestra discriminado si corresponde. /// </summary> /// <param name="unitario">El precio unitario a mostrar y usar como base para el cálculo de IVA e importe final.</param> protected void EstablecerImporteUnitarioOriginal(decimal unitario) { if (this.AplicarIva && m_Alicuota != null) { this.ImporteIvaUnitario = unitario * (m_Alicuota.Porcentaje / 100m); if (this.DiscriminarIva) { EntradaUnitario.ValueDecimal = unitario; EntradaIva.ValueDecimal = this.ImporteIvaUnitario; } else { EntradaUnitario.ValueDecimal = unitario + this.ImporteIvaUnitario; EntradaIva.ValueDecimal = 0m; } } else { this.ImporteIvaUnitario = 0m; EntradaUnitario.ValueDecimal = unitario; EntradaIva.ValueDecimal = 0; } } /// <summary> /// Recalcula el importe final, según importe, IVA, cantidad y descuento. /// </summary> protected void RecalcularImporteFinal() { if(m_DiscriminarIva) { if(m_AplicarIva && this.m_Alicuota != null) { decimal Iva = this.ImporteUnitario * (this.m_Alicuota.Porcentaje / 100m); if(Math.Abs(this.ImporteIvaUnitario - Iva) > 0.01m) { this.ImporteIvaUnitario = Iva; } } else { if(this.ImporteIvaUnitario != 0m) { this.ImporteIvaUnitario = 0m; } } EntradaIva.ValueDecimal = this.ImporteIvaUnitario; } else { EntradaIva.ValueDecimal = 0m; } try { decimal ImporteFinal = (this.ImporteUnitario + this.ImporteIvaDiscriminadoUnitario) * this.Cantidad * (1m - this.Descuento / 100m); EntradaImporte.ValueDecimal = ImporteFinal; } catch { EntradaImporte.ValueDecimal = 0m; } if (m_MostrarExistencias) { VerificarStock(); } } } }
lazarogestion/lazaro
Lcc/Entrada/Articulos/DetalleComprobante.cs
C#
gpl-2.0
47,695
#myGallery, #myGallerySet, #flickrGallery { width: 520px; height: 300px; z-index:5; margin-bottom: 20px; } .jdGallery a { outline:0; } #flickrGallery { width: 500px; height: 334px; } #myGallery img.thumbnail, #myGallerySet img.thumbnail { display: none; } .jdGallery { overflow: hidden; position: relative; } .jdGallery img { border: 0; margin: 0; } .jdGallery .slideElement { width: 100%; height: 100%; background-color: #000; background-repeat: no-repeat; background-position: center center; background-image: url('img/loading-bar-black.gif'); } .jdGallery .loadingElement { width: 100%; height: 100%; position: absolute; left: 0; top: 0; background-color: #000; background-repeat: no-repeat; background-position: center center; background-image: url('img/loading-bar-black.gif'); } .jdGallery .slideInfoZone { position: absolute; z-index: 10; width: 100%; margin: 0px; left: 0; bottom: 0; height: 120px; background: #181818; color: #fff; text-indent: 0; overflow: hidden; } * html .jdGallery .slideInfoZone { bottom: -1px; } .jdGallery .slideInfoZone h2 { padding: 0; font-size: 14px; margin: 0; margin: 2px 5px; font-weight: bold; color: #fff !important; } .jdGallery .slideInfoZone p { padding: 0; font-size: 12px; margin: 2px 5px; color: #eee; } .jdGallery div.carouselContainer { position: absolute; height: 135px; width: 100%; z-index: 10; margin: 0px; left: 0; top: 0; } .jdGallery a.carouselBtn { position: absolute; bottom: 0; right: 30px; height: 20px; /*width: 100px; background: url('img/carousel_btn.gif') no-repeat;*/ text-align: center; padding: 0 10px; font-size: 13px; background: #333; color: #fff; cursor: pointer; } .jdGallery .carousel { position: absolute; width: 100%; margin: 0px; left: 0; top: 0; height: 115px; background: #333; color: #fff; text-indent: 0; overflow: hidden; } .jdExtCarousel { overflow: hidden; position: relative; } .jdGallery .carousel .carouselWrapper, .jdExtCarousel .carouselWrapper { position: absolute; width: 100%; height: 78px; top: 10px; left: 0; overflow: hidden; } .jdGallery .carousel .carouselInner, .jdExtCarousel .carouselInner { position: relative; } .jdGallery .carousel .carouselInner .thumbnail, .jdExtCarousel .carouselInner .thumbnail { cursor: pointer; background: #000; background-position: center center; float: left; border: solid 1px #fff; } .jdGallery .wall .thumbnail, .jdExtCarousel .wall .thumbnail { margin-bottom: 10px; } .jdGallery .carousel .label, .jdExtCarousel .label { font-size: 13px; position: absolute; bottom: 5px; left: 10px; padding: 0; margin: 0; } .jdGallery .carousel .wallButton, .jdExtCarousel .wallButton { font-size: 10px; position: absolute; bottom: 5px; right: 10px; padding: 1px 2px; margin: 0; background: #222; border: 1px solid #888; cursor: pointer; } .jdGallery .carousel .label .number, .jdExtCarousel .label .number { color: #b5b5b5; } .jdGallery a { font-size: 100%; text-decoration: none; color: #fff; } .jdGallery a.right, .jdGallery a.left { position: absolute; height: 99%; width: 25%; cursor: pointer; z-index:10; filter:alpha(opacity=20); -moz-opacity:0.2; -khtml-opacity: 0.2; opacity: 0.2; } * html .jdGallery a.right, * html .jdGallery a.left { filter:alpha(opacity=50); } .jdGallery a.right:hover, .jdGallery a.left:hover { filter:alpha(opacity=80); -moz-opacity:0.8; -khtml-opacity: 0.8; opacity: 0.8; } .jdGallery a.left { left: 0; top: 0; background: url('img/fleche1.png') no-repeat center left; } * html .jdGallery a.left { background: url('img/fleche1.gif') no-repeat center left; } .jdGallery a.right { right: 0; top: 0; background: url('img/fleche2.png') no-repeat center right; } * html .jdGallery a.right { background: url('img/fleche2.gif') no-repeat center right; } .jdGallery a.open { left: 0; top: 0; width: 100%; height: 100%; } .withArrows a.open { position: absolute; top: 0; left: 25%; height: 99%; width: 50%; cursor: pointer; z-index: 10; background: none; -moz-opacity:0.8; -khtml-opacity: 0.8; opacity: 0.8; } .withArrows a.open:hover { background: url('img/open.png') no-repeat center center; } * html .withArrows a.open:hover { background: url('img/open.gif') no-repeat center center; filter:alpha(opacity=80); } /* Gallery Sets */ .jdGallery a.gallerySelectorBtn { z-index: 15; position: absolute; top: 0; left: 30px; height: 20px; /*width: 100px; background: url('img/carousel_btn.gif') no-repeat;*/ text-align: center; padding: 0 10px; font-size: 13px; background: #333; color: #fff; cursor: pointer; opacity: .4; -moz-opacity: .4; -khtml-opacity: 0.4; filter:alpha(opacity=40); } .jdGallery .gallerySelector { z-index: 20; width: 100%; height: 100%; position: absolute; top: 0; left: 0; background: #000; } .jdGallery .gallerySelector h2 { margin: 0; padding: 10px 20px 10px 20px; font-size: 20px; line-height: 30px; color: #fff !important; } .jdGallery .gallerySelector .gallerySelectorWrapper { overflow: hidden; } .jdGallery .gallerySelector .gallerySelectorInner div.galleryButton { margin-left: 10px; margin-top: 10px; border: 1px solid #888; padding: 5px; height: 40px; color: #fff; cursor: pointer; float: left; } .jdGallery .gallerySelector .gallerySelectorInner div.hover { background: #333; } .jdGallery .gallerySelector .gallerySelectorInner div.galleryButton div.preview { background: #000; background-position: center center; float: left; border: none; width: 40px; height: 40px; margin-right: 5px; } .jdGallery .gallerySelector .gallerySelectorInner div.galleryButton h3 { margin: 0; padding: 0; font-size: 12px; font-weight: normal; color: #fff; } .jdGallery .gallerySelector .gallerySelectorInner div.galleryButton p.info { margin: 0; padding: 0; font-size: 12px; font-weight: normal; color: #fff !important; }
Quartermain/viettrungtravel_wordpress
wp-content/themes/Innox/jdgallery/jd.gallery.css
CSS
gpl-2.0
6,296
#include <stdio.h> #include <l4/sys/kdebug.h> void fork_to_background(void); void fork_to_background(void) { printf("unimplemented: %s\n", __func__); enter_kdebug(); }
MicroTrustRepos/microkernel
src/l4/pkg/ankh/examples/wget/l4re_helpers.c
C
gpl-2.0
171
{{tpl:extends parent="__layout.html"}} <tpl:Block name="head-title"> <title>{{tpl:lang Categories Page}} - {{tpl:BlogName encode_html="1"}}</title> </tpl:Block> <tpl:Block name="meta-robots"> <meta name="ROBOTS" content="{{tpl:BlogMetaRobots}}" /> </tpl:Block> <tpl:Block name="dc-entry"> <meta name="dc.title" lang="{{tpl:BlogLanguage}}" content="{{tpl:EntryTitle encode_html="1"}} - {{tpl:BlogName encode_html="1"}}" /> <meta property="dc.language" content="{{tpl:BlogLanguage}}" /> </tpl:Block> <tpl:Block name="head-linkrel"> <link rel="top" href="{{tpl:BlogURL}}" title="{{tpl:lang Home}}" /> <link rel="contents" href="{{tpl:BlogArchiveURL}}" title="{{tpl:lang Archives}}" /> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="{{tpl:BlogFeedURL type="atom"}}" /> </tpl:Block> <tpl:Block name="body-tag"><body class="dc-page"></tpl:Block> <tpl:Block name="main-breadcrumb"> {{tpl:Breadcrumb}} </tpl:Block> <tpl:Block name="main-content"> <div id="p{{tpl:EntryID}}" class="post" role="article"> <h2 class="post-title">{{tpl:EntryTitle encode_html="1"}}</h2> <!-- # --BEHAVIOR-- publicEntryBeforeContent --> {{tpl:SysBehavior behavior="publicEntryBeforeContent"}} <tpl:EntryIf extended="1"> <div class="post-excerpt">{{tpl:EntryExcerpt}}</div> </tpl:EntryIf> <div class="post-content">{{tpl:EntryContent}}</div> <p class="page-info">{{tpl:lang Published on}} {{tpl:EntryDate}} {{tpl:lang by}} {{tpl:EntryAuthorLink}}</p> <!-- # --BEHAVIOR-- publicEntryAfterContent --> {{tpl:SysBehavior behavior="publicEntryAfterContent"}} </div> </tpl:Block>
nikrou/related
default-templates/dotty/external.html
HTML
gpl-2.0
1,649
/* * mm/page-writeback.c * * Copyright (C) 2002, Linus Torvalds. * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com> * * Contains functions related to writing back dirty pages at the * address_space level. * * 10Apr2002 Andrew Morton * Initial version */ #include <linux/kernel.h> #include <linux/export.h> #include <linux/spinlock.h> #include <linux/fs.h> #include <linux/mm.h> #include <linux/swap.h> #include <linux/slab.h> #include <linux/pagemap.h> #include <linux/writeback.h> #include <linux/init.h> #include <linux/backing-dev.h> #include <linux/task_io_accounting_ops.h> #include <linux/blkdev.h> #include <linux/mpage.h> #include <linux/rmap.h> #include <linux/percpu.h> #include <linux/notifier.h> #include <linux/smp.h> #include <linux/sysctl.h> #include <linux/cpu.h> #include <linux/syscalls.h> #include <linux/buffer_head.h> /* __set_page_dirty_buffers */ #include <linux/pagevec.h> #include <linux/timer.h> #include <linux/sched/rt.h> #include <linux/mm_inline.h> #include <trace/events/writeback.h> #include "internal.h" /* * Sleep at most 200ms at a time in balance_dirty_pages(). */ #define MAX_PAUSE max(HZ/5, 1) /* * Try to keep balance_dirty_pages() call intervals higher than this many pages * by raising pause time to max_pause when falls below it. */ #define DIRTY_POLL_THRESH (128 >> (PAGE_SHIFT - 10)) /* * Estimate write bandwidth at 200ms intervals. */ #define BANDWIDTH_INTERVAL max(HZ/5, 1) #define RATELIMIT_CALC_SHIFT 10 /* * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited * will look to see if it needs to force writeback or throttling. */ static long ratelimit_pages = 32; /* The following parameters are exported via /proc/sys/vm */ /* * Start background writeback (via writeback threads) at this percentage */ int dirty_background_ratio = 10; /* * dirty_background_bytes starts at 0 (disabled) so that it is a function of * dirty_background_ratio * the amount of dirtyable memory */ unsigned long dirty_background_bytes; /* * free highmem will not be subtracted from the total free memory * for calculating free ratios if vm_highmem_is_dirtyable is true */ int vm_highmem_is_dirtyable; /* * The generator of dirty data starts writeback at this percentage */ int vm_dirty_ratio = 20; /* * vm_dirty_bytes starts at 0 (disabled) so that it is a function of * vm_dirty_ratio * the amount of dirtyable memory */ unsigned long vm_dirty_bytes; /* * The interval between `kupdate'-style writebacks */ unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */ EXPORT_SYMBOL_GPL(dirty_writeback_interval); /* * The longest time for which data is allowed to remain dirty */ unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */ /* * Flag that makes the machine dump writes/reads and block dirtyings. */ int block_dump; /* * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies: * a full sync is triggered after this time elapses without any disk activity. */ int laptop_mode; EXPORT_SYMBOL(laptop_mode); /* End of sysctl-exported parameters */ unsigned long global_dirty_limit; /* * Scale the writeback cache size proportional to the relative writeout speeds. * * We do this by keeping a floating proportion between BDIs, based on page * writeback completions [end_page_writeback()]. Those devices that write out * pages fastest will get the larger share, while the slower will get a smaller * share. * * We use page writeout completions because we are interested in getting rid of * dirty pages. Having them written out is the primary goal. * * We introduce a concept of time, a period over which we measure these events, * because demand can/will vary over time. The length of this period itself is * measured in page writeback completions. * */ static struct fprop_global writeout_completions; static void writeout_period(unsigned long t); /* Timer for aging of writeout_completions */ static struct timer_list writeout_period_timer = TIMER_DEFERRED_INITIALIZER(writeout_period, 0, 0); static unsigned long writeout_period_time = 0; /* * Length of period for aging writeout fractions of bdis. This is an * arbitrarily chosen number. The longer the period, the slower fractions will * reflect changes in current writeout rate. */ #define VM_COMPLETIONS_PERIOD_LEN (3*HZ) /* * Work out the current dirty-memory clamping and background writeout * thresholds. * * The main aim here is to lower them aggressively if there is a lot of mapped * memory around. To avoid stressing page reclaim with lots of unreclaimable * pages. It is better to clamp down on writers than to start swapping, and * performing lots of scanning. * * We only allow 1/2 of the currently-unmapped memory to be dirtied. * * We don't permit the clamping level to fall below 5% - that is getting rather * excessive. * * We make sure that the background writeout level is below the adjusted * clamping level. */ /* * In a memory zone, there is a certain amount of pages we consider * available for the page cache, which is essentially the number of * free and reclaimable pages, minus some zone reserves to protect * lowmem and the ability to uphold the zone's watermarks without * requiring writeback. * * This number of dirtyable pages is the base value of which the * user-configurable dirty ratio is the effictive number of pages that * are allowed to be actually dirtied. Per individual zone, or * globally by using the sum of dirtyable pages over all zones. * * Because the user is allowed to specify the dirty limit globally as * absolute number of bytes, calculating the per-zone dirty limit can * require translating the configured limit into a percentage of * global dirtyable memory first. */ /** * zone_dirtyable_memory - number of dirtyable pages in a zone * @zone: the zone * * Returns the zone's number of pages potentially available for dirty * page cache. This is the base value for the per-zone dirty limits. */ static unsigned long zone_dirtyable_memory(struct zone *zone) { unsigned long nr_pages; nr_pages = zone_page_state(zone, NR_FREE_PAGES); nr_pages -= min(nr_pages, zone->dirty_balance_reserve); nr_pages += zone_page_state(zone, NR_INACTIVE_FILE); nr_pages += zone_page_state(zone, NR_ACTIVE_FILE); return nr_pages; } static unsigned long highmem_dirtyable_memory(unsigned long total) { #ifdef CONFIG_HIGHMEM int node; unsigned long x = 0; for_each_node_state(node, N_HIGH_MEMORY) { struct zone *z = &NODE_DATA(node)->node_zones[ZONE_HIGHMEM]; x += zone_dirtyable_memory(z); } /* * Unreclaimable memory (kernel memory or anonymous memory * without swap) can bring down the dirtyable pages below * the zone's dirty balance reserve and the above calculation * will underflow. However we still want to add in nodes * which are below threshold (negative values) to get a more * accurate calculation but make sure that the total never * underflows. */ if ((long)x < 0) x = 0; /* * Make sure that the number of highmem pages is never larger * than the number of the total dirtyable memory. This can only * occur in very strange VM situations but we want to make sure * that this does not occur. */ return min(x, total); #else return 0; #endif } /** * global_dirtyable_memory - number of globally dirtyable pages * * Returns the global number of pages potentially available for dirty * page cache. This is the base value for the global dirty limits. */ static unsigned long global_dirtyable_memory(void) { unsigned long x; x = global_page_state(NR_FREE_PAGES); x -= min(x, dirty_balance_reserve); x += global_page_state(NR_INACTIVE_FILE); x += global_page_state(NR_ACTIVE_FILE); if (!vm_highmem_is_dirtyable) x -= highmem_dirtyable_memory(x); /* Subtract min_free_kbytes */ x -= min_t(unsigned long, x, min_free_kbytes >> (PAGE_SHIFT - 10)); return x + 1; /* Ensure that we never return 0 */ } /* * global_dirty_limits - background-writeback and dirty-throttling thresholds * * Calculate the dirty thresholds based on sysctl parameters * - vm.dirty_background_ratio or vm.dirty_background_bytes * - vm.dirty_ratio or vm.dirty_bytes * The dirty limits will be lifted by 1/4 for PF_LESS_THROTTLE (ie. nfsd) and * real-time tasks. */ void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty) { unsigned long background; unsigned long dirty; unsigned long uninitialized_var(available_memory); struct task_struct *tsk; if (!vm_dirty_bytes || !dirty_background_bytes) available_memory = global_dirtyable_memory(); if (vm_dirty_bytes) dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE); else dirty = (vm_dirty_ratio * available_memory) / 100; if (dirty_background_bytes) background = DIV_ROUND_UP(dirty_background_bytes, PAGE_SIZE); else background = (dirty_background_ratio * available_memory) / 100; if (background >= dirty) background = dirty / 2; tsk = current; if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) { background += background / 4; dirty += dirty / 4; } *pbackground = background; *pdirty = dirty; trace_global_dirty_state(background, dirty); } /** * zone_dirty_limit - maximum number of dirty pages allowed in a zone * @zone: the zone * * Returns the maximum number of dirty pages allowed in a zone, based * on the zone's dirtyable memory. */ static unsigned long zone_dirty_limit(struct zone *zone) { unsigned long zone_memory = zone_dirtyable_memory(zone); struct task_struct *tsk = current; unsigned long dirty; if (vm_dirty_bytes) dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) * zone_memory / global_dirtyable_memory(); else dirty = vm_dirty_ratio * zone_memory / 100; if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) dirty += dirty / 4; return dirty; } /** * zone_dirty_ok - tells whether a zone is within its dirty limits * @zone: the zone to check * * Returns %true when the dirty pages in @zone are within the zone's * dirty limit, %false if the limit is exceeded. */ bool zone_dirty_ok(struct zone *zone) { unsigned long limit = zone_dirty_limit(zone); return zone_page_state(zone, NR_FILE_DIRTY) + zone_page_state(zone, NR_UNSTABLE_NFS) + zone_page_state(zone, NR_WRITEBACK) <= limit; } int dirty_background_ratio_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret; ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); if (ret == 0 && write) dirty_background_bytes = 0; return ret; } int dirty_background_bytes_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret; ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos); if (ret == 0 && write) dirty_background_ratio = 0; return ret; } int dirty_ratio_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int old_ratio = vm_dirty_ratio; int ret; ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); if (ret == 0 && write && vm_dirty_ratio != old_ratio) { writeback_set_ratelimit(); vm_dirty_bytes = 0; } return ret; } int dirty_bytes_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { unsigned long old_bytes = vm_dirty_bytes; int ret; ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos); if (ret == 0 && write && vm_dirty_bytes != old_bytes) { writeback_set_ratelimit(); vm_dirty_ratio = 0; } return ret; } static unsigned long wp_next_time(unsigned long cur_time) { cur_time += VM_COMPLETIONS_PERIOD_LEN; /* 0 has a special meaning... */ if (!cur_time) return 1; return cur_time; } /* * Increment the BDI's writeout completion count and the global writeout * completion count. Called from test_clear_page_writeback(). */ static inline void __bdi_writeout_inc(struct backing_dev_info *bdi) { __inc_bdi_stat(bdi, BDI_WRITTEN); __fprop_inc_percpu_max(&writeout_completions, &bdi->completions, bdi->max_prop_frac); /* First event after period switching was turned off? */ if (!unlikely(writeout_period_time)) { /* * We can race with other __bdi_writeout_inc calls here but * it does not cause any harm since the resulting time when * timer will fire and what is in writeout_period_time will be * roughly the same. */ writeout_period_time = wp_next_time(jiffies); mod_timer(&writeout_period_timer, writeout_period_time); } } void bdi_writeout_inc(struct backing_dev_info *bdi) { unsigned long flags; local_irq_save(flags); __bdi_writeout_inc(bdi); local_irq_restore(flags); } EXPORT_SYMBOL_GPL(bdi_writeout_inc); /* * Obtain an accurate fraction of the BDI's portion. */ static void bdi_writeout_fraction(struct backing_dev_info *bdi, long *numerator, long *denominator) { fprop_fraction_percpu(&writeout_completions, &bdi->completions, numerator, denominator); } /* * On idle system, we can be called long after we scheduled because we use * deferred timers so count with missed periods. */ static void writeout_period(unsigned long t) { int miss_periods = (jiffies - writeout_period_time) / VM_COMPLETIONS_PERIOD_LEN; if (fprop_new_period(&writeout_completions, miss_periods + 1)) { writeout_period_time = wp_next_time(writeout_period_time + miss_periods * VM_COMPLETIONS_PERIOD_LEN); mod_timer(&writeout_period_timer, writeout_period_time); } else { /* * Aging has zeroed all fractions. Stop wasting CPU on period * updates. */ writeout_period_time = 0; } } /* * bdi_min_ratio keeps the sum of the minimum dirty shares of all * registered backing devices, which, for obvious reasons, can not * exceed 100%. */ static unsigned int bdi_min_ratio = 5; int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio) { int ret = 0; spin_lock_bh(&bdi_lock); if (min_ratio > bdi->max_ratio) { ret = -EINVAL; } else { min_ratio -= bdi->min_ratio; if (bdi_min_ratio + min_ratio < 100) { bdi_min_ratio += min_ratio; bdi->min_ratio += min_ratio; } else { ret = -EINVAL; } } spin_unlock_bh(&bdi_lock); return ret; } int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio) { int ret = 0; if (max_ratio > 100) return -EINVAL; spin_lock_bh(&bdi_lock); if (bdi->min_ratio > max_ratio) { ret = -EINVAL; } else { bdi->max_ratio = max_ratio; bdi->max_prop_frac = (FPROP_FRAC_BASE * max_ratio) / 100; } spin_unlock_bh(&bdi_lock); return ret; } EXPORT_SYMBOL(bdi_set_max_ratio); static unsigned long dirty_freerun_ceiling(unsigned long thresh, unsigned long bg_thresh) { return (thresh + bg_thresh) / 2; } static unsigned long hard_dirty_limit(unsigned long thresh) { return max(thresh, global_dirty_limit); } /** * bdi_dirty_limit - @bdi's share of dirty throttling threshold * @bdi: the backing_dev_info to query * @dirty: global dirty limit in pages * * Returns @bdi's dirty limit in pages. The term "dirty" in the context of * dirty balancing includes all PG_dirty, PG_writeback and NFS unstable pages. * * Note that balance_dirty_pages() will only seriously take it as a hard limit * when sleeping max_pause per page is not enough to keep the dirty pages under * control. For example, when the device is completely stalled due to some error * conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key. * In the other normal situations, it acts more gently by throttling the tasks * more (rather than completely block them) when the bdi dirty pages go high. * * It allocates high/low dirty limits to fast/slow devices, in order to prevent * - starving fast devices * - piling up dirty pages (that will take long time to sync) on slow devices * * The bdi's share of dirty limit will be adapting to its throughput and * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set. */ unsigned long bdi_dirty_limit(struct backing_dev_info *bdi, unsigned long dirty) { u64 bdi_dirty; long numerator, denominator; /* * Calculate this BDI's share of the dirty ratio. */ bdi_writeout_fraction(bdi, &numerator, &denominator); bdi_dirty = (dirty * (100 - bdi_min_ratio)) / 100; bdi_dirty *= numerator; do_div(bdi_dirty, denominator); bdi_dirty += (dirty * bdi->min_ratio) / 100; if (bdi_dirty > (dirty * bdi->max_ratio) / 100) bdi_dirty = dirty * bdi->max_ratio / 100; return bdi_dirty; } /* * setpoint - dirty 3 * f(dirty) := 1.0 + (----------------) * limit - setpoint * * it's a 3rd order polynomial that subjects to * * (1) f(freerun) = 2.0 => rampup dirty_ratelimit reasonably fast * (2) f(setpoint) = 1.0 => the balance point * (3) f(limit) = 0 => the hard limit * (4) df/dx <= 0 => negative feedback control * (5) the closer to setpoint, the smaller |df/dx| (and the reverse) * => fast response on large errors; small oscillation near setpoint */ static inline long long pos_ratio_polynom(unsigned long setpoint, unsigned long dirty, unsigned long limit) { long long pos_ratio; long x; x = div_s64(((s64)setpoint - (s64)dirty) << RATELIMIT_CALC_SHIFT, limit - setpoint + 1); pos_ratio = x; pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT; pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT; pos_ratio += 1 << RATELIMIT_CALC_SHIFT; return clamp(pos_ratio, 0LL, 2LL << RATELIMIT_CALC_SHIFT); } /* * Dirty position control. * * (o) global/bdi setpoints * * We want the dirty pages be balanced around the global/bdi setpoints. * When the number of dirty pages is higher/lower than the setpoint, the * dirty position control ratio (and hence task dirty ratelimit) will be * decreased/increased to bring the dirty pages back to the setpoint. * * pos_ratio = 1 << RATELIMIT_CALC_SHIFT * * if (dirty < setpoint) scale up pos_ratio * if (dirty > setpoint) scale down pos_ratio * * if (bdi_dirty < bdi_setpoint) scale up pos_ratio * if (bdi_dirty > bdi_setpoint) scale down pos_ratio * * task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT * * (o) global control line * * ^ pos_ratio * | * | |<===== global dirty control scope ======>| * 2.0 .............* * | .* * | . * * | . * * | . * * | . * * | . * * 1.0 ................................* * | . . * * | . . * * | . . * * | . . * * | . . * * 0 +------------.------------------.----------------------*-------------> * freerun^ setpoint^ limit^ dirty pages * * (o) bdi control line * * ^ pos_ratio * | * | * * | * * | * * | * * | * |<=========== span ============>| * 1.0 .......................* * | . * * | . * * | . * * | . * * | . * * | . * * | . * * | . * * | . * * | . * * | . * * 1/4 ...............................................* * * * * * * * * * * * * | . . * | . . * | . . * 0 +----------------------.-------------------------------.-------------> * bdi_setpoint^ x_intercept^ * * The bdi control line won't drop below pos_ratio=1/4, so that bdi_dirty can * be smoothly throttled down to normal if it starts high in situations like * - start writing to a slow SD card and a fast disk at the same time. The SD * card's bdi_dirty may rush to many times higher than bdi_setpoint. * - the bdi dirty thresh drops quickly due to change of JBOD workload */ static unsigned long bdi_position_ratio(struct backing_dev_info *bdi, unsigned long thresh, unsigned long bg_thresh, unsigned long dirty, unsigned long bdi_thresh, unsigned long bdi_dirty) { unsigned long write_bw = bdi->avg_write_bandwidth; unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh); unsigned long limit = hard_dirty_limit(thresh); unsigned long x_intercept; unsigned long setpoint; /* dirty pages' target balance point */ unsigned long bdi_setpoint; unsigned long span; long long pos_ratio; /* for scaling up/down the rate limit */ long x; if (unlikely(dirty >= limit)) return 0; /* * global setpoint * * See comment for pos_ratio_polynom(). */ setpoint = (freerun + limit) / 2; pos_ratio = pos_ratio_polynom(setpoint, dirty, limit); /* * The strictlimit feature is a tool preventing mistrusted filesystems * from growing a large number of dirty pages before throttling. For * such filesystems balance_dirty_pages always checks bdi counters * against bdi limits. Even if global "nr_dirty" is under "freerun". * This is especially important for fuse which sets bdi->max_ratio to * 1% by default. Without strictlimit feature, fuse writeback may * consume arbitrary amount of RAM because it is accounted in * NR_WRITEBACK_TEMP which is not involved in calculating "nr_dirty". * * Here, in bdi_position_ratio(), we calculate pos_ratio based on * two values: bdi_dirty and bdi_thresh. Let's consider an example: * total amount of RAM is 16GB, bdi->max_ratio is equal to 1%, global * limits are set by default to 10% and 20% (background and throttle). * Then bdi_thresh is 1% of 20% of 16GB. This amounts to ~8K pages. * bdi_dirty_limit(bdi, bg_thresh) is about ~4K pages. bdi_setpoint is * about ~6K pages (as the average of background and throttle bdi * limits). The 3rd order polynomial will provide positive feedback if * bdi_dirty is under bdi_setpoint and vice versa. * * Note, that we cannot use global counters in these calculations * because we want to throttle process writing to a strictlimit BDI * much earlier than global "freerun" is reached (~23MB vs. ~2.3GB * in the example above). */ if (unlikely(bdi->capabilities & BDI_CAP_STRICTLIMIT)) { long long bdi_pos_ratio; unsigned long bdi_bg_thresh; if (bdi_dirty < 8) return min_t(long long, pos_ratio * 2, 2 << RATELIMIT_CALC_SHIFT); if (bdi_dirty >= bdi_thresh) return 0; bdi_bg_thresh = div_u64((u64)bdi_thresh * bg_thresh, thresh); bdi_setpoint = dirty_freerun_ceiling(bdi_thresh, bdi_bg_thresh); if (bdi_setpoint == 0 || bdi_setpoint == bdi_thresh) return 0; bdi_pos_ratio = pos_ratio_polynom(bdi_setpoint, bdi_dirty, bdi_thresh); /* * Typically, for strictlimit case, bdi_setpoint << setpoint * and pos_ratio >> bdi_pos_ratio. In the other words global * state ("dirty") is not limiting factor and we have to * make decision based on bdi counters. But there is an * important case when global pos_ratio should get precedence: * global limits are exceeded (e.g. due to activities on other * BDIs) while given strictlimit BDI is below limit. * * "pos_ratio * bdi_pos_ratio" would work for the case above, * but it would look too non-natural for the case of all * activity in the system coming from a single strictlimit BDI * with bdi->max_ratio == 100%. * * Note that min() below somewhat changes the dynamics of the * control system. Normally, pos_ratio value can be well over 3 * (when globally we are at freerun and bdi is well below bdi * setpoint). Now the maximum pos_ratio in the same situation * is 2. We might want to tweak this if we observe the control * system is too slow to adapt. */ return min(pos_ratio, bdi_pos_ratio); } /* * We have computed basic pos_ratio above based on global situation. If * the bdi is over/under its share of dirty pages, we want to scale * pos_ratio further down/up. That is done by the following mechanism. */ /* * bdi setpoint * * f(bdi_dirty) := 1.0 + k * (bdi_dirty - bdi_setpoint) * * x_intercept - bdi_dirty * := -------------------------- * x_intercept - bdi_setpoint * * The main bdi control line is a linear function that subjects to * * (1) f(bdi_setpoint) = 1.0 * (2) k = - 1 / (8 * write_bw) (in single bdi case) * or equally: x_intercept = bdi_setpoint + 8 * write_bw * * For single bdi case, the dirty pages are observed to fluctuate * regularly within range * [bdi_setpoint - write_bw/2, bdi_setpoint + write_bw/2] * for various filesystems, where (2) can yield in a reasonable 12.5% * fluctuation range for pos_ratio. * * For JBOD case, bdi_thresh (not bdi_dirty!) could fluctuate up to its * own size, so move the slope over accordingly and choose a slope that * yields 100% pos_ratio fluctuation on suddenly doubled bdi_thresh. */ if (unlikely(bdi_thresh > thresh)) bdi_thresh = thresh; /* * It's very possible that bdi_thresh is close to 0 not because the * device is slow, but that it has remained inactive for long time. * Honour such devices a reasonable good (hopefully IO efficient) * threshold, so that the occasional writes won't be blocked and active * writes can rampup the threshold quickly. */ bdi_thresh = max(bdi_thresh, (limit - dirty) / 8); /* * scale global setpoint to bdi's: * bdi_setpoint = setpoint * bdi_thresh / thresh */ x = div_u64((u64)bdi_thresh << 16, thresh + 1); bdi_setpoint = setpoint * (u64)x >> 16; /* * Use span=(8*write_bw) in single bdi case as indicated by * (thresh - bdi_thresh ~= 0) and transit to bdi_thresh in JBOD case. * * bdi_thresh thresh - bdi_thresh * span = ---------- * (8 * write_bw) + ------------------- * bdi_thresh * thresh thresh */ span = (thresh - bdi_thresh + 8 * write_bw) * (u64)x >> 16; x_intercept = bdi_setpoint + span; if (bdi_dirty < x_intercept - span / 4) { pos_ratio = div_u64(pos_ratio * (x_intercept - bdi_dirty), x_intercept - bdi_setpoint + 1); } else pos_ratio /= 4; /* * bdi reserve area, safeguard against dirty pool underrun and disk idle * It may push the desired control point of global dirty pages higher * than setpoint. */ x_intercept = bdi_thresh / 2; if (bdi_dirty < x_intercept) { if (bdi_dirty > x_intercept / 8) pos_ratio = div_u64(pos_ratio * x_intercept, bdi_dirty); else pos_ratio *= 8; } return pos_ratio; } static void bdi_update_write_bandwidth(struct backing_dev_info *bdi, unsigned long elapsed, unsigned long written) { const unsigned long period = roundup_pow_of_two(3 * HZ); unsigned long avg = bdi->avg_write_bandwidth; unsigned long old = bdi->write_bandwidth; u64 bw; /* * bw = written * HZ / elapsed * * bw * elapsed + write_bandwidth * (period - elapsed) * write_bandwidth = --------------------------------------------------- * period * * @written may have decreased due to account_page_redirty(). * Avoid underflowing @bw calculation. */ bw = written - min(written, bdi->written_stamp); bw *= HZ; if (unlikely(elapsed > period)) { do_div(bw, elapsed); avg = bw; goto out; } bw += (u64)bdi->write_bandwidth * (period - elapsed); bw >>= ilog2(period); /* * one more level of smoothing, for filtering out sudden spikes */ if (avg > old && old >= (unsigned long)bw) avg -= (avg - old) >> 3; if (avg < old && old <= (unsigned long)bw) avg += (old - avg) >> 3; out: bdi->write_bandwidth = bw; bdi->avg_write_bandwidth = avg; } /* * The global dirtyable memory and dirty threshold could be suddenly knocked * down by a large amount (eg. on the startup of KVM in a swapless system). * This may throw the system into deep dirty exceeded state and throttle * heavy/light dirtiers alike. To retain good responsiveness, maintain * global_dirty_limit for tracking slowly down to the knocked down dirty * threshold. */ static void update_dirty_limit(unsigned long thresh, unsigned long dirty) { unsigned long limit = global_dirty_limit; /* * Follow up in one step. */ if (limit < thresh) { limit = thresh; goto update; } /* * Follow down slowly. Use the higher one as the target, because thresh * may drop below dirty. This is exactly the reason to introduce * global_dirty_limit which is guaranteed to lie above the dirty pages. */ thresh = max(thresh, dirty); if (limit > thresh) { limit -= (limit - thresh) >> 5; goto update; } return; update: global_dirty_limit = limit; } static void global_update_bandwidth(unsigned long thresh, unsigned long dirty, unsigned long now) { static DEFINE_SPINLOCK(dirty_lock); static unsigned long update_time = INITIAL_JIFFIES; /* * check locklessly first to optimize away locking for the most time */ if (time_before(now, update_time + BANDWIDTH_INTERVAL)) return; spin_lock(&dirty_lock); if (time_after_eq(now, update_time + BANDWIDTH_INTERVAL)) { update_dirty_limit(thresh, dirty); update_time = now; } spin_unlock(&dirty_lock); } /* * Maintain bdi->dirty_ratelimit, the base dirty throttle rate. * * Normal bdi tasks will be curbed at or below it in long term. * Obviously it should be around (write_bw / N) when there are N dd tasks. */ static void bdi_update_dirty_ratelimit(struct backing_dev_info *bdi, unsigned long thresh, unsigned long bg_thresh, unsigned long dirty, unsigned long bdi_thresh, unsigned long bdi_dirty, unsigned long dirtied, unsigned long elapsed) { unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh); unsigned long limit = hard_dirty_limit(thresh); unsigned long setpoint = (freerun + limit) / 2; unsigned long write_bw = bdi->avg_write_bandwidth; unsigned long dirty_ratelimit = bdi->dirty_ratelimit; unsigned long dirty_rate; unsigned long task_ratelimit; unsigned long balanced_dirty_ratelimit; unsigned long pos_ratio; unsigned long step; unsigned long x; /* * The dirty rate will match the writeout rate in long term, except * when dirty pages are truncated by userspace or re-dirtied by FS. */ dirty_rate = (dirtied - bdi->dirtied_stamp) * HZ / elapsed; pos_ratio = bdi_position_ratio(bdi, thresh, bg_thresh, dirty, bdi_thresh, bdi_dirty); /* * task_ratelimit reflects each dd's dirty rate for the past 200ms. */ task_ratelimit = (u64)dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT; task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */ /* * A linear estimation of the "balanced" throttle rate. The theory is, * if there are N dd tasks, each throttled at task_ratelimit, the bdi's * dirty_rate will be measured to be (N * task_ratelimit). So the below * formula will yield the balanced rate limit (write_bw / N). * * Note that the expanded form is not a pure rate feedback: * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1) * but also takes pos_ratio into account: * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2) * * (1) is not realistic because pos_ratio also takes part in balancing * the dirty rate. Consider the state * pos_ratio = 0.5 (3) * rate = 2 * (write_bw / N) (4) * If (1) is used, it will stuck in that state! Because each dd will * be throttled at * task_ratelimit = pos_ratio * rate = (write_bw / N) (5) * yielding * dirty_rate = N * task_ratelimit = write_bw (6) * put (6) into (1) we get * rate_(i+1) = rate_(i) (7) * * So we end up using (2) to always keep * rate_(i+1) ~= (write_bw / N) (8) * regardless of the value of pos_ratio. As long as (8) is satisfied, * pos_ratio is able to drive itself to 1.0, which is not only where * the dirty count meet the setpoint, but also where the slope of * pos_ratio is most flat and hence task_ratelimit is least fluctuated. */ balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw, dirty_rate | 1); /* * balanced_dirty_ratelimit ~= (write_bw / N) <= write_bw */ if (unlikely(balanced_dirty_ratelimit > write_bw)) balanced_dirty_ratelimit = write_bw; /* * We could safely do this and return immediately: * * bdi->dirty_ratelimit = balanced_dirty_ratelimit; * * However to get a more stable dirty_ratelimit, the below elaborated * code makes use of task_ratelimit to filter out singular points and * limit the step size. * * The below code essentially only uses the relative value of * * task_ratelimit - dirty_ratelimit * = (pos_ratio - 1) * dirty_ratelimit * * which reflects the direction and size of dirty position error. */ /* * dirty_ratelimit will follow balanced_dirty_ratelimit iff * task_ratelimit is on the same side of dirty_ratelimit, too. * For example, when * - dirty_ratelimit > balanced_dirty_ratelimit * - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint) * lowering dirty_ratelimit will help meet both the position and rate * control targets. Otherwise, don't update dirty_ratelimit if it will * only help meet the rate target. After all, what the users ultimately * feel and care are stable dirty rate and small position error. * * |task_ratelimit - dirty_ratelimit| is used to limit the step size * and filter out the singular points of balanced_dirty_ratelimit. Which * keeps jumping around randomly and can even leap far away at times * due to the small 200ms estimation period of dirty_rate (we want to * keep that period small to reduce time lags). */ step = 0; /* * For strictlimit case, calculations above were based on bdi counters * and limits (starting from pos_ratio = bdi_position_ratio() and up to * balanced_dirty_ratelimit = task_ratelimit * write_bw / dirty_rate). * Hence, to calculate "step" properly, we have to use bdi_dirty as * "dirty" and bdi_setpoint as "setpoint". * * We rampup dirty_ratelimit forcibly if bdi_dirty is low because * it's possible that bdi_thresh is close to zero due to inactivity * of backing device (see the implementation of bdi_dirty_limit()). */ if (unlikely(bdi->capabilities & BDI_CAP_STRICTLIMIT)) { dirty = bdi_dirty; if (bdi_dirty < 8) setpoint = bdi_dirty + 1; else setpoint = (bdi_thresh + bdi_dirty_limit(bdi, bg_thresh)) / 2; } if (dirty < setpoint) { x = min(bdi->balanced_dirty_ratelimit, min(balanced_dirty_ratelimit, task_ratelimit)); if (dirty_ratelimit < x) step = x - dirty_ratelimit; } else { x = max(bdi->balanced_dirty_ratelimit, max(balanced_dirty_ratelimit, task_ratelimit)); if (dirty_ratelimit > x) step = dirty_ratelimit - x; } /* * Don't pursue 100% rate matching. It's impossible since the balanced * rate itself is constantly fluctuating. So decrease the track speed * when it gets close to the target. Helps eliminate pointless tremors. */ step >>= dirty_ratelimit / (2 * step + 1); /* * Limit the tracking speed to avoid overshooting. */ step = (step + 7) / 8; if (dirty_ratelimit < balanced_dirty_ratelimit) dirty_ratelimit += step; else dirty_ratelimit -= step; bdi->dirty_ratelimit = max(dirty_ratelimit, 1UL); bdi->balanced_dirty_ratelimit = balanced_dirty_ratelimit; trace_bdi_dirty_ratelimit(bdi, dirty_rate, task_ratelimit); } void __bdi_update_bandwidth(struct backing_dev_info *bdi, unsigned long thresh, unsigned long bg_thresh, unsigned long dirty, unsigned long bdi_thresh, unsigned long bdi_dirty, unsigned long start_time) { unsigned long now = jiffies; unsigned long elapsed = now - bdi->bw_time_stamp; unsigned long dirtied; unsigned long written; /* * rate-limit, only update once every 200ms. */ if (elapsed < BANDWIDTH_INTERVAL) return; dirtied = percpu_counter_read(&bdi->bdi_stat[BDI_DIRTIED]); written = percpu_counter_read(&bdi->bdi_stat[BDI_WRITTEN]); /* * Skip quiet periods when disk bandwidth is under-utilized. * (at least 1s idle time between two flusher runs) */ if (elapsed > HZ && time_before(bdi->bw_time_stamp, start_time)) goto snapshot; if (thresh) { global_update_bandwidth(thresh, dirty, now); bdi_update_dirty_ratelimit(bdi, thresh, bg_thresh, dirty, bdi_thresh, bdi_dirty, dirtied, elapsed); } bdi_update_write_bandwidth(bdi, elapsed, written); snapshot: bdi->dirtied_stamp = dirtied; bdi->written_stamp = written; bdi->bw_time_stamp = now; } static void bdi_update_bandwidth(struct backing_dev_info *bdi, unsigned long thresh, unsigned long bg_thresh, unsigned long dirty, unsigned long bdi_thresh, unsigned long bdi_dirty, unsigned long start_time) { if (time_is_after_eq_jiffies(bdi->bw_time_stamp + BANDWIDTH_INTERVAL)) return; spin_lock(&bdi->wb.list_lock); __bdi_update_bandwidth(bdi, thresh, bg_thresh, dirty, bdi_thresh, bdi_dirty, start_time); spin_unlock(&bdi->wb.list_lock); } /* * After a task dirtied this many pages, balance_dirty_pages_ratelimited() * will look to see if it needs to start dirty throttling. * * If dirty_poll_interval is too low, big NUMA machines will call the expensive * global_page_state() too often. So scale it near-sqrt to the safety margin * (the number of pages we may dirty without exceeding the dirty limits). */ static unsigned long dirty_poll_interval(unsigned long dirty, unsigned long thresh) { if (thresh > dirty) return 1UL << (ilog2(thresh - dirty) >> 1); return 1; } static unsigned long bdi_max_pause(struct backing_dev_info *bdi, unsigned long bdi_dirty) { unsigned long bw = bdi->avg_write_bandwidth; unsigned long t; /* * Limit pause time for small memory systems. If sleeping for too long * time, a small pool of dirty/writeback pages may go empty and disk go * idle. * * 8 serves as the safety ratio. */ t = bdi_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8)); t++; return min_t(unsigned long, t, MAX_PAUSE); } static long bdi_min_pause(struct backing_dev_info *bdi, long max_pause, unsigned long task_ratelimit, unsigned long dirty_ratelimit, int *nr_dirtied_pause) { long hi = ilog2(bdi->avg_write_bandwidth); long lo = ilog2(bdi->dirty_ratelimit); long t; /* target pause */ long pause; /* estimated next pause */ int pages; /* target nr_dirtied_pause */ /* target for 10ms pause on 1-dd case */ t = max(1, HZ / 100); /* * Scale up pause time for concurrent dirtiers in order to reduce CPU * overheads. * * (N * 10ms) on 2^N concurrent tasks. */ if (hi > lo) t += (hi - lo) * (10 * HZ) / 1024; /* * This is a bit convoluted. We try to base the next nr_dirtied_pause * on the much more stable dirty_ratelimit. However the next pause time * will be computed based on task_ratelimit and the two rate limits may * depart considerably at some time. Especially if task_ratelimit goes * below dirty_ratelimit/2 and the target pause is max_pause, the next * pause time will be max_pause*2 _trimmed down_ to max_pause. As a * result task_ratelimit won't be executed faithfully, which could * eventually bring down dirty_ratelimit. * * We apply two rules to fix it up: * 1) try to estimate the next pause time and if necessary, use a lower * nr_dirtied_pause so as not to exceed max_pause. When this happens, * nr_dirtied_pause will be "dancing" with task_ratelimit. * 2) limit the target pause time to max_pause/2, so that the normal * small fluctuations of task_ratelimit won't trigger rule (1) and * nr_dirtied_pause will remain as stable as dirty_ratelimit. */ t = min(t, 1 + max_pause / 2); pages = dirty_ratelimit * t / roundup_pow_of_two(HZ); /* * Tiny nr_dirtied_pause is found to hurt I/O performance in the test * case fio-mmap-randwrite-64k, which does 16*{sync read, async write}. * When the 16 consecutive reads are often interrupted by some dirty * throttling pause during the async writes, cfq will go into idles * (deadline is fine). So push nr_dirtied_pause as high as possible * until reaches DIRTY_POLL_THRESH=32 pages. */ if (pages < DIRTY_POLL_THRESH) { t = max_pause; pages = dirty_ratelimit * t / roundup_pow_of_two(HZ); if (pages > DIRTY_POLL_THRESH) { pages = DIRTY_POLL_THRESH; t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit; } } pause = HZ * pages / (task_ratelimit + 1); if (pause > max_pause) { t = max_pause; pages = task_ratelimit * t / roundup_pow_of_two(HZ); } *nr_dirtied_pause = pages; /* * The minimal pause time will normally be half the target pause time. */ return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t; } static inline void bdi_dirty_limits(struct backing_dev_info *bdi, unsigned long dirty_thresh, unsigned long background_thresh, unsigned long *bdi_dirty, unsigned long *bdi_thresh, unsigned long *bdi_bg_thresh) { unsigned long bdi_reclaimable; /* * bdi_thresh is not treated as some limiting factor as * dirty_thresh, due to reasons * - in JBOD setup, bdi_thresh can fluctuate a lot * - in a system with HDD and USB key, the USB key may somehow * go into state (bdi_dirty >> bdi_thresh) either because * bdi_dirty starts high, or because bdi_thresh drops low. * In this case we don't want to hard throttle the USB key * dirtiers for 100 seconds until bdi_dirty drops under * bdi_thresh. Instead the auxiliary bdi control line in * bdi_position_ratio() will let the dirtier task progress * at some rate <= (write_bw / 2) for bringing down bdi_dirty. */ *bdi_thresh = bdi_dirty_limit(bdi, dirty_thresh); if (bdi_bg_thresh) *bdi_bg_thresh = div_u64((u64)*bdi_thresh * background_thresh, dirty_thresh); /* * In order to avoid the stacked BDI deadlock we need * to ensure we accurately count the 'dirty' pages when * the threshold is low. * * Otherwise it would be possible to get thresh+n pages * reported dirty, even though there are thresh-m pages * actually dirty; with m+n sitting in the percpu * deltas. */ if (*bdi_thresh < 2 * bdi_stat_error(bdi)) { bdi_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE); *bdi_dirty = bdi_reclaimable + bdi_stat_sum(bdi, BDI_WRITEBACK); } else { bdi_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE); *bdi_dirty = bdi_reclaimable + bdi_stat(bdi, BDI_WRITEBACK); } } /* * balance_dirty_pages() must be called by processes which are generating dirty * data. It looks at the number of dirty pages in the machine and will force * the caller to wait once crossing the (background_thresh + dirty_thresh) / 2. * If we're over `background_thresh' then the writeback threads are woken to * perform some writeout. */ static void balance_dirty_pages(struct address_space *mapping, unsigned long pages_dirtied) { unsigned long nr_reclaimable; /* = file_dirty + unstable_nfs */ unsigned long nr_dirty; /* = file_dirty + writeback + unstable_nfs */ unsigned long background_thresh; unsigned long dirty_thresh; long period; long pause; long max_pause; long min_pause; int nr_dirtied_pause; bool dirty_exceeded = false; unsigned long task_ratelimit; unsigned long dirty_ratelimit; unsigned long pos_ratio; struct backing_dev_info *bdi = mapping->backing_dev_info; bool strictlimit = bdi->capabilities & BDI_CAP_STRICTLIMIT; unsigned long start_time = jiffies; for (;;) { unsigned long now = jiffies; unsigned long uninitialized_var(bdi_thresh); unsigned long thresh; unsigned long uninitialized_var(bdi_dirty); unsigned long dirty; unsigned long bg_thresh; /* * Unstable writes are a feature of certain networked * filesystems (i.e. NFS) in which data may have been * written to the server's write cache, but has not yet * been flushed to permanent storage. */ nr_reclaimable = global_page_state(NR_FILE_DIRTY) + global_page_state(NR_UNSTABLE_NFS); nr_dirty = nr_reclaimable + global_page_state(NR_WRITEBACK); global_dirty_limits(&background_thresh, &dirty_thresh); if (unlikely(strictlimit)) { bdi_dirty_limits(bdi, dirty_thresh, background_thresh, &bdi_dirty, &bdi_thresh, &bg_thresh); dirty = bdi_dirty; thresh = bdi_thresh; } else { dirty = nr_dirty; thresh = dirty_thresh; bg_thresh = background_thresh; } /* * Throttle it only when the background writeback cannot * catch-up. This avoids (excessively) small writeouts * when the bdi limits are ramping up in case of !strictlimit. * * In strictlimit case make decision based on the bdi counters * and limits. Small writeouts when the bdi limits are ramping * up are the price we consciously pay for strictlimit-ing. */ if (dirty <= dirty_freerun_ceiling(thresh, bg_thresh)) { current->dirty_paused_when = now; current->nr_dirtied = 0; current->nr_dirtied_pause = dirty_poll_interval(dirty, thresh); break; } if (unlikely(!writeback_in_progress(bdi))) bdi_start_background_writeback(bdi); if (!strictlimit) bdi_dirty_limits(bdi, dirty_thresh, background_thresh, &bdi_dirty, &bdi_thresh, NULL); dirty_exceeded = (bdi_dirty > bdi_thresh) && ((nr_dirty > dirty_thresh) || strictlimit); if (dirty_exceeded && !bdi->dirty_exceeded) bdi->dirty_exceeded = 1; bdi_update_bandwidth(bdi, dirty_thresh, background_thresh, nr_dirty, bdi_thresh, bdi_dirty, start_time); dirty_ratelimit = bdi->dirty_ratelimit; pos_ratio = bdi_position_ratio(bdi, dirty_thresh, background_thresh, nr_dirty, bdi_thresh, bdi_dirty); task_ratelimit = ((u64)dirty_ratelimit * pos_ratio) >> RATELIMIT_CALC_SHIFT; max_pause = bdi_max_pause(bdi, bdi_dirty); min_pause = bdi_min_pause(bdi, max_pause, task_ratelimit, dirty_ratelimit, &nr_dirtied_pause); if (unlikely(task_ratelimit == 0)) { period = max_pause; pause = max_pause; goto pause; } period = HZ * pages_dirtied / task_ratelimit; pause = period; if (current->dirty_paused_when) pause -= now - current->dirty_paused_when; /* * For less than 1s think time (ext3/4 may block the dirtier * for up to 800ms from time to time on 1-HDD; so does xfs, * however at much less frequency), try to compensate it in * future periods by updating the virtual time; otherwise just * do a reset, as it may be a light dirtier. */ if (pause < min_pause) { trace_balance_dirty_pages(bdi, dirty_thresh, background_thresh, nr_dirty, bdi_thresh, bdi_dirty, dirty_ratelimit, task_ratelimit, pages_dirtied, period, min(pause, 0L), start_time); if (pause < -HZ) { current->dirty_paused_when = now; current->nr_dirtied = 0; } else if (period) { current->dirty_paused_when += period; current->nr_dirtied = 0; } else if (current->nr_dirtied_pause <= pages_dirtied) current->nr_dirtied_pause += pages_dirtied; break; } if (unlikely(pause > max_pause)) { /* for occasional dropped task_ratelimit */ now += min(pause - max_pause, max_pause); pause = max_pause; } pause: trace_balance_dirty_pages(bdi, dirty_thresh, background_thresh, nr_dirty, bdi_thresh, bdi_dirty, dirty_ratelimit, task_ratelimit, pages_dirtied, period, pause, start_time); __set_current_state(TASK_KILLABLE); io_schedule_timeout(pause); current->dirty_paused_when = now + pause; current->nr_dirtied = 0; current->nr_dirtied_pause = nr_dirtied_pause; /* * This is typically equal to (nr_dirty < dirty_thresh) and can * also keep "1000+ dd on a slow USB stick" under control. */ if (task_ratelimit) break; /* * In the case of an unresponding NFS server and the NFS dirty * pages exceeds dirty_thresh, give the other good bdi's a pipe * to go through, so that tasks on them still remain responsive. * * In theory 1 page is enough to keep the comsumer-producer * pipe going: the flusher cleans 1 page => the task dirties 1 * more page. However bdi_dirty has accounting errors. So use * the larger and more IO friendly bdi_stat_error. */ if (bdi_dirty <= bdi_stat_error(bdi)) break; if (fatal_signal_pending(current)) break; } if (!dirty_exceeded && bdi->dirty_exceeded) bdi->dirty_exceeded = 0; if (writeback_in_progress(bdi)) return; /* * In laptop mode, we wait until hitting the higher threshold before * starting background writeout, and then write out all the way down * to the lower threshold. So slow writers cause minimal disk activity. * * In normal mode, we start background writeout at the lower * background_thresh, to keep the amount of dirty memory low. */ if (laptop_mode) return; if (nr_reclaimable > background_thresh) bdi_start_background_writeback(bdi); } void set_page_dirty_balance(struct page *page, int page_mkwrite) { if (set_page_dirty(page) || page_mkwrite) { struct address_space *mapping = page_mapping(page); if (mapping) balance_dirty_pages_ratelimited(mapping); } } static DEFINE_PER_CPU(int, bdp_ratelimits); /* * Normal tasks are throttled by * loop { * dirty tsk->nr_dirtied_pause pages; * take a snap in balance_dirty_pages(); * } * However there is a worst case. If every task exit immediately when dirtied * (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be * called to throttle the page dirties. The solution is to save the not yet * throttled page dirties in dirty_throttle_leaks on task exit and charge them * randomly into the running tasks. This works well for the above worst case, * as the new task will pick up and accumulate the old task's leaked dirty * count and eventually get throttled. */ DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0; /** * balance_dirty_pages_ratelimited - balance dirty memory state * @mapping: address_space which was dirtied * * Processes which are dirtying memory should call in here once for each page * which was newly dirtied. The function will periodically check the system's * dirty state and will initiate writeback if needed. * * On really big machines, get_writeback_state is expensive, so try to avoid * calling it too often (ratelimiting). But once we're over the dirty memory * limit we decrease the ratelimiting by a lot, to prevent individual processes * from overshooting the limit by (ratelimit_pages) each. */ void balance_dirty_pages_ratelimited(struct address_space *mapping) { struct backing_dev_info *bdi = mapping->backing_dev_info; int ratelimit; int *p; if (!bdi_cap_account_dirty(bdi)) return; ratelimit = current->nr_dirtied_pause; if (bdi->dirty_exceeded) ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10)); preempt_disable(); /* * This prevents one CPU to accumulate too many dirtied pages without * calling into balance_dirty_pages(), which can happen when there are * 1000+ tasks, all of them start dirtying pages at exactly the same * time, hence all honoured too large initial task->nr_dirtied_pause. */ p = &__get_cpu_var(bdp_ratelimits); if (unlikely(current->nr_dirtied >= ratelimit)) *p = 0; else if (unlikely(*p >= ratelimit_pages)) { *p = 0; ratelimit = 0; } /* * Pick up the dirtied pages by the exited tasks. This avoids lots of * short-lived tasks (eg. gcc invocations in a kernel build) escaping * the dirty throttling and livelock other long-run dirtiers. */ p = &__get_cpu_var(dirty_throttle_leaks); if (*p > 0 && current->nr_dirtied < ratelimit) { unsigned long nr_pages_dirtied; nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied); *p -= nr_pages_dirtied; current->nr_dirtied += nr_pages_dirtied; } preempt_enable(); if (unlikely(current->nr_dirtied >= ratelimit)) balance_dirty_pages(mapping, current->nr_dirtied); } EXPORT_SYMBOL(balance_dirty_pages_ratelimited); void throttle_vm_writeout(gfp_t gfp_mask) { unsigned long background_thresh; unsigned long dirty_thresh; for ( ; ; ) { global_dirty_limits(&background_thresh, &dirty_thresh); dirty_thresh = hard_dirty_limit(dirty_thresh); /* * Boost the allowable dirty threshold a bit for page * allocators so they don't get DoS'ed by heavy writers */ dirty_thresh += dirty_thresh / 10; /* wheeee... */ if (global_page_state(NR_UNSTABLE_NFS) + global_page_state(NR_WRITEBACK) <= dirty_thresh) break; /* Try safe version */ else if (unlikely(global_page_state_snapshot(NR_UNSTABLE_NFS) + global_page_state_snapshot(NR_WRITEBACK) <= dirty_thresh)) break; congestion_wait(BLK_RW_ASYNC, HZ/10); /* * The caller might hold locks which can prevent IO completion * or progress in the filesystem. So we cannot just sit here * waiting for IO to complete. */ if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO)) break; } } /* * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs */ int dirty_writeback_centisecs_handler(ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { proc_dointvec(table, write, buffer, length, ppos); return 0; } #ifdef CONFIG_BLOCK void laptop_mode_timer_fn(unsigned long data) { struct request_queue *q = (struct request_queue *)data; int nr_pages = global_page_state(NR_FILE_DIRTY) + global_page_state(NR_UNSTABLE_NFS); /* * We want to write everything out, not just down to the dirty * threshold */ if (bdi_has_dirty_io(&q->backing_dev_info)) bdi_start_writeback(&q->backing_dev_info, nr_pages, WB_REASON_LAPTOP_TIMER); } /* * We've spun up the disk and we're in laptop mode: schedule writeback * of all dirty data a few seconds from now. If the flush is already scheduled * then push it back - the user is still using the disk. */ void laptop_io_completion(struct backing_dev_info *info) { mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode); } /* * We're in laptop mode and we've just synced. The sync's writes will have * caused another writeback to be scheduled by laptop_io_completion. * Nothing needs to be written back anymore, so we unschedule the writeback. */ void laptop_sync_completion(void) { struct backing_dev_info *bdi; rcu_read_lock(); list_for_each_entry_rcu(bdi, &bdi_list, bdi_list) del_timer(&bdi->laptop_mode_wb_timer); rcu_read_unlock(); } #endif /* * If ratelimit_pages is too high then we can get into dirty-data overload * if a large number of processes all perform writes at the same time. * If it is too low then SMP machines will call the (expensive) * get_writeback_state too often. * * Here we set ratelimit_pages to a level which ensures that when all CPUs are * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory * thresholds. */ void writeback_set_ratelimit(void) { unsigned long background_thresh; unsigned long dirty_thresh; global_dirty_limits(&background_thresh, &dirty_thresh); global_dirty_limit = dirty_thresh; ratelimit_pages = dirty_thresh / (num_online_cpus() * 32); if (ratelimit_pages < 16) ratelimit_pages = 16; } static int __cpuinit ratelimit_handler(struct notifier_block *self, unsigned long action, void *hcpu) { switch (action & ~CPU_TASKS_FROZEN) { case CPU_ONLINE: case CPU_DEAD: writeback_set_ratelimit(); return NOTIFY_OK; default: return NOTIFY_DONE; } } static struct notifier_block __cpuinitdata ratelimit_nb = { .notifier_call = ratelimit_handler, .next = NULL, }; /* * Called early on to tune the page writeback dirty limits. * * We used to scale dirty pages according to how total memory * related to pages that could be allocated for buffers (by * comparing nr_free_buffer_pages() to vm_total_pages. * * However, that was when we used "dirty_ratio" to scale with * all memory, and we don't do that any more. "dirty_ratio" * is now applied to total non-HIGHPAGE memory (by subtracting * totalhigh_pages from vm_total_pages), and as such we can't * get into the old insane situation any more where we had * large amounts of dirty pages compared to a small amount of * non-HIGHMEM memory. * * But we might still want to scale the dirty_ratio by how * much memory the box has.. */ void __init page_writeback_init(void) { writeback_set_ratelimit(); register_cpu_notifier(&ratelimit_nb); fprop_global_init(&writeout_completions); } /** * tag_pages_for_writeback - tag pages to be written by write_cache_pages * @mapping: address space structure to write * @start: starting page index * @end: ending page index (inclusive) * * This function scans the page range from @start to @end (inclusive) and tags * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is * that write_cache_pages (or whoever calls this function) will then use * TOWRITE tag to identify pages eligible for writeback. This mechanism is * used to avoid livelocking of writeback by a process steadily creating new * dirty pages in the file (thus it is important for this function to be quick * so that it can tag pages faster than a dirtying process can create them). */ /* * We tag pages in batches of WRITEBACK_TAG_BATCH to reduce tree_lock latency. */ void tag_pages_for_writeback(struct address_space *mapping, pgoff_t start, pgoff_t end) { #define WRITEBACK_TAG_BATCH 4096 unsigned long tagged; do { spin_lock_irq(&mapping->tree_lock); tagged = radix_tree_range_tag_if_tagged(&mapping->page_tree, &start, end, WRITEBACK_TAG_BATCH, PAGECACHE_TAG_DIRTY, PAGECACHE_TAG_TOWRITE); spin_unlock_irq(&mapping->tree_lock); WARN_ON_ONCE(tagged > WRITEBACK_TAG_BATCH); cond_resched(); /* We check 'start' to handle wrapping when end == ~0UL */ } while (tagged >= WRITEBACK_TAG_BATCH && start); } EXPORT_SYMBOL(tag_pages_for_writeback); /** * write_cache_pages - walk the list of dirty pages of the given address space and write all of them. * @mapping: address space structure to write * @wbc: subtract the number of written pages from *@wbc->nr_to_write * @writepage: function called for each page * @data: data passed to writepage function * * If a page is already under I/O, write_cache_pages() skips it, even * if it's dirty. This is desirable behaviour for memory-cleaning writeback, * but it is INCORRECT for data-integrity system calls such as fsync(). fsync() * and msync() need to guarantee that all the data which was dirty at the time * the call was made get new I/O started against them. If wbc->sync_mode is * WB_SYNC_ALL then we were called for data integrity and we must wait for * existing IO to complete. * * To avoid livelocks (when other process dirties new pages), we first tag * pages which should be written back with TOWRITE tag and only then start * writing them. For data-integrity sync we have to be careful so that we do * not miss some pages (e.g., because some other process has cleared TOWRITE * tag we set). The rule we follow is that TOWRITE tag can be cleared only * by the process clearing the DIRTY tag (and submitting the page for IO). */ int write_cache_pages(struct address_space *mapping, struct writeback_control *wbc, writepage_t writepage, void *data) { int ret = 0; int done = 0; struct pagevec pvec; int nr_pages; pgoff_t uninitialized_var(writeback_index); pgoff_t index; pgoff_t end; /* Inclusive */ pgoff_t done_index; int cycled; int range_whole = 0; int tag; pagevec_init(&pvec, 0); if (wbc->range_cyclic) { writeback_index = mapping->writeback_index; /* prev offset */ index = writeback_index; if (index == 0) cycled = 1; else cycled = 0; end = -1; } else { index = wbc->range_start >> PAGE_CACHE_SHIFT; end = wbc->range_end >> PAGE_CACHE_SHIFT; if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX) range_whole = 1; cycled = 1; /* ignore range_cyclic tests */ } if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) tag = PAGECACHE_TAG_TOWRITE; else tag = PAGECACHE_TAG_DIRTY; retry: if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) tag_pages_for_writeback(mapping, index, end); done_index = index; while (!done && (index <= end)) { int i; nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag, min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1); if (nr_pages == 0) break; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; /* * At this point, the page may be truncated or * invalidated (changing page->mapping to NULL), or * even swizzled back from swapper_space to tmpfs file * mapping. However, page->index will not change * because we have a reference on the page. */ if (page->index > end) { /* * can't be range_cyclic (1st pass) because * end == -1 in that case. */ done = 1; break; } done_index = page->index; lock_page(page); /* * Page truncated or invalidated. We can freely skip it * then, even for data integrity operations: the page * has disappeared concurrently, so there could be no * real expectation of this data interity operation * even if there is now a new, dirty page at the same * pagecache address. */ if (unlikely(page->mapping != mapping)) { continue_unlock: unlock_page(page); continue; } if (!PageDirty(page)) { /* someone wrote it for us */ goto continue_unlock; } if (PageWriteback(page)) { if (wbc->sync_mode != WB_SYNC_NONE) wait_on_page_writeback(page); else goto continue_unlock; } BUG_ON(PageWriteback(page)); if (!clear_page_dirty_for_io(page)) goto continue_unlock; trace_wbc_writepage(wbc, mapping->backing_dev_info); ret = (*writepage)(page, wbc, data); if (unlikely(ret)) { if (ret == AOP_WRITEPAGE_ACTIVATE) { unlock_page(page); ret = 0; } else { /* * done_index is set past this page, * so media errors will not choke * background writeout for the entire * file. This has consequences for * range_cyclic semantics (ie. it may * not be suitable for data integrity * writeout). */ done_index = page->index + 1; done = 1; break; } } /* * We stop writing back only if we are not doing * integrity sync. In case of integrity sync we have to * keep going until we have written all the pages * we tagged for writeback prior to entering this loop. */ if (--wbc->nr_to_write <= 0 && wbc->sync_mode == WB_SYNC_NONE) { done = 1; break; } } pagevec_release(&pvec); cond_resched(); } if (!cycled && !done) { /* * range_cyclic: * We hit the last page and there is more work to be done: wrap * back to the start of the file */ cycled = 1; index = 0; end = writeback_index - 1; goto retry; } if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) mapping->writeback_index = done_index; return ret; } EXPORT_SYMBOL(write_cache_pages); /* * Function used by generic_writepages to call the real writepage * function and set the mapping flags on error */ static int __writepage(struct page *page, struct writeback_control *wbc, void *data) { struct address_space *mapping = data; int ret = mapping->a_ops->writepage(page, wbc); mapping_set_error(mapping, ret); return ret; } /** * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them. * @mapping: address space structure to write * @wbc: subtract the number of written pages from *@wbc->nr_to_write * * This is a library function, which implements the writepages() * address_space_operation. */ int generic_writepages(struct address_space *mapping, struct writeback_control *wbc) { struct blk_plug plug; int ret; /* deal with chardevs and other special file */ if (!mapping->a_ops->writepage) return 0; blk_start_plug(&plug); ret = write_cache_pages(mapping, wbc, __writepage, mapping); blk_finish_plug(&plug); return ret; } EXPORT_SYMBOL(generic_writepages); int do_writepages(struct address_space *mapping, struct writeback_control *wbc) { int ret; if (wbc->nr_to_write <= 0) return 0; if (mapping->a_ops->writepages) ret = mapping->a_ops->writepages(mapping, wbc); else ret = generic_writepages(mapping, wbc); return ret; } /** * write_one_page - write out a single page and optionally wait on I/O * @page: the page to write * @wait: if true, wait on writeout * * The page must be locked by the caller and will be unlocked upon return. * * write_one_page() returns a negative error code if I/O failed. */ int write_one_page(struct page *page, int wait) { struct address_space *mapping = page->mapping; int ret = 0; struct writeback_control wbc = { .sync_mode = WB_SYNC_ALL, .nr_to_write = 1, }; BUG_ON(!PageLocked(page)); if (wait) wait_on_page_writeback(page); if (clear_page_dirty_for_io(page)) { page_cache_get(page); ret = mapping->a_ops->writepage(page, &wbc); if (ret == 0 && wait) { wait_on_page_writeback(page); if (PageError(page)) ret = -EIO; } page_cache_release(page); } else { unlock_page(page); } return ret; } EXPORT_SYMBOL(write_one_page); /* * For address_spaces which do not use buffers nor write back. */ int __set_page_dirty_no_writeback(struct page *page) { if (!PageDirty(page)) return !TestSetPageDirty(page); return 0; } /* * Helper function for set_page_dirty family. * NOTE: This relies on being atomic wrt interrupts. */ void account_page_dirtied(struct page *page, struct address_space *mapping) { trace_writeback_dirty_page(page, mapping); if (mapping_cap_account_dirty(mapping)) { __inc_zone_page_state(page, NR_FILE_DIRTY); __inc_zone_page_state(page, NR_DIRTIED); __inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE); __inc_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED); task_io_account_write(PAGE_CACHE_SIZE); current->nr_dirtied++; this_cpu_inc(bdp_ratelimits); } } EXPORT_SYMBOL(account_page_dirtied); /* * Helper function for set_page_writeback family. * NOTE: Unlike account_page_dirtied this does not rely on being atomic * wrt interrupts. */ void account_page_writeback(struct page *page) { inc_zone_page_state(page, NR_WRITEBACK); } EXPORT_SYMBOL(account_page_writeback); /* * For address_spaces which do not use buffers. Just tag the page as dirty in * its radix tree. * * This is also used when a single buffer is being dirtied: we want to set the * page dirty in that case, but not all the buffers. This is a "bottom-up" * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying. * * Most callers have locked the page, which pins the address_space in memory. * But zap_pte_range() does not lock the page, however in that case the * mapping is pinned by the vma's ->vm_file reference. * * We take care to handle the case where the page was truncated from the * mapping by re-checking page_mapping() inside tree_lock. */ int __set_page_dirty_nobuffers(struct page *page) { if (!TestSetPageDirty(page)) { struct address_space *mapping = page_mapping(page); struct address_space *mapping2; unsigned long flags; if (!mapping) return 1; spin_lock_irqsave(&mapping->tree_lock, flags); mapping2 = page_mapping(page); if (mapping2) { /* Race with truncate? */ BUG_ON(mapping2 != mapping); WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page)); account_page_dirtied(page, mapping); radix_tree_tag_set(&mapping->page_tree, page_index(page), PAGECACHE_TAG_DIRTY); } spin_unlock_irqrestore(&mapping->tree_lock, flags); if (mapping->host) { /* !PageAnon && !swapper_space */ __mark_inode_dirty(mapping->host, I_DIRTY_PAGES); } return 1; } return 0; } EXPORT_SYMBOL(__set_page_dirty_nobuffers); /* * Call this whenever redirtying a page, to de-account the dirty counters * (NR_DIRTIED, BDI_DIRTIED, tsk->nr_dirtied), so that they match the written * counters (NR_WRITTEN, BDI_WRITTEN) in long term. The mismatches will lead to * systematic errors in balanced_dirty_ratelimit and the dirty pages position * control. */ void account_page_redirty(struct page *page) { struct address_space *mapping = page->mapping; if (mapping && mapping_cap_account_dirty(mapping)) { current->nr_dirtied--; dec_zone_page_state(page, NR_DIRTIED); dec_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED); } } EXPORT_SYMBOL(account_page_redirty); /* * When a writepage implementation decides that it doesn't want to write this * page for some reason, it should redirty the locked page via * redirty_page_for_writepage() and it should then unlock the page and return 0 */ int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page) { wbc->pages_skipped++; account_page_redirty(page); return __set_page_dirty_nobuffers(page); } EXPORT_SYMBOL(redirty_page_for_writepage); /* * Dirty a page. * * For pages with a mapping this should be done under the page lock * for the benefit of asynchronous memory errors who prefer a consistent * dirty state. This rule can be broken in some special cases, * but should be better not to. * * If the mapping doesn't provide a set_page_dirty a_op, then * just fall through and assume that it wants buffer_heads. */ int set_page_dirty(struct page *page) { struct address_space *mapping = page_mapping(page); if (likely(mapping)) { int (*spd)(struct page *) = mapping->a_ops->set_page_dirty; /* * readahead/lru_deactivate_page could remain * PG_readahead/PG_reclaim due to race with end_page_writeback * About readahead, if the page is written, the flags would be * reset. So no problem. * About lru_deactivate_page, if the page is redirty, the flag * will be reset. So no problem. but if the page is used by readahead * it will confuse readahead and make it restart the size rampup * process. But it's a trivial problem. */ ClearPageReclaim(page); #ifdef CONFIG_BLOCK if (!spd) spd = __set_page_dirty_buffers; #endif return (*spd)(page); } if (!PageDirty(page)) { if (!TestSetPageDirty(page)) return 1; } return 0; } EXPORT_SYMBOL(set_page_dirty); /* * set_page_dirty() is racy if the caller has no reference against * page->mapping->host, and if the page is unlocked. This is because another * CPU could truncate the page off the mapping and then free the mapping. * * Usually, the page _is_ locked, or the caller is a user-space process which * holds a reference on the inode by having an open file. * * In other cases, the page should be locked before running set_page_dirty(). */ int set_page_dirty_lock(struct page *page) { int ret; lock_page(page); ret = set_page_dirty(page); unlock_page(page); return ret; } EXPORT_SYMBOL(set_page_dirty_lock); /* * Clear a page's dirty flag, while caring for dirty memory accounting. * Returns true if the page was previously dirty. * * This is for preparing to put the page under writeout. We leave the page * tagged as dirty in the radix tree so that a concurrent write-for-sync * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage * implementation will run either set_page_writeback() or set_page_dirty(), * at which stage we bring the page's dirty flag and radix-tree dirty tag * back into sync. * * This incoherency between the page's dirty flag and radix-tree tag is * unfortunate, but it only exists while the page is locked. */ int clear_page_dirty_for_io(struct page *page) { struct address_space *mapping = page_mapping(page); BUG_ON(!PageLocked(page)); if (mapping && mapping_cap_account_dirty(mapping)) { /* * Yes, Virginia, this is indeed insane. * * We use this sequence to make sure that * (a) we account for dirty stats properly * (b) we tell the low-level filesystem to * mark the whole page dirty if it was * dirty in a pagetable. Only to then * (c) clean the page again and return 1 to * cause the writeback. * * This way we avoid all nasty races with the * dirty bit in multiple places and clearing * them concurrently from different threads. * * Note! Normally the "set_page_dirty(page)" * has no effect on the actual dirty bit - since * that will already usually be set. But we * need the side effects, and it can help us * avoid races. * * We basically use the page "master dirty bit" * as a serialization point for all the different * threads doing their things. */ if (page_mkclean(page)) set_page_dirty(page); /* * We carefully synchronise fault handlers against * installing a dirty pte and marking the page dirty * at this point. We do this by having them hold the * page lock at some point after installing their * pte, but before marking the page dirty. * Pages are always locked coming in here, so we get * the desired exclusion. See mm/memory.c:do_wp_page() * for more comments. */ if (TestClearPageDirty(page)) { dec_zone_page_state(page, NR_FILE_DIRTY); dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE); return 1; } return 0; } return TestClearPageDirty(page); } EXPORT_SYMBOL(clear_page_dirty_for_io); int test_clear_page_writeback(struct page *page) { struct address_space *mapping = page_mapping(page); int ret; if (mapping) { struct backing_dev_info *bdi = mapping->backing_dev_info; unsigned long flags; spin_lock_irqsave(&mapping->tree_lock, flags); ret = TestClearPageWriteback(page); if (ret) { radix_tree_tag_clear(&mapping->page_tree, page_index(page), PAGECACHE_TAG_WRITEBACK); if (bdi_cap_account_writeback(bdi)) { __dec_bdi_stat(bdi, BDI_WRITEBACK); __bdi_writeout_inc(bdi); } } spin_unlock_irqrestore(&mapping->tree_lock, flags); } else { ret = TestClearPageWriteback(page); } if (ret) { dec_zone_page_state(page, NR_WRITEBACK); inc_zone_page_state(page, NR_WRITTEN); } return ret; } int test_set_page_writeback(struct page *page) { struct address_space *mapping = page_mapping(page); int ret; if (mapping) { struct backing_dev_info *bdi = mapping->backing_dev_info; unsigned long flags; spin_lock_irqsave(&mapping->tree_lock, flags); ret = TestSetPageWriteback(page); if (!ret) { radix_tree_tag_set(&mapping->page_tree, page_index(page), PAGECACHE_TAG_WRITEBACK); if (bdi_cap_account_writeback(bdi)) __inc_bdi_stat(bdi, BDI_WRITEBACK); } if (!PageDirty(page)) radix_tree_tag_clear(&mapping->page_tree, page_index(page), PAGECACHE_TAG_DIRTY); radix_tree_tag_clear(&mapping->page_tree, page_index(page), PAGECACHE_TAG_TOWRITE); spin_unlock_irqrestore(&mapping->tree_lock, flags); } else { ret = TestSetPageWriteback(page); } if (!ret) account_page_writeback(page); return ret; } EXPORT_SYMBOL(test_set_page_writeback); /* * Return true if any of the pages in the mapping are marked with the * passed tag. */ int mapping_tagged(struct address_space *mapping, int tag) { return radix_tree_tagged(&mapping->page_tree, tag); } EXPORT_SYMBOL(mapping_tagged); /** * wait_for_stable_page() - wait for writeback to finish, if necessary. * @page: The page to wait on. * * This function determines if the given page is related to a backing device * that requires page contents to be held stable during writeback. If so, then * it will wait for any pending writeback to complete. */ void wait_for_stable_page(struct page *page) { struct address_space *mapping = page_mapping(page); struct backing_dev_info *bdi = mapping->backing_dev_info; if (!bdi_cap_stable_pages_required(bdi)) return; wait_on_page_writeback(page); } EXPORT_SYMBOL_GPL(wait_for_stable_page);
andrewwrightt/kernel_moto_shamu
mm/page-writeback.c
C
gpl-2.0
76,843
<?php /** * Чистый Шаблон для разработки * Шаблон вывода поста * http://dontforget.pro * @package WordPress * @subpackage clean */ get_header(); // Подключаем хедер?> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); // Начало цикла ?> <h1><?php the_title(); // Заголовок ?></h1> <?php the_content(); // Содержимое страницы ?> <?php echo 'Рубрики: '; the_category( ' | ' ); // Выводим категории поста ?> <?php the_tags( 'Тэги: ', ' | ', '' ); // Выводим тэги(метки) поста ?> <?php endwhile; // Конец цикла ?> <?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', 'twentyten' ) . '</span> %title' ); // Ссылка на предидущий пост?> <?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '&rarr;', 'Next post link', 'twentyten' ) . '</span>' ); // Ссылка на следующий пост?> <?php comments_template( '', true ); // Комментарии ?> <?php get_sidebar(); // Подключаем сайдбар ?> <?php get_footer(); // Подключаем футер ?>
lexus65/yummy.loc
wp-content/themes/yummy-theme/single.php
PHP
gpl-2.0
1,240
/* * This file is part of wl1271 * * Copyright (C) 2008-2010 Nokia Corporation * * Contact: Luciano Coelho <luciano.coelho@nokia.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <linux/module.h> #include <linux/firmware.h> #include <linux/delay.h> #include <linux/spi/spi.h> #include <linux/crc32.h> #include <linux/etherdevice.h> #include <linux/vmalloc.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/wl12xx.h> #include <linux/sched.h> #include <linux/interrupt.h> #include "wl12xx.h" #include "debug.h" #include "wl12xx_80211.h" #include "reg.h" #include "io.h" #include "event.h" #include "tx.h" #include "rx.h" #include "ps.h" #include "init.h" #include "debugfs.h" #include "cmd.h" #include "boot.h" #include "testmode.h" #include "scan.h" #define WL1271_BOOT_RETRIES 3 static struct conf_drv_settings default_conf = { .sg = { .params = { [CONF_SG_ACL_BT_MASTER_MIN_BR] = 10, [CONF_SG_ACL_BT_MASTER_MAX_BR] = 180, [CONF_SG_ACL_BT_SLAVE_MIN_BR] = 10, [CONF_SG_ACL_BT_SLAVE_MAX_BR] = 180, [CONF_SG_ACL_BT_MASTER_MIN_EDR] = 10, [CONF_SG_ACL_BT_MASTER_MAX_EDR] = 80, [CONF_SG_ACL_BT_SLAVE_MIN_EDR] = 10, [CONF_SG_ACL_BT_SLAVE_MAX_EDR] = 80, [CONF_SG_ACL_WLAN_PS_MASTER_BR] = 8, [CONF_SG_ACL_WLAN_PS_SLAVE_BR] = 8, [CONF_SG_ACL_WLAN_PS_MASTER_EDR] = 20, [CONF_SG_ACL_WLAN_PS_SLAVE_EDR] = 20, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_BR] = 20, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_BR] = 35, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_BR] = 16, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_BR] = 35, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_EDR] = 32, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_EDR] = 50, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_EDR] = 28, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_EDR] = 50, [CONF_SG_ACL_ACTIVE_SCAN_WLAN_BR] = 10, [CONF_SG_ACL_ACTIVE_SCAN_WLAN_EDR] = 20, [CONF_SG_ACL_PASSIVE_SCAN_BT_BR] = 75, [CONF_SG_ACL_PASSIVE_SCAN_WLAN_BR] = 15, [CONF_SG_ACL_PASSIVE_SCAN_BT_EDR] = 27, [CONF_SG_ACL_PASSIVE_SCAN_WLAN_EDR] = 17, /* active scan params */ [CONF_SG_AUTO_SCAN_PROBE_REQ] = 170, [CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_HV3] = 50, [CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_A2DP] = 100, /* passive scan params */ [CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_BR] = 800, [CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_EDR] = 200, [CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_HV3] = 200, /* passive scan in dual antenna params */ [CONF_SG_CONSECUTIVE_HV3_IN_PASSIVE_SCAN] = 0, [CONF_SG_BCN_HV3_COLLISION_THRESH_IN_PASSIVE_SCAN] = 0, [CONF_SG_TX_RX_PROTECTION_BWIDTH_IN_PASSIVE_SCAN] = 0, /* general params */ [CONF_SG_STA_FORCE_PS_IN_BT_SCO] = 1, [CONF_SG_ANTENNA_CONFIGURATION] = 0, [CONF_SG_BEACON_MISS_PERCENT] = 60, [CONF_SG_DHCP_TIME] = 5000, [CONF_SG_RXT] = 1200, [CONF_SG_TXT] = 1000, [CONF_SG_ADAPTIVE_RXT_TXT] = 1, [CONF_SG_GENERAL_USAGE_BIT_MAP] = 3, [CONF_SG_HV3_MAX_SERVED] = 6, [CONF_SG_PS_POLL_TIMEOUT] = 10, [CONF_SG_UPSD_TIMEOUT] = 10, [CONF_SG_CONSECUTIVE_CTS_THRESHOLD] = 2, [CONF_SG_STA_RX_WINDOW_AFTER_DTIM] = 5, [CONF_SG_STA_CONNECTION_PROTECTION_TIME] = 30, /* AP params */ [CONF_AP_BEACON_MISS_TX] = 3, [CONF_AP_RX_WINDOW_AFTER_BEACON] = 10, [CONF_AP_BEACON_WINDOW_INTERVAL] = 2, [CONF_AP_CONNECTION_PROTECTION_TIME] = 0, [CONF_AP_BT_ACL_VAL_BT_SERVE_TIME] = 25, [CONF_AP_BT_ACL_VAL_WL_SERVE_TIME] = 25, /* CTS Diluting params */ [CONF_SG_CTS_DILUTED_BAD_RX_PACKETS_TH] = 0, [CONF_SG_CTS_CHOP_IN_DUAL_ANT_SCO_MASTER] = 0, }, .state = CONF_SG_PROTECTIVE, }, .rx = { .rx_msdu_life_time = 512000, .packet_detection_threshold = 0, .ps_poll_timeout = 15, .upsd_timeout = 15, .rts_threshold = IEEE80211_MAX_RTS_THRESHOLD, .rx_cca_threshold = 0, .irq_blk_threshold = 0xFFFF, .irq_pkt_threshold = 0, .irq_timeout = 600, .queue_type = CONF_RX_QUEUE_TYPE_LOW_PRIORITY, }, .tx = { .tx_energy_detection = 0, .sta_rc_conf = { .enabled_rates = 0, .short_retry_limit = 10, .long_retry_limit = 10, .aflags = 0, }, .ac_conf_count = 4, .ac_conf = { [CONF_TX_AC_BE] = { .ac = CONF_TX_AC_BE, .cw_min = 15, .cw_max = 63, .aifsn = 3, .tx_op_limit = 0, }, [CONF_TX_AC_BK] = { .ac = CONF_TX_AC_BK, .cw_min = 15, .cw_max = 63, .aifsn = 7, .tx_op_limit = 0, }, [CONF_TX_AC_VI] = { .ac = CONF_TX_AC_VI, .cw_min = 15, .cw_max = 63, .aifsn = CONF_TX_AIFS_PIFS, .tx_op_limit = 3008, }, [CONF_TX_AC_VO] = { .ac = CONF_TX_AC_VO, .cw_min = 15, .cw_max = 63, .aifsn = CONF_TX_AIFS_PIFS, .tx_op_limit = 1504, }, }, .max_tx_retries = 100, .ap_aging_period = 300, .tid_conf_count = 4, .tid_conf = { [CONF_TX_AC_BE] = { .queue_id = CONF_TX_AC_BE, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_BE, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, [CONF_TX_AC_BK] = { .queue_id = CONF_TX_AC_BK, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_BK, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, [CONF_TX_AC_VI] = { .queue_id = CONF_TX_AC_VI, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_VI, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, [CONF_TX_AC_VO] = { .queue_id = CONF_TX_AC_VO, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_VO, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, }, .frag_threshold = IEEE80211_MAX_FRAG_THRESHOLD, .tx_compl_timeout = 700, .tx_compl_threshold = 4, .basic_rate = CONF_HW_BIT_RATE_1MBPS, .basic_rate_5 = CONF_HW_BIT_RATE_6MBPS, .tmpl_short_retry_limit = 10, .tmpl_long_retry_limit = 10, .tx_watchdog_timeout = 5000, }, .conn = { .wake_up_event = CONF_WAKE_UP_EVENT_DTIM, .listen_interval = 1, .suspend_wake_up_event = CONF_WAKE_UP_EVENT_N_DTIM, .suspend_listen_interval = 3, .bcn_filt_mode = CONF_BCN_FILT_MODE_ENABLED, .bcn_filt_ie_count = 2, .bcn_filt_ie = { [0] = { .ie = WLAN_EID_CHANNEL_SWITCH, .rule = CONF_BCN_RULE_PASS_ON_APPEARANCE, }, [1] = { .ie = WLAN_EID_HT_INFORMATION, .rule = CONF_BCN_RULE_PASS_ON_CHANGE, }, }, .synch_fail_thold = 10, .bss_lose_timeout = 100, .beacon_rx_timeout = 10000, .broadcast_timeout = 20000, .rx_broadcast_in_ps = 1, .ps_poll_threshold = 10, .bet_enable = CONF_BET_MODE_ENABLE, .bet_max_consecutive = 50, .psm_entry_retries = 8, .psm_exit_retries = 16, .psm_entry_nullfunc_retries = 3, .dynamic_ps_timeout = 200, .forced_ps = false, .keep_alive_interval = 55000, .max_listen_interval = 20, }, .itrim = { .enable = false, .timeout = 50000, }, .pm_config = { .host_clk_settling_time = 5000, .host_fast_wakeup_support = false }, .roam_trigger = { .trigger_pacing = 1, .avg_weight_rssi_beacon = 20, .avg_weight_rssi_data = 10, .avg_weight_snr_beacon = 20, .avg_weight_snr_data = 10, }, .scan = { .min_dwell_time_active = 7500, .max_dwell_time_active = 30000, .min_dwell_time_passive = 100000, .max_dwell_time_passive = 100000, .num_probe_reqs = 2, .split_scan_timeout = 50000, }, .sched_scan = { /* sched_scan requires dwell times in TU instead of TU/1000 */ .min_dwell_time_active = 30, .max_dwell_time_active = 60, .dwell_time_passive = 100, .dwell_time_dfs = 150, .num_probe_reqs = 2, .rssi_threshold = -90, .snr_threshold = 0, }, .rf = { .tx_per_channel_power_compensation_2 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, .tx_per_channel_power_compensation_5 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, }, .ht = { .rx_ba_win_size = 8, .tx_ba_win_size = 64, .inactivity_timeout = 10000, .tx_ba_tid_bitmap = CONF_TX_BA_ENABLED_TID_BITMAP, }, .mem_wl127x = { .num_stations = 1, .ssid_profiles = 1, .rx_block_num = 70, .tx_min_block_num = 40, .dynamic_memory = 1, .min_req_tx_blocks = 100, .min_req_rx_blocks = 22, .tx_min = 27, }, .mem_wl128x = { .num_stations = 1, .ssid_profiles = 1, .rx_block_num = 40, .tx_min_block_num = 40, .dynamic_memory = 1, .min_req_tx_blocks = 45, .min_req_rx_blocks = 22, .tx_min = 27, }, .fm_coex = { .enable = true, .swallow_period = 5, .n_divider_fref_set_1 = 0xff, /* default */ .n_divider_fref_set_2 = 12, .m_divider_fref_set_1 = 148, .m_divider_fref_set_2 = 0xffff, /* default */ .coex_pll_stabilization_time = 0xffffffff, /* default */ .ldo_stabilization_time = 0xffff, /* default */ .fm_disturbed_band_margin = 0xff, /* default */ .swallow_clk_diff = 0xff, /* default */ }, .rx_streaming = { .duration = 150, .queues = 0x1, .interval = 20, .always = 0, }, .fwlog = { .mode = WL12XX_FWLOG_ON_DEMAND, .mem_blocks = 2, .severity = 0, .timestamp = WL12XX_FWLOG_TIMESTAMP_DISABLED, .output = WL12XX_FWLOG_OUTPUT_HOST, .threshold = 0, }, .hci_io_ds = HCI_IO_DS_6MA, .rate = { .rate_retry_score = 32000, .per_add = 8192, .per_th1 = 2048, .per_th2 = 4096, .max_per = 8100, .inverse_curiosity_factor = 5, .tx_fail_low_th = 4, .tx_fail_high_th = 10, .per_alpha_shift = 4, .per_add_shift = 13, .per_beta1_shift = 10, .per_beta2_shift = 8, .rate_check_up = 2, .rate_check_down = 12, .rate_retry_policy = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, }, .hangover = { .recover_time = 0, .hangover_period = 20, .dynamic_mode = 1, .early_termination_mode = 1, .max_period = 20, .min_period = 1, .increase_delta = 1, .decrease_delta = 2, .quiet_time = 4, .increase_time = 1, .window_size = 16, }, }; static char *fwlog_param; static bool bug_on_recovery; static void __wl1271_op_remove_interface(struct wl1271 *wl, struct ieee80211_vif *vif, bool reset_tx_queues); static void wl1271_op_stop(struct ieee80211_hw *hw); static void wl1271_free_ap_keys(struct wl1271 *wl, struct wl12xx_vif *wlvif); static int wl12xx_set_authorized(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret; if (WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS)) return -EINVAL; if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) return 0; if (test_and_set_bit(WLVIF_FLAG_STA_STATE_SENT, &wlvif->flags)) return 0; ret = wl12xx_cmd_set_peer_state(wl, wlvif->sta.hlid); if (ret < 0) return ret; wl12xx_croc(wl, wlvif->role_id); wl1271_info("Association completed."); return 0; } static int wl1271_reg_notify(struct wiphy *wiphy, struct regulatory_request *request) { struct ieee80211_supported_band *band; struct ieee80211_channel *ch; int i; band = wiphy->bands[IEEE80211_BAND_5GHZ]; for (i = 0; i < band->n_channels; i++) { ch = &band->channels[i]; if (ch->flags & IEEE80211_CHAN_DISABLED) continue; if (ch->flags & IEEE80211_CHAN_RADAR) ch->flags |= IEEE80211_CHAN_NO_IBSS | IEEE80211_CHAN_PASSIVE_SCAN; } return 0; } static int wl1271_set_rx_streaming(struct wl1271 *wl, struct wl12xx_vif *wlvif, bool enable) { int ret = 0; /* we should hold wl->mutex */ ret = wl1271_acx_ps_rx_streaming(wl, wlvif, enable); if (ret < 0) goto out; if (enable) set_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags); else clear_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags); out: return ret; } /* * this function is being called when the rx_streaming interval * has beed changed or rx_streaming should be disabled */ int wl1271_recalc_rx_streaming(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret = 0; int period = wl->conf.rx_streaming.interval; /* don't reconfigure if rx_streaming is disabled */ if (!test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags)) goto out; /* reconfigure/disable according to new streaming_period */ if (period && test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) && (wl->conf.rx_streaming.always || test_bit(WL1271_FLAG_SOFT_GEMINI, &wl->flags))) ret = wl1271_set_rx_streaming(wl, wlvif, true); else { ret = wl1271_set_rx_streaming(wl, wlvif, false); /* don't cancel_work_sync since we might deadlock */ del_timer_sync(&wlvif->rx_streaming_timer); } out: return ret; } static void wl1271_rx_streaming_enable_work(struct work_struct *work) { int ret; struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif, rx_streaming_enable_work); struct wl1271 *wl = wlvif->wl; mutex_lock(&wl->mutex); if (test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags) || !test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) || (!wl->conf.rx_streaming.always && !test_bit(WL1271_FLAG_SOFT_GEMINI, &wl->flags))) goto out; if (!wl->conf.rx_streaming.interval) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl1271_set_rx_streaming(wl, wlvif, true); if (ret < 0) goto out_sleep; /* stop it after some time of inactivity */ mod_timer(&wlvif->rx_streaming_timer, jiffies + msecs_to_jiffies(wl->conf.rx_streaming.duration)); out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static void wl1271_rx_streaming_disable_work(struct work_struct *work) { int ret; struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif, rx_streaming_disable_work); struct wl1271 *wl = wlvif->wl; mutex_lock(&wl->mutex); if (!test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl1271_set_rx_streaming(wl, wlvif, false); if (ret) goto out_sleep; out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static void wl1271_rx_streaming_timer(unsigned long data) { struct wl12xx_vif *wlvif = (struct wl12xx_vif *)data; struct wl1271 *wl = wlvif->wl; ieee80211_queue_work(wl->hw, &wlvif->rx_streaming_disable_work); } /* wl->mutex must be taken */ void wl12xx_rearm_tx_watchdog_locked(struct wl1271 *wl) { /* if the watchdog is not armed, don't do anything */ if (wl->tx_allocated_blocks == 0) return; cancel_delayed_work(&wl->tx_watchdog_work); ieee80211_queue_delayed_work(wl->hw, &wl->tx_watchdog_work, msecs_to_jiffies(wl->conf.tx.tx_watchdog_timeout)); } static void wl12xx_tx_watchdog_work(struct work_struct *work) { struct delayed_work *dwork; struct wl1271 *wl; dwork = container_of(work, struct delayed_work, work); wl = container_of(dwork, struct wl1271, tx_watchdog_work); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; /* Tx went out in the meantime - everything is ok */ if (unlikely(wl->tx_allocated_blocks == 0)) goto out; /* * if a ROC is in progress, we might not have any Tx for a long * time (e.g. pending Tx on the non-ROC channels) */ if (find_first_bit(wl->roc_map, WL12XX_MAX_ROLES) < WL12XX_MAX_ROLES) { wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms due to ROC", wl->conf.tx.tx_watchdog_timeout); wl12xx_rearm_tx_watchdog_locked(wl); goto out; } /* * if a scan is in progress, we might not have any Tx for a long * time */ if (wl->scan.state != WL1271_SCAN_STATE_IDLE) { wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms due to scan", wl->conf.tx.tx_watchdog_timeout); wl12xx_rearm_tx_watchdog_locked(wl); goto out; } /* * AP might cache a frame for a long time for a sleeping station, * so rearm the timer if there's an AP interface with stations. If * Tx is genuinely stuck we will most hopefully discover it when all * stations are removed due to inactivity. */ if (wl->active_sta_count) { wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms. AP has " " %d stations", wl->conf.tx.tx_watchdog_timeout, wl->active_sta_count); wl12xx_rearm_tx_watchdog_locked(wl); goto out; } wl1271_error("Tx stuck (in FW) for %d ms. Starting recovery", wl->conf.tx.tx_watchdog_timeout); wl12xx_queue_recovery_work(wl); out: mutex_unlock(&wl->mutex); } static void wl1271_conf_init(struct wl1271 *wl) { /* * This function applies the default configuration to the driver. This * function is invoked upon driver load (spi probe.) * * The configuration is stored in a run-time structure in order to * facilitate for run-time adjustment of any of the parameters. Making * changes to the configuration structure will apply the new values on * the next interface up (wl1271_op_start.) */ /* apply driver default configuration */ memcpy(&wl->conf, &default_conf, sizeof(default_conf)); /* Adjust settings according to optional module parameters */ if (fwlog_param) { if (!strcmp(fwlog_param, "continuous")) { wl->conf.fwlog.mode = WL12XX_FWLOG_CONTINUOUS; } else if (!strcmp(fwlog_param, "ondemand")) { wl->conf.fwlog.mode = WL12XX_FWLOG_ON_DEMAND; } else if (!strcmp(fwlog_param, "dbgpins")) { wl->conf.fwlog.mode = WL12XX_FWLOG_CONTINUOUS; wl->conf.fwlog.output = WL12XX_FWLOG_OUTPUT_DBG_PINS; } else if (!strcmp(fwlog_param, "disable")) { wl->conf.fwlog.mem_blocks = 0; wl->conf.fwlog.output = WL12XX_FWLOG_OUTPUT_NONE; } else { wl1271_error("Unknown fwlog parameter %s", fwlog_param); } } } static int wl1271_plt_init(struct wl1271 *wl) { int ret; if (wl->chip.id == CHIP_ID_1283_PG20) ret = wl128x_cmd_general_parms(wl); else ret = wl1271_cmd_general_parms(wl); if (ret < 0) return ret; if (wl->chip.id == CHIP_ID_1283_PG20) ret = wl128x_cmd_radio_parms(wl); else ret = wl1271_cmd_radio_parms(wl); if (ret < 0) return ret; if (wl->chip.id != CHIP_ID_1283_PG20) { ret = wl1271_cmd_ext_radio_parms(wl); if (ret < 0) return ret; } /* Chip-specific initializations */ ret = wl1271_chip_specific_init(wl); if (ret < 0) return ret; ret = wl1271_acx_init_mem_config(wl); if (ret < 0) return ret; ret = wl12xx_acx_mem_cfg(wl); if (ret < 0) goto out_free_memmap; /* Enable data path */ ret = wl1271_cmd_data_path(wl, 1); if (ret < 0) goto out_free_memmap; /* Configure for CAM power saving (ie. always active) */ ret = wl1271_acx_sleep_auth(wl, WL1271_PSM_CAM); if (ret < 0) goto out_free_memmap; /* configure PM */ ret = wl1271_acx_pm_config(wl); if (ret < 0) goto out_free_memmap; return 0; out_free_memmap: kfree(wl->target_mem_map); wl->target_mem_map = NULL; return ret; } static void wl12xx_irq_ps_regulate_link(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 hlid, u8 tx_pkts) { bool fw_ps, single_sta; fw_ps = test_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map); single_sta = (wl->active_sta_count == 1); /* * Wake up from high level PS if the STA is asleep with too little * packets in FW or if the STA is awake. */ if (!fw_ps || tx_pkts < WL1271_PS_STA_MAX_PACKETS) wl12xx_ps_link_end(wl, wlvif, hlid); /* * Start high-level PS if the STA is asleep with enough blocks in FW. * Make an exception if this is the only connected station. In this * case FW-memory congestion is not a problem. */ else if (!single_sta && fw_ps && tx_pkts >= WL1271_PS_STA_MAX_PACKETS) wl12xx_ps_link_start(wl, wlvif, hlid, true); } static void wl12xx_irq_update_links_status(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct wl12xx_fw_status *status) { struct wl1271_link *lnk; u32 cur_fw_ps_map; u8 hlid, cnt; /* TODO: also use link_fast_bitmap here */ cur_fw_ps_map = le32_to_cpu(status->link_ps_bitmap); if (wl->ap_fw_ps_map != cur_fw_ps_map) { wl1271_debug(DEBUG_PSM, "link ps prev 0x%x cur 0x%x changed 0x%x", wl->ap_fw_ps_map, cur_fw_ps_map, wl->ap_fw_ps_map ^ cur_fw_ps_map); wl->ap_fw_ps_map = cur_fw_ps_map; } for_each_set_bit(hlid, wlvif->ap.sta_hlid_map, WL12XX_MAX_LINKS) { lnk = &wl->links[hlid]; cnt = status->tx_lnk_free_pkts[hlid] - lnk->prev_freed_pkts; lnk->prev_freed_pkts = status->tx_lnk_free_pkts[hlid]; lnk->allocated_pkts -= cnt; wl12xx_irq_ps_regulate_link(wl, wlvif, hlid, lnk->allocated_pkts); } } static void wl12xx_fw_status(struct wl1271 *wl, struct wl12xx_fw_status *status) { struct wl12xx_vif *wlvif; struct timespec ts; u32 old_tx_blk_count = wl->tx_blocks_available; int avail, freed_blocks; int i; wl1271_raw_read(wl, FW_STATUS_ADDR, status, sizeof(*status), false); wl1271_debug(DEBUG_IRQ, "intr: 0x%x (fw_rx_counter = %d, " "drv_rx_counter = %d, tx_results_counter = %d)", status->intr, status->fw_rx_counter, status->drv_rx_counter, status->tx_results_counter); for (i = 0; i < NUM_TX_QUEUES; i++) { /* prevent wrap-around in freed-packets counter */ wl->tx_allocated_pkts[i] -= (status->tx_released_pkts[i] - wl->tx_pkts_freed[i]) & 0xff; wl->tx_pkts_freed[i] = status->tx_released_pkts[i]; } /* prevent wrap-around in total blocks counter */ if (likely(wl->tx_blocks_freed <= le32_to_cpu(status->total_released_blks))) freed_blocks = le32_to_cpu(status->total_released_blks) - wl->tx_blocks_freed; else freed_blocks = 0x100000000LL - wl->tx_blocks_freed + le32_to_cpu(status->total_released_blks); wl->tx_blocks_freed = le32_to_cpu(status->total_released_blks); wl->tx_allocated_blocks -= freed_blocks; /* * If the FW freed some blocks: * If we still have allocated blocks - re-arm the timer, Tx is * not stuck. Otherwise, cancel the timer (no Tx currently). */ if (freed_blocks) { if (wl->tx_allocated_blocks) wl12xx_rearm_tx_watchdog_locked(wl); else cancel_delayed_work(&wl->tx_watchdog_work); } avail = le32_to_cpu(status->tx_total) - wl->tx_allocated_blocks; /* * The FW might change the total number of TX memblocks before * we get a notification about blocks being released. Thus, the * available blocks calculation might yield a temporary result * which is lower than the actual available blocks. Keeping in * mind that only blocks that were allocated can be moved from * TX to RX, tx_blocks_available should never decrease here. */ wl->tx_blocks_available = max((int)wl->tx_blocks_available, avail); /* if more blocks are available now, tx work can be scheduled */ if (wl->tx_blocks_available > old_tx_blk_count) clear_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags); /* for AP update num of allocated TX blocks per link and ps status */ wl12xx_for_each_wlvif_ap(wl, wlvif) { wl12xx_irq_update_links_status(wl, wlvif, status); } /* update the host-chipset time offset */ getnstimeofday(&ts); wl->time_offset = (timespec_to_ns(&ts) >> 10) - (s64)le32_to_cpu(status->fw_localtime); } static void wl1271_flush_deferred_work(struct wl1271 *wl) { struct sk_buff *skb; /* Pass all received frames to the network stack */ while ((skb = skb_dequeue(&wl->deferred_rx_queue))) ieee80211_rx_ni(wl->hw, skb); /* Return sent skbs to the network stack */ while ((skb = skb_dequeue(&wl->deferred_tx_queue))) ieee80211_tx_status_ni(wl->hw, skb); } static void wl1271_netstack_work(struct work_struct *work) { struct wl1271 *wl = container_of(work, struct wl1271, netstack_work); do { wl1271_flush_deferred_work(wl); } while (skb_queue_len(&wl->deferred_rx_queue)); } #define WL1271_IRQ_MAX_LOOPS 256 static irqreturn_t wl1271_irq(int irq, void *cookie) { int ret; u32 intr; int loopcount = WL1271_IRQ_MAX_LOOPS; struct wl1271 *wl = (struct wl1271 *)cookie; bool done = false; unsigned int defer_count; unsigned long flags; /* TX might be handled here, avoid redundant work */ set_bit(WL1271_FLAG_TX_PENDING, &wl->flags); cancel_work_sync(&wl->tx_work); /* * In case edge triggered interrupt must be used, we cannot iterate * more than once without introducing race conditions with the hardirq. */ if (wl->platform_quirks & WL12XX_PLATFORM_QUIRK_EDGE_IRQ) loopcount = 1; mutex_lock(&wl->mutex); wl1271_debug(DEBUG_IRQ, "IRQ work"); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; while (!done && loopcount--) { /* * In order to avoid a race with the hardirq, clear the flag * before acknowledging the chip. Since the mutex is held, * wl1271_ps_elp_wakeup cannot be called concurrently. */ clear_bit(WL1271_FLAG_IRQ_RUNNING, &wl->flags); smp_mb__after_clear_bit(); wl12xx_fw_status(wl, wl->fw_status); intr = le32_to_cpu(wl->fw_status->intr); intr &= WL1271_INTR_MASK; if (!intr) { done = true; continue; } if (unlikely(intr & WL1271_ACX_INTR_WATCHDOG)) { wl1271_error("watchdog interrupt received! " "starting recovery."); wl12xx_queue_recovery_work(wl); /* restarting the chip. ignore any other interrupt. */ goto out; } if (likely(intr & WL1271_ACX_INTR_DATA)) { wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_DATA"); wl12xx_rx(wl, wl->fw_status); /* Check if any tx blocks were freed */ spin_lock_irqsave(&wl->wl_lock, flags); if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) && wl1271_tx_total_queue_count(wl) > 0) { spin_unlock_irqrestore(&wl->wl_lock, flags); /* * In order to avoid starvation of the TX path, * call the work function directly. */ wl1271_tx_work_locked(wl); } else { spin_unlock_irqrestore(&wl->wl_lock, flags); } /* check for tx results */ if (wl->fw_status->tx_results_counter != (wl->tx_results_count & 0xff)) wl1271_tx_complete(wl); /* Make sure the deferred queues don't get too long */ defer_count = skb_queue_len(&wl->deferred_tx_queue) + skb_queue_len(&wl->deferred_rx_queue); if (defer_count > WL1271_DEFERRED_QUEUE_LIMIT) wl1271_flush_deferred_work(wl); } if (intr & WL1271_ACX_INTR_EVENT_A) { wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_EVENT_A"); wl1271_event_handle(wl, 0); } if (intr & WL1271_ACX_INTR_EVENT_B) { wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_EVENT_B"); wl1271_event_handle(wl, 1); } if (intr & WL1271_ACX_INTR_INIT_COMPLETE) wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_INIT_COMPLETE"); if (intr & WL1271_ACX_INTR_HW_AVAILABLE) wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_HW_AVAILABLE"); } wl1271_ps_elp_sleep(wl); out: spin_lock_irqsave(&wl->wl_lock, flags); /* In case TX was not handled here, queue TX work */ clear_bit(WL1271_FLAG_TX_PENDING, &wl->flags); if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) && wl1271_tx_total_queue_count(wl) > 0) ieee80211_queue_work(wl->hw, &wl->tx_work); spin_unlock_irqrestore(&wl->wl_lock, flags); mutex_unlock(&wl->mutex); return IRQ_HANDLED; } struct vif_counter_data { u8 counter; struct ieee80211_vif *cur_vif; bool cur_vif_running; }; static void wl12xx_vif_count_iter(void *data, u8 *mac, struct ieee80211_vif *vif) { struct vif_counter_data *counter = data; counter->counter++; if (counter->cur_vif == vif) counter->cur_vif_running = true; } /* caller must not hold wl->mutex, as it might deadlock */ static void wl12xx_get_vif_count(struct ieee80211_hw *hw, struct ieee80211_vif *cur_vif, struct vif_counter_data *data) { memset(data, 0, sizeof(*data)); data->cur_vif = cur_vif; ieee80211_iterate_active_interfaces(hw, wl12xx_vif_count_iter, data); } static int wl12xx_fetch_firmware(struct wl1271 *wl, bool plt) { const struct firmware *fw; const char *fw_name; enum wl12xx_fw_type fw_type; int ret; if (plt) { fw_type = WL12XX_FW_TYPE_PLT; if (wl->chip.id == CHIP_ID_1283_PG20) fw_name = WL128X_PLT_FW_NAME; else fw_name = WL127X_PLT_FW_NAME; } else { /* * we can't call wl12xx_get_vif_count() here because * wl->mutex is taken, so use the cached last_vif_count value */ if (wl->last_vif_count > 1) { fw_type = WL12XX_FW_TYPE_MULTI; if (wl->chip.id == CHIP_ID_1283_PG20) fw_name = WL128X_FW_NAME_MULTI; else fw_name = WL127X_FW_NAME_MULTI; } else { fw_type = WL12XX_FW_TYPE_NORMAL; if (wl->chip.id == CHIP_ID_1283_PG20) fw_name = WL128X_FW_NAME_SINGLE; else fw_name = WL127X_FW_NAME_SINGLE; } } if (wl->fw_type == fw_type) return 0; wl1271_debug(DEBUG_BOOT, "booting firmware %s", fw_name); ret = request_firmware(&fw, fw_name, wl->dev); if (ret < 0) { wl1271_error("could not get firmware %s: %d", fw_name, ret); return ret; } if (fw->size % 4) { wl1271_error("firmware size is not multiple of 32 bits: %zu", fw->size); ret = -EILSEQ; goto out; } vfree(wl->fw); wl->fw_type = WL12XX_FW_TYPE_NONE; wl->fw_len = fw->size; wl->fw = vmalloc(wl->fw_len); if (!wl->fw) { wl1271_error("could not allocate memory for the firmware"); ret = -ENOMEM; goto out; } memcpy(wl->fw, fw->data, wl->fw_len); ret = 0; wl->fw_type = fw_type; out: release_firmware(fw); return ret; } static int wl1271_fetch_nvs(struct wl1271 *wl) { const struct firmware *fw; int ret; ret = request_firmware(&fw, WL12XX_NVS_NAME, wl->dev); if (ret < 0) { wl1271_error("could not get nvs file %s: %d", WL12XX_NVS_NAME, ret); return ret; } wl->nvs = kmemdup(fw->data, fw->size, GFP_KERNEL); if (!wl->nvs) { wl1271_error("could not allocate memory for the nvs file"); ret = -ENOMEM; goto out; } wl->nvs_len = fw->size; out: release_firmware(fw); return ret; } void wl12xx_queue_recovery_work(struct wl1271 *wl) { if (!test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags)) ieee80211_queue_work(wl->hw, &wl->recovery_work); } size_t wl12xx_copy_fwlog(struct wl1271 *wl, u8 *memblock, size_t maxlen) { size_t len = 0; /* The FW log is a length-value list, find where the log end */ while (len < maxlen) { if (memblock[len] == 0) break; if (len + memblock[len] + 1 > maxlen) break; len += memblock[len] + 1; } /* Make sure we have enough room */ len = min(len, (size_t)(PAGE_SIZE - wl->fwlog_size)); /* Fill the FW log file, consumed by the sysfs fwlog entry */ memcpy(wl->fwlog + wl->fwlog_size, memblock, len); wl->fwlog_size += len; return len; } static void wl12xx_read_fwlog_panic(struct wl1271 *wl) { u32 addr; u32 first_addr; u8 *block; if ((wl->quirks & WL12XX_QUIRK_FWLOG_NOT_IMPLEMENTED) || (wl->conf.fwlog.mode != WL12XX_FWLOG_ON_DEMAND) || (wl->conf.fwlog.mem_blocks == 0)) return; wl1271_info("Reading FW panic log"); block = kmalloc(WL12XX_HW_BLOCK_SIZE, GFP_KERNEL); if (!block) return; /* * Make sure the chip is awake and the logger isn't active. * This might fail if the firmware hanged. */ if (!wl1271_ps_elp_wakeup(wl)) wl12xx_cmd_stop_fwlog(wl); /* Read the first memory block address */ wl12xx_fw_status(wl, wl->fw_status); first_addr = le32_to_cpu(wl->fw_status->log_start_addr); if (!first_addr) goto out; /* Traverse the memory blocks linked list */ addr = first_addr; do { memset(block, 0, WL12XX_HW_BLOCK_SIZE); wl1271_read_hwaddr(wl, addr, block, WL12XX_HW_BLOCK_SIZE, false); /* * Memory blocks are linked to one another. The first 4 bytes * of each memory block hold the hardware address of the next * one. The last memory block points to the first one. */ addr = le32_to_cpup((__le32 *)block); if (!wl12xx_copy_fwlog(wl, block + sizeof(addr), WL12XX_HW_BLOCK_SIZE - sizeof(addr))) break; } while (addr && (addr != first_addr)); wake_up_interruptible(&wl->fwlog_waitq); out: kfree(block); } static void wl1271_recovery_work(struct work_struct *work) { struct wl1271 *wl = container_of(work, struct wl1271, recovery_work); struct wl12xx_vif *wlvif; struct ieee80211_vif *vif; mutex_lock(&wl->mutex); if (wl->state != WL1271_STATE_ON || wl->plt) goto out_unlock; /* Avoid a recursive recovery */ set_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags); wl12xx_read_fwlog_panic(wl); wl1271_info("Hardware recovery in progress. FW ver: %s pc: 0x%x", wl->chip.fw_ver_str, wl1271_read32(wl, SCR_PAD4)); BUG_ON(bug_on_recovery && !test_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags)); /* * Advance security sequence number to overcome potential progress * in the firmware during recovery. This doens't hurt if the network is * not encrypted. */ wl12xx_for_each_wlvif(wl, wlvif) { if (test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) || test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) wlvif->tx_security_seq += WL1271_TX_SQN_POST_RECOVERY_PADDING; } /* Prevent spurious TX during FW restart */ ieee80211_stop_queues(wl->hw); if (wl->sched_scanning) { ieee80211_sched_scan_stopped(wl->hw); wl->sched_scanning = false; } /* reboot the chipset */ while (!list_empty(&wl->wlvif_list)) { wlvif = list_first_entry(&wl->wlvif_list, struct wl12xx_vif, list); vif = wl12xx_wlvif_to_vif(wlvif); __wl1271_op_remove_interface(wl, vif, false); } mutex_unlock(&wl->mutex); wl1271_op_stop(wl->hw); clear_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags); ieee80211_restart_hw(wl->hw); /* * Its safe to enable TX now - the queues are stopped after a request * to restart the HW. */ ieee80211_wake_queues(wl->hw); return; out_unlock: mutex_unlock(&wl->mutex); } static void wl1271_fw_wakeup(struct wl1271 *wl) { u32 elp_reg; elp_reg = ELPCTRL_WAKE_UP; wl1271_raw_write32(wl, HW_ACCESS_ELP_CTRL_REG_ADDR, elp_reg); } static int wl1271_setup(struct wl1271 *wl) { wl->fw_status = kmalloc(sizeof(*wl->fw_status), GFP_KERNEL); if (!wl->fw_status) return -ENOMEM; wl->tx_res_if = kmalloc(sizeof(*wl->tx_res_if), GFP_KERNEL); if (!wl->tx_res_if) { kfree(wl->fw_status); return -ENOMEM; } return 0; } static int wl12xx_set_power_on(struct wl1271 *wl) { int ret; msleep(WL1271_PRE_POWER_ON_SLEEP); ret = wl1271_power_on(wl); if (ret < 0) goto out; msleep(WL1271_POWER_ON_SLEEP); wl1271_io_reset(wl); wl1271_io_init(wl); wl1271_set_partition(wl, &wl12xx_part_table[PART_DOWN]); /* ELP module wake up */ wl1271_fw_wakeup(wl); out: return ret; } static int wl12xx_chip_wakeup(struct wl1271 *wl, bool plt) { int ret = 0; ret = wl12xx_set_power_on(wl); if (ret < 0) goto out; /* * For wl127x based devices we could use the default block * size (512 bytes), but due to a bug in the sdio driver, we * need to set it explicitly after the chip is powered on. To * simplify the code and since the performance impact is * negligible, we use the same block size for all different * chip types. */ if (!wl1271_set_block_size(wl)) wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT; switch (wl->chip.id) { case CHIP_ID_1271_PG10: wl1271_warning("chip id 0x%x (1271 PG10) support is obsolete", wl->chip.id); ret = wl1271_setup(wl); if (ret < 0) goto out; wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT; break; case CHIP_ID_1271_PG20: wl1271_debug(DEBUG_BOOT, "chip id 0x%x (1271 PG20)", wl->chip.id); ret = wl1271_setup(wl); if (ret < 0) goto out; wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT; break; case CHIP_ID_1283_PG20: wl1271_debug(DEBUG_BOOT, "chip id 0x%x (1283 PG20)", wl->chip.id); ret = wl1271_setup(wl); if (ret < 0) goto out; break; case CHIP_ID_1283_PG10: default: wl1271_warning("unsupported chip id: 0x%x", wl->chip.id); ret = -ENODEV; goto out; } ret = wl12xx_fetch_firmware(wl, plt); if (ret < 0) goto out; /* No NVS from netlink, try to get it from the filesystem */ if (wl->nvs == NULL) { ret = wl1271_fetch_nvs(wl); if (ret < 0) goto out; } out: return ret; } int wl1271_plt_start(struct wl1271 *wl) { int retries = WL1271_BOOT_RETRIES; struct wiphy *wiphy = wl->hw->wiphy; int ret; mutex_lock(&wl->mutex); wl1271_notice("power up"); if (wl->state != WL1271_STATE_OFF) { wl1271_error("cannot go into PLT state because not " "in off state: %d", wl->state); ret = -EBUSY; goto out; } while (retries) { retries--; ret = wl12xx_chip_wakeup(wl, true); if (ret < 0) goto power_off; ret = wl1271_boot(wl); if (ret < 0) goto power_off; ret = wl1271_plt_init(wl); if (ret < 0) goto irq_disable; wl->plt = true; wl->state = WL1271_STATE_ON; wl1271_notice("firmware booted in PLT mode (%s)", wl->chip.fw_ver_str); /* update hw/fw version info in wiphy struct */ wiphy->hw_version = wl->chip.id; strncpy(wiphy->fw_version, wl->chip.fw_ver_str, sizeof(wiphy->fw_version)); goto out; irq_disable: mutex_unlock(&wl->mutex); /* Unlocking the mutex in the middle of handling is inherently unsafe. In this case we deem it safe to do, because we need to let any possibly pending IRQ out of the system (and while we are WL1271_STATE_OFF the IRQ work function will not do anything.) Also, any other possible concurrent operations will fail due to the current state, hence the wl1271 struct should be safe. */ wl1271_disable_interrupts(wl); wl1271_flush_deferred_work(wl); cancel_work_sync(&wl->netstack_work); mutex_lock(&wl->mutex); power_off: wl1271_power_off(wl); } wl1271_error("firmware boot in PLT mode failed despite %d retries", WL1271_BOOT_RETRIES); out: mutex_unlock(&wl->mutex); return ret; } int wl1271_plt_stop(struct wl1271 *wl) { int ret = 0; wl1271_notice("power down"); /* * Interrupts must be disabled before setting the state to OFF. * Otherwise, the interrupt handler might be called and exit without * reading the interrupt status. */ wl1271_disable_interrupts(wl); mutex_lock(&wl->mutex); if (!wl->plt) { mutex_unlock(&wl->mutex); /* * This will not necessarily enable interrupts as interrupts * may have been disabled when op_stop was called. It will, * however, balance the above call to disable_interrupts(). */ wl1271_enable_interrupts(wl); wl1271_error("cannot power down because not in PLT " "state: %d", wl->state); ret = -EBUSY; goto out; } mutex_unlock(&wl->mutex); wl1271_flush_deferred_work(wl); cancel_work_sync(&wl->netstack_work); cancel_work_sync(&wl->recovery_work); cancel_delayed_work_sync(&wl->elp_work); cancel_delayed_work_sync(&wl->tx_watchdog_work); mutex_lock(&wl->mutex); wl1271_power_off(wl); wl->flags = 0; wl->state = WL1271_STATE_OFF; wl->plt = false; wl->rx_counter = 0; mutex_unlock(&wl->mutex); out: return ret; } static void wl1271_op_tx(struct ieee80211_hw *hw, struct sk_buff *skb) { struct wl1271 *wl = hw->priv; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_vif *vif = info->control.vif; struct wl12xx_vif *wlvif = NULL; unsigned long flags; int q, mapping; u8 hlid; if (vif) wlvif = wl12xx_vif_to_data(vif); mapping = skb_get_queue_mapping(skb); q = wl1271_tx_get_queue(mapping); hlid = wl12xx_tx_get_hlid(wl, wlvif, skb); spin_lock_irqsave(&wl->wl_lock, flags); /* queue the packet */ if (hlid == WL12XX_INVALID_LINK_ID || (wlvif && !test_bit(hlid, wlvif->links_map))) { wl1271_debug(DEBUG_TX, "DROP skb hlid %d q %d", hlid, q); ieee80211_free_txskb(hw, skb); goto out; } wl1271_debug(DEBUG_TX, "queue skb hlid %d q %d len %d", hlid, q, skb->len); skb_queue_tail(&wl->links[hlid].tx_queue[q], skb); wl->tx_queue_count[q]++; /* * The workqueue is slow to process the tx_queue and we need stop * the queue here, otherwise the queue will get too long. */ if (wl->tx_queue_count[q] >= WL1271_TX_QUEUE_HIGH_WATERMARK) { wl1271_debug(DEBUG_TX, "op_tx: stopping queues for q %d", q); ieee80211_stop_queue(wl->hw, mapping); set_bit(q, &wl->stopped_queues_map); } /* * The chip specific setup must run before the first TX packet - * before that, the tx_work will not be initialized! */ if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) && !test_bit(WL1271_FLAG_TX_PENDING, &wl->flags)) ieee80211_queue_work(wl->hw, &wl->tx_work); out: spin_unlock_irqrestore(&wl->wl_lock, flags); } int wl1271_tx_dummy_packet(struct wl1271 *wl) { unsigned long flags; int q; /* no need to queue a new dummy packet if one is already pending */ if (test_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags)) return 0; q = wl1271_tx_get_queue(skb_get_queue_mapping(wl->dummy_packet)); spin_lock_irqsave(&wl->wl_lock, flags); set_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags); wl->tx_queue_count[q]++; spin_unlock_irqrestore(&wl->wl_lock, flags); /* The FW is low on RX memory blocks, so send the dummy packet asap */ if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags)) wl1271_tx_work_locked(wl); /* * If the FW TX is busy, TX work will be scheduled by the threaded * interrupt handler function */ return 0; } /* * The size of the dummy packet should be at least 1400 bytes. However, in * order to minimize the number of bus transactions, aligning it to 512 bytes * boundaries could be beneficial, performance wise */ #define TOTAL_TX_DUMMY_PACKET_SIZE (ALIGN(1400, 512)) static struct sk_buff *wl12xx_alloc_dummy_packet(struct wl1271 *wl) { struct sk_buff *skb; struct ieee80211_hdr_3addr *hdr; unsigned int dummy_packet_size; dummy_packet_size = TOTAL_TX_DUMMY_PACKET_SIZE - sizeof(struct wl1271_tx_hw_descr) - sizeof(*hdr); skb = dev_alloc_skb(TOTAL_TX_DUMMY_PACKET_SIZE); if (!skb) { wl1271_warning("Failed to allocate a dummy packet skb"); return NULL; } skb_reserve(skb, sizeof(struct wl1271_tx_hw_descr)); hdr = (struct ieee80211_hdr_3addr *) skb_put(skb, sizeof(*hdr)); memset(hdr, 0, sizeof(*hdr)); hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS); memset(skb_put(skb, dummy_packet_size), 0, dummy_packet_size); /* Dummy packets require the TID to be management */ skb->priority = WL1271_TID_MGMT; /* Initialize all fields that might be used */ skb_set_queue_mapping(skb, 0); memset(IEEE80211_SKB_CB(skb), 0, sizeof(struct ieee80211_tx_info)); return skb; } #ifdef CONFIG_PM static int wl1271_configure_suspend_sta(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret = 0; mutex_lock(&wl->mutex); if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) goto out_unlock; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out_unlock; ret = wl1271_acx_wake_up_conditions(wl, wlvif, wl->conf.conn.suspend_wake_up_event, wl->conf.conn.suspend_listen_interval); if (ret < 0) wl1271_error("suspend: set wake up conditions failed: %d", ret); wl1271_ps_elp_sleep(wl); out_unlock: mutex_unlock(&wl->mutex); return ret; } static int wl1271_configure_suspend_ap(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret = 0; mutex_lock(&wl->mutex); if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) goto out_unlock; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out_unlock; ret = wl1271_acx_beacon_filter_opt(wl, wlvif, true); wl1271_ps_elp_sleep(wl); out_unlock: mutex_unlock(&wl->mutex); return ret; } static int wl1271_configure_suspend(struct wl1271 *wl, struct wl12xx_vif *wlvif) { if (wlvif->bss_type == BSS_TYPE_STA_BSS) return wl1271_configure_suspend_sta(wl, wlvif); if (wlvif->bss_type == BSS_TYPE_AP_BSS) return wl1271_configure_suspend_ap(wl, wlvif); return 0; } static void wl1271_configure_resume(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret = 0; bool is_ap = wlvif->bss_type == BSS_TYPE_AP_BSS; bool is_sta = wlvif->bss_type == BSS_TYPE_STA_BSS; if ((!is_ap) && (!is_sta)) return; mutex_lock(&wl->mutex); ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; if (is_sta) { ret = wl1271_acx_wake_up_conditions(wl, wlvif, wl->conf.conn.wake_up_event, wl->conf.conn.listen_interval); if (ret < 0) wl1271_error("resume: wake up conditions failed: %d", ret); } else if (is_ap) { ret = wl1271_acx_beacon_filter_opt(wl, wlvif, false); } wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static int wl1271_op_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wow) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 suspend wow=%d", !!wow); WARN_ON(!wow || !wow->any); wl1271_tx_flush(wl); wl->wow_enabled = true; wl12xx_for_each_wlvif(wl, wlvif) { ret = wl1271_configure_suspend(wl, wlvif); if (ret < 0) { wl1271_warning("couldn't prepare device to suspend"); return ret; } } /* flush any remaining work */ wl1271_debug(DEBUG_MAC80211, "flushing remaining works"); /* * disable and re-enable interrupts in order to flush * the threaded_irq */ wl1271_disable_interrupts(wl); /* * set suspended flag to avoid triggering a new threaded_irq * work. no need for spinlock as interrupts are disabled. */ set_bit(WL1271_FLAG_SUSPENDED, &wl->flags); wl1271_enable_interrupts(wl); flush_work(&wl->tx_work); flush_delayed_work(&wl->elp_work); return 0; } static int wl1271_op_resume(struct ieee80211_hw *hw) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; unsigned long flags; bool run_irq_work = false; wl1271_debug(DEBUG_MAC80211, "mac80211 resume wow=%d", wl->wow_enabled); WARN_ON(!wl->wow_enabled); /* * re-enable irq_work enqueuing, and call irq_work directly if * there is a pending work. */ spin_lock_irqsave(&wl->wl_lock, flags); clear_bit(WL1271_FLAG_SUSPENDED, &wl->flags); if (test_and_clear_bit(WL1271_FLAG_PENDING_WORK, &wl->flags)) run_irq_work = true; spin_unlock_irqrestore(&wl->wl_lock, flags); if (run_irq_work) { wl1271_debug(DEBUG_MAC80211, "run postponed irq_work directly"); wl1271_irq(0, wl); wl1271_enable_interrupts(wl); } wl12xx_for_each_wlvif(wl, wlvif) { wl1271_configure_resume(wl, wlvif); } wl->wow_enabled = false; return 0; } #endif static int wl1271_op_start(struct ieee80211_hw *hw) { wl1271_debug(DEBUG_MAC80211, "mac80211 start"); /* * We have to delay the booting of the hardware because * we need to know the local MAC address before downloading and * initializing the firmware. The MAC address cannot be changed * after boot, and without the proper MAC address, the firmware * will not function properly. * * The MAC address is first known when the corresponding interface * is added. That is where we will initialize the hardware. */ return 0; } static void wl1271_op_stop(struct ieee80211_hw *hw) { struct wl1271 *wl = hw->priv; int i; wl1271_debug(DEBUG_MAC80211, "mac80211 stop"); /* * Interrupts must be disabled before setting the state to OFF. * Otherwise, the interrupt handler might be called and exit without * reading the interrupt status. */ wl1271_disable_interrupts(wl); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) { mutex_unlock(&wl->mutex); /* * This will not necessarily enable interrupts as interrupts * may have been disabled when op_stop was called. It will, * however, balance the above call to disable_interrupts(). */ wl1271_enable_interrupts(wl); return; } /* * this must be before the cancel_work calls below, so that the work * functions don't perform further work. */ wl->state = WL1271_STATE_OFF; mutex_unlock(&wl->mutex); wl1271_flush_deferred_work(wl); cancel_delayed_work_sync(&wl->scan_complete_work); cancel_work_sync(&wl->netstack_work); cancel_work_sync(&wl->tx_work); cancel_delayed_work_sync(&wl->elp_work); cancel_delayed_work_sync(&wl->tx_watchdog_work); /* let's notify MAC80211 about the remaining pending TX frames */ wl12xx_tx_reset(wl, true); mutex_lock(&wl->mutex); wl1271_power_off(wl); wl->band = IEEE80211_BAND_2GHZ; wl->rx_counter = 0; wl->power_level = WL1271_DEFAULT_POWER_LEVEL; wl->tx_blocks_available = 0; wl->tx_allocated_blocks = 0; wl->tx_results_count = 0; wl->tx_packets_count = 0; wl->time_offset = 0; wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT; wl->ap_fw_ps_map = 0; wl->ap_ps_map = 0; wl->sched_scanning = false; memset(wl->roles_map, 0, sizeof(wl->roles_map)); memset(wl->links_map, 0, sizeof(wl->links_map)); memset(wl->roc_map, 0, sizeof(wl->roc_map)); wl->active_sta_count = 0; /* The system link is always allocated */ __set_bit(WL12XX_SYSTEM_HLID, wl->links_map); /* * this is performed after the cancel_work calls and the associated * mutex_lock, so that wl1271_op_add_interface does not accidentally * get executed before all these vars have been reset. */ wl->flags = 0; wl->tx_blocks_freed = 0; for (i = 0; i < NUM_TX_QUEUES; i++) { wl->tx_pkts_freed[i] = 0; wl->tx_allocated_pkts[i] = 0; } wl1271_debugfs_reset(wl); kfree(wl->fw_status); wl->fw_status = NULL; kfree(wl->tx_res_if); wl->tx_res_if = NULL; kfree(wl->target_mem_map); wl->target_mem_map = NULL; mutex_unlock(&wl->mutex); } static int wl12xx_allocate_rate_policy(struct wl1271 *wl, u8 *idx) { u8 policy = find_first_zero_bit(wl->rate_policies_map, WL12XX_MAX_RATE_POLICIES); if (policy >= WL12XX_MAX_RATE_POLICIES) return -EBUSY; __set_bit(policy, wl->rate_policies_map); *idx = policy; return 0; } static void wl12xx_free_rate_policy(struct wl1271 *wl, u8 *idx) { if (WARN_ON(*idx >= WL12XX_MAX_RATE_POLICIES)) return; __clear_bit(*idx, wl->rate_policies_map); *idx = WL12XX_MAX_RATE_POLICIES; } static u8 wl12xx_get_role_type(struct wl1271 *wl, struct wl12xx_vif *wlvif) { switch (wlvif->bss_type) { case BSS_TYPE_AP_BSS: if (wlvif->p2p) return WL1271_ROLE_P2P_GO; else return WL1271_ROLE_AP; case BSS_TYPE_STA_BSS: if (wlvif->p2p) return WL1271_ROLE_P2P_CL; else return WL1271_ROLE_STA; case BSS_TYPE_IBSS: return WL1271_ROLE_IBSS; default: wl1271_error("invalid bss_type: %d", wlvif->bss_type); } return WL12XX_INVALID_ROLE_TYPE; } static int wl12xx_init_vif_data(struct wl1271 *wl, struct ieee80211_vif *vif) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int i; /* clear everything but the persistent data */ memset(wlvif, 0, offsetof(struct wl12xx_vif, persistent)); switch (ieee80211_vif_type_p2p(vif)) { case NL80211_IFTYPE_P2P_CLIENT: wlvif->p2p = 1; /* fall-through */ case NL80211_IFTYPE_STATION: wlvif->bss_type = BSS_TYPE_STA_BSS; break; case NL80211_IFTYPE_ADHOC: wlvif->bss_type = BSS_TYPE_IBSS; break; case NL80211_IFTYPE_P2P_GO: wlvif->p2p = 1; /* fall-through */ case NL80211_IFTYPE_AP: wlvif->bss_type = BSS_TYPE_AP_BSS; break; default: wlvif->bss_type = MAX_BSS_TYPE; return -EOPNOTSUPP; } wlvif->role_id = WL12XX_INVALID_ROLE_ID; wlvif->dev_role_id = WL12XX_INVALID_ROLE_ID; wlvif->dev_hlid = WL12XX_INVALID_LINK_ID; if (wlvif->bss_type == BSS_TYPE_STA_BSS || wlvif->bss_type == BSS_TYPE_IBSS) { /* init sta/ibss data */ wlvif->sta.hlid = WL12XX_INVALID_LINK_ID; wl12xx_allocate_rate_policy(wl, &wlvif->sta.basic_rate_idx); wl12xx_allocate_rate_policy(wl, &wlvif->sta.ap_rate_idx); wl12xx_allocate_rate_policy(wl, &wlvif->sta.p2p_rate_idx); } else { /* init ap data */ wlvif->ap.bcast_hlid = WL12XX_INVALID_LINK_ID; wlvif->ap.global_hlid = WL12XX_INVALID_LINK_ID; wl12xx_allocate_rate_policy(wl, &wlvif->ap.mgmt_rate_idx); wl12xx_allocate_rate_policy(wl, &wlvif->ap.bcast_rate_idx); for (i = 0; i < CONF_TX_MAX_AC_COUNT; i++) wl12xx_allocate_rate_policy(wl, &wlvif->ap.ucast_rate_idx[i]); } wlvif->bitrate_masks[IEEE80211_BAND_2GHZ] = wl->conf.tx.basic_rate; wlvif->bitrate_masks[IEEE80211_BAND_5GHZ] = wl->conf.tx.basic_rate_5; wlvif->basic_rate_set = CONF_TX_RATE_MASK_BASIC; wlvif->basic_rate = CONF_TX_RATE_MASK_BASIC; wlvif->rate_set = CONF_TX_RATE_MASK_BASIC; wlvif->beacon_int = WL1271_DEFAULT_BEACON_INT; /* * mac80211 configures some values globally, while we treat them * per-interface. thus, on init, we have to copy them from wl */ wlvif->band = wl->band; wlvif->channel = wl->channel; wlvif->power_level = wl->power_level; INIT_WORK(&wlvif->rx_streaming_enable_work, wl1271_rx_streaming_enable_work); INIT_WORK(&wlvif->rx_streaming_disable_work, wl1271_rx_streaming_disable_work); INIT_LIST_HEAD(&wlvif->list); setup_timer(&wlvif->rx_streaming_timer, wl1271_rx_streaming_timer, (unsigned long) wlvif); return 0; } static bool wl12xx_init_fw(struct wl1271 *wl) { int retries = WL1271_BOOT_RETRIES; bool booted = false; struct wiphy *wiphy = wl->hw->wiphy; int ret; while (retries) { retries--; ret = wl12xx_chip_wakeup(wl, false); if (ret < 0) goto power_off; ret = wl1271_boot(wl); if (ret < 0) goto power_off; ret = wl1271_hw_init(wl); if (ret < 0) goto irq_disable; booted = true; break; irq_disable: mutex_unlock(&wl->mutex); /* Unlocking the mutex in the middle of handling is inherently unsafe. In this case we deem it safe to do, because we need to let any possibly pending IRQ out of the system (and while we are WL1271_STATE_OFF the IRQ work function will not do anything.) Also, any other possible concurrent operations will fail due to the current state, hence the wl1271 struct should be safe. */ wl1271_disable_interrupts(wl); wl1271_flush_deferred_work(wl); cancel_work_sync(&wl->netstack_work); mutex_lock(&wl->mutex); power_off: wl1271_power_off(wl); } if (!booted) { wl1271_error("firmware boot failed despite %d retries", WL1271_BOOT_RETRIES); goto out; } wl1271_info("firmware booted (%s)", wl->chip.fw_ver_str); /* update hw/fw version info in wiphy struct */ wiphy->hw_version = wl->chip.id; strncpy(wiphy->fw_version, wl->chip.fw_ver_str, sizeof(wiphy->fw_version)); /* * Now we know if 11a is supported (info from the NVS), so disable * 11a channels if not supported */ if (!wl->enable_11a) wiphy->bands[IEEE80211_BAND_5GHZ]->n_channels = 0; wl1271_debug(DEBUG_MAC80211, "11a is %ssupported", wl->enable_11a ? "" : "not "); wl->state = WL1271_STATE_ON; out: return booted; } static bool wl12xx_dev_role_started(struct wl12xx_vif *wlvif) { return wlvif->dev_hlid != WL12XX_INVALID_LINK_ID; } /* * Check whether a fw switch (i.e. moving from one loaded * fw to another) is needed. This function is also responsible * for updating wl->last_vif_count, so it must be called before * loading a non-plt fw (so the correct fw (single-role/multi-role) * will be used). */ static bool wl12xx_need_fw_change(struct wl1271 *wl, struct vif_counter_data vif_counter_data, bool add) { enum wl12xx_fw_type current_fw = wl->fw_type; u8 vif_count = vif_counter_data.counter; if (test_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags)) return false; /* increase the vif count if this is a new vif */ if (add && !vif_counter_data.cur_vif_running) vif_count++; wl->last_vif_count = vif_count; /* no need for fw change if the device is OFF */ if (wl->state == WL1271_STATE_OFF) return false; if (vif_count > 1 && current_fw == WL12XX_FW_TYPE_NORMAL) return true; if (vif_count <= 1 && current_fw == WL12XX_FW_TYPE_MULTI) return true; return false; } /* * Enter "forced psm". Make sure the sta is in psm against the ap, * to make the fw switch a bit more disconnection-persistent. */ static void wl12xx_force_active_psm(struct wl1271 *wl) { struct wl12xx_vif *wlvif; wl12xx_for_each_wlvif_sta(wl, wlvif) { wl1271_ps_set_mode(wl, wlvif, STATION_POWER_SAVE_MODE); } } static int wl1271_op_add_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct vif_counter_data vif_count; int ret = 0; u8 role_type; bool booted = false; vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER | IEEE80211_VIF_SUPPORTS_CQM_RSSI; wl1271_debug(DEBUG_MAC80211, "mac80211 add interface type %d mac %pM", ieee80211_vif_type_p2p(vif), vif->addr); wl12xx_get_vif_count(hw, vif, &vif_count); mutex_lock(&wl->mutex); ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out_unlock; /* * in some very corner case HW recovery scenarios its possible to * get here before __wl1271_op_remove_interface is complete, so * opt out if that is the case. */ if (test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags) || test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) { ret = -EBUSY; goto out; } ret = wl12xx_init_vif_data(wl, vif); if (ret < 0) goto out; wlvif->wl = wl; role_type = wl12xx_get_role_type(wl, wlvif); if (role_type == WL12XX_INVALID_ROLE_TYPE) { ret = -EINVAL; goto out; } if (wl12xx_need_fw_change(wl, vif_count, true)) { wl12xx_force_active_psm(wl); set_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags); mutex_unlock(&wl->mutex); wl1271_recovery_work(&wl->recovery_work); return 0; } /* * TODO: after the nvs issue will be solved, move this block * to start(), and make sure here the driver is ON. */ if (wl->state == WL1271_STATE_OFF) { /* * we still need this in order to configure the fw * while uploading the nvs */ memcpy(wl->addresses[0].addr, vif->addr, ETH_ALEN); booted = wl12xx_init_fw(wl); if (!booted) { ret = -EINVAL; goto out; } } if (wlvif->bss_type == BSS_TYPE_STA_BSS || wlvif->bss_type == BSS_TYPE_IBSS) { /* * The device role is a special role used for * rx and tx frames prior to association (as * the STA role can get packets only from * its associated bssid) */ ret = wl12xx_cmd_role_enable(wl, vif->addr, WL1271_ROLE_DEVICE, &wlvif->dev_role_id); if (ret < 0) goto out; } ret = wl12xx_cmd_role_enable(wl, vif->addr, role_type, &wlvif->role_id); if (ret < 0) goto out; ret = wl1271_init_vif_specific(wl, vif); if (ret < 0) goto out; list_add(&wlvif->list, &wl->wlvif_list); set_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags); if (wlvif->bss_type == BSS_TYPE_AP_BSS) wl->ap_count++; else wl->sta_count++; out: wl1271_ps_elp_sleep(wl); out_unlock: mutex_unlock(&wl->mutex); return ret; } static void __wl1271_op_remove_interface(struct wl1271 *wl, struct ieee80211_vif *vif, bool reset_tx_queues) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int i, ret; wl1271_debug(DEBUG_MAC80211, "mac80211 remove interface"); if (!test_and_clear_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) return; /* because of hardware recovery, we may get here twice */ if (wl->state != WL1271_STATE_ON) return; wl1271_info("down"); if (wl->scan.state != WL1271_SCAN_STATE_IDLE && wl->scan_vif == vif) { /* * Rearm the tx watchdog just before idling scan. This * prevents just-finished scans from triggering the watchdog */ wl12xx_rearm_tx_watchdog_locked(wl); wl->scan.state = WL1271_SCAN_STATE_IDLE; memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch)); wl->scan_vif = NULL; wl->scan.req = NULL; ieee80211_scan_completed(wl->hw, true); } if (!test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags)) { /* disable active roles */ ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto deinit; if (wlvif->bss_type == BSS_TYPE_STA_BSS || wlvif->bss_type == BSS_TYPE_IBSS) { if (wl12xx_dev_role_started(wlvif)) wl12xx_stop_dev(wl, wlvif); ret = wl12xx_cmd_role_disable(wl, &wlvif->dev_role_id); if (ret < 0) goto deinit; } ret = wl12xx_cmd_role_disable(wl, &wlvif->role_id); if (ret < 0) goto deinit; wl1271_ps_elp_sleep(wl); } deinit: /* clear all hlids (except system_hlid) */ wlvif->dev_hlid = WL12XX_INVALID_LINK_ID; if (wlvif->bss_type == BSS_TYPE_STA_BSS || wlvif->bss_type == BSS_TYPE_IBSS) { wlvif->sta.hlid = WL12XX_INVALID_LINK_ID; wl12xx_free_rate_policy(wl, &wlvif->sta.basic_rate_idx); wl12xx_free_rate_policy(wl, &wlvif->sta.ap_rate_idx); wl12xx_free_rate_policy(wl, &wlvif->sta.p2p_rate_idx); } else { wlvif->ap.bcast_hlid = WL12XX_INVALID_LINK_ID; wlvif->ap.global_hlid = WL12XX_INVALID_LINK_ID; wl12xx_free_rate_policy(wl, &wlvif->ap.mgmt_rate_idx); wl12xx_free_rate_policy(wl, &wlvif->ap.bcast_rate_idx); for (i = 0; i < CONF_TX_MAX_AC_COUNT; i++) wl12xx_free_rate_policy(wl, &wlvif->ap.ucast_rate_idx[i]); } wl12xx_tx_reset_wlvif(wl, wlvif); wl1271_free_ap_keys(wl, wlvif); if (wl->last_wlvif == wlvif) wl->last_wlvif = NULL; list_del(&wlvif->list); memset(wlvif->ap.sta_hlid_map, 0, sizeof(wlvif->ap.sta_hlid_map)); wlvif->role_id = WL12XX_INVALID_ROLE_ID; wlvif->dev_role_id = WL12XX_INVALID_ROLE_ID; if (wlvif->bss_type == BSS_TYPE_AP_BSS) wl->ap_count--; else wl->sta_count--; mutex_unlock(&wl->mutex); del_timer_sync(&wlvif->rx_streaming_timer); cancel_work_sync(&wlvif->rx_streaming_enable_work); cancel_work_sync(&wlvif->rx_streaming_disable_work); mutex_lock(&wl->mutex); } static void wl1271_op_remove_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct wl12xx_vif *iter; struct vif_counter_data vif_count; bool cancel_recovery = true; wl12xx_get_vif_count(hw, vif, &vif_count); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF || !test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) goto out; /* * wl->vif can be null here if someone shuts down the interface * just when hardware recovery has been started. */ wl12xx_for_each_wlvif(wl, iter) { if (iter != wlvif) continue; __wl1271_op_remove_interface(wl, vif, true); break; } WARN_ON(iter != wlvif); if (wl12xx_need_fw_change(wl, vif_count, false)) { wl12xx_force_active_psm(wl); set_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags); wl12xx_queue_recovery_work(wl); cancel_recovery = false; } out: mutex_unlock(&wl->mutex); if (cancel_recovery) cancel_work_sync(&wl->recovery_work); } static int wl12xx_op_change_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum nl80211_iftype new_type, bool p2p) { struct wl1271 *wl = hw->priv; int ret; set_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags); wl1271_op_remove_interface(hw, vif); vif->type = new_type; vif->p2p = p2p; ret = wl1271_op_add_interface(hw, vif); clear_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags); return ret; } static int wl1271_join(struct wl1271 *wl, struct wl12xx_vif *wlvif, bool set_assoc) { int ret; bool is_ibss = (wlvif->bss_type == BSS_TYPE_IBSS); /* * One of the side effects of the JOIN command is that is clears * WPA/WPA2 keys from the chipset. Performing a JOIN while associated * to a WPA/WPA2 access point will therefore kill the data-path. * Currently the only valid scenario for JOIN during association * is on roaming, in which case we will also be given new keys. * Keep the below message for now, unless it starts bothering * users who really like to roam a lot :) */ if (test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) wl1271_info("JOIN while associated."); /* clear encryption type */ wlvif->encryption_type = KEY_NONE; if (set_assoc) set_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags); if (is_ibss) ret = wl12xx_cmd_role_start_ibss(wl, wlvif); else ret = wl12xx_cmd_role_start_sta(wl, wlvif); if (ret < 0) goto out; if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) goto out; /* * The join command disable the keep-alive mode, shut down its process, * and also clear the template config, so we need to reset it all after * the join. The acx_aid starts the keep-alive process, and the order * of the commands below is relevant. */ ret = wl1271_acx_keep_alive_mode(wl, wlvif, true); if (ret < 0) goto out; ret = wl1271_acx_aid(wl, wlvif, wlvif->aid); if (ret < 0) goto out; ret = wl12xx_cmd_build_klv_null_data(wl, wlvif); if (ret < 0) goto out; ret = wl1271_acx_keep_alive_config(wl, wlvif, CMD_TEMPL_KLV_IDX_NULL_DATA, ACX_KEEP_ALIVE_TPL_VALID); if (ret < 0) goto out; out: return ret; } static int wl1271_unjoin(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret; if (test_and_clear_bit(WLVIF_FLAG_CS_PROGRESS, &wlvif->flags)) { struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif); wl12xx_cmd_stop_channel_switch(wl); ieee80211_chswitch_done(vif, false); } /* to stop listening to a channel, we disconnect */ ret = wl12xx_cmd_role_stop_sta(wl, wlvif); if (ret < 0) goto out; /* reset TX security counters on a clean disconnect */ wlvif->tx_security_last_seq_lsb = 0; wlvif->tx_security_seq = 0; out: return ret; } static void wl1271_set_band_rate(struct wl1271 *wl, struct wl12xx_vif *wlvif) { wlvif->basic_rate_set = wlvif->bitrate_masks[wlvif->band]; wlvif->rate_set = wlvif->basic_rate_set; } static int wl1271_sta_handle_idle(struct wl1271 *wl, struct wl12xx_vif *wlvif, bool idle) { int ret; bool cur_idle = !test_bit(WLVIF_FLAG_IN_USE, &wlvif->flags); if (idle == cur_idle) return 0; if (idle) { /* no need to croc if we weren't busy (e.g. during boot) */ if (wl12xx_dev_role_started(wlvif)) { ret = wl12xx_stop_dev(wl, wlvif); if (ret < 0) goto out; } wlvif->rate_set = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) goto out; ret = wl1271_acx_keep_alive_config( wl, wlvif, CMD_TEMPL_KLV_IDX_NULL_DATA, ACX_KEEP_ALIVE_TPL_INVALID); if (ret < 0) goto out; clear_bit(WLVIF_FLAG_IN_USE, &wlvif->flags); } else { /* The current firmware only supports sched_scan in idle */ if (wl->sched_scanning) { wl1271_scan_sched_scan_stop(wl); ieee80211_sched_scan_stopped(wl->hw); } ret = wl12xx_start_dev(wl, wlvif); if (ret < 0) goto out; set_bit(WLVIF_FLAG_IN_USE, &wlvif->flags); } out: return ret; } static int wl12xx_config_vif(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_conf *conf, u32 changed) { bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS); int channel, ret; channel = ieee80211_frequency_to_channel(conf->channel->center_freq); /* if the channel changes while joined, join again */ if (changed & IEEE80211_CONF_CHANGE_CHANNEL && ((wlvif->band != conf->channel->band) || (wlvif->channel != channel))) { /* send all pending packets */ wl1271_tx_work_locked(wl); wlvif->band = conf->channel->band; wlvif->channel = channel; if (!is_ap) { /* * FIXME: the mac80211 should really provide a fixed * rate to use here. for now, just use the smallest * possible rate for the band as a fixed rate for * association frames and other control messages. */ if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) wl1271_set_band_rate(wl, wlvif); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) wl1271_warning("rate policy for channel " "failed %d", ret); /* * change the ROC channel. do it only if we are * not idle. otherwise, CROC will be called * anyway. */ if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) && wl12xx_dev_role_started(wlvif) && !(conf->flags & IEEE80211_CONF_IDLE)) { ret = wl12xx_stop_dev(wl, wlvif); if (ret < 0) return ret; ret = wl12xx_start_dev(wl, wlvif); if (ret < 0) return ret; } } } if ((changed & IEEE80211_CONF_CHANGE_PS) && !is_ap) { if ((conf->flags & IEEE80211_CONF_PS) && test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) && !test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags)) { int ps_mode; char *ps_mode_str; if (wl->conf.conn.forced_ps) { ps_mode = STATION_POWER_SAVE_MODE; ps_mode_str = "forced"; } else { ps_mode = STATION_AUTO_PS_MODE; ps_mode_str = "auto"; } wl1271_debug(DEBUG_PSM, "%s ps enabled", ps_mode_str); ret = wl1271_ps_set_mode(wl, wlvif, ps_mode); if (ret < 0) wl1271_warning("enter %s ps failed %d", ps_mode_str, ret); } else if (!(conf->flags & IEEE80211_CONF_PS) && test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags)) { wl1271_debug(DEBUG_PSM, "auto ps disabled"); ret = wl1271_ps_set_mode(wl, wlvif, STATION_ACTIVE_MODE); if (ret < 0) wl1271_warning("exit auto ps failed %d", ret); } } if (conf->power_level != wlvif->power_level) { ret = wl1271_acx_tx_power(wl, wlvif, conf->power_level); if (ret < 0) return ret; wlvif->power_level = conf->power_level; } return 0; } static int wl1271_op_config(struct ieee80211_hw *hw, u32 changed) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; struct ieee80211_conf *conf = &hw->conf; int channel, ret = 0; channel = ieee80211_frequency_to_channel(conf->channel->center_freq); wl1271_debug(DEBUG_MAC80211, "mac80211 config ch %d psm %s power %d %s" " changed 0x%x", channel, conf->flags & IEEE80211_CONF_PS ? "on" : "off", conf->power_level, conf->flags & IEEE80211_CONF_IDLE ? "idle" : "in use", changed); /* * mac80211 will go to idle nearly immediately after transmitting some * frames, such as the deauth. To make sure those frames reach the air, * wait here until the TX queue is fully flushed. */ if ((changed & IEEE80211_CONF_CHANGE_IDLE) && (conf->flags & IEEE80211_CONF_IDLE)) wl1271_tx_flush(wl); mutex_lock(&wl->mutex); /* we support configuring the channel and band even while off */ if (changed & IEEE80211_CONF_CHANGE_CHANNEL) { wl->band = conf->channel->band; wl->channel = channel; } if (changed & IEEE80211_CONF_CHANGE_POWER) wl->power_level = conf->power_level; if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; /* configure each interface */ wl12xx_for_each_wlvif(wl, wlvif) { ret = wl12xx_config_vif(wl, wlvif, conf, changed); if (ret < 0) goto out_sleep; } out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } struct wl1271_filter_params { bool enabled; int mc_list_length; u8 mc_list[ACX_MC_ADDRESS_GROUP_MAX][ETH_ALEN]; }; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) static u64 wl1271_op_prepare_multicast(struct ieee80211_hw *hw, struct netdev_hw_addr_list *mc_list) #else static u64 wl1271_op_prepare_multicast(struct ieee80211_hw *hw, int mc_count, struct dev_addr_list *mc_list) #endif { struct wl1271_filter_params *fp; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) struct netdev_hw_addr *ha; #else int i; #endif struct wl1271 *wl = hw->priv; if (unlikely(wl->state == WL1271_STATE_OFF)) return 0; fp = kzalloc(sizeof(*fp), GFP_ATOMIC); if (!fp) { wl1271_error("Out of memory setting filters."); return 0; } /* update multicast filtering parameters */ #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) fp->mc_list_length = 0; if (netdev_hw_addr_list_count(mc_list) > ACX_MC_ADDRESS_GROUP_MAX) { #else fp->enabled = true; if (mc_count > ACX_MC_ADDRESS_GROUP_MAX) { mc_count = 0; #endif fp->enabled = false; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) } else { fp->enabled = true; netdev_hw_addr_list_for_each(ha, mc_list) { #else } fp->mc_list_length = 0; for (i = 0; i < mc_count; i++) { if (mc_list->da_addrlen == ETH_ALEN) { #endif memcpy(fp->mc_list[fp->mc_list_length], #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) ha->addr, ETH_ALEN); #else mc_list->da_addr, ETH_ALEN); #endif fp->mc_list_length++; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) } #else } else wl1271_warning("Unknown mc address length."); mc_list = mc_list->next; #endif } return (u64)(unsigned long)fp; } #define WL1271_SUPPORTED_FILTERS (FIF_PROMISC_IN_BSS | \ FIF_ALLMULTI | \ FIF_FCSFAIL | \ FIF_BCN_PRBRESP_PROMISC | \ FIF_CONTROL | \ FIF_OTHER_BSS) static void wl1271_op_configure_filter(struct ieee80211_hw *hw, unsigned int changed, unsigned int *total, u64 multicast) { struct wl1271_filter_params *fp = (void *)(unsigned long)multicast; struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 configure filter changed %x" " total %x", changed, *total); mutex_lock(&wl->mutex); *total &= WL1271_SUPPORTED_FILTERS; changed &= WL1271_SUPPORTED_FILTERS; if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl12xx_for_each_wlvif(wl, wlvif) { if (wlvif->bss_type != BSS_TYPE_AP_BSS) { if (*total & FIF_ALLMULTI) ret = wl1271_acx_group_address_tbl(wl, wlvif, false, NULL, 0); else if (fp) ret = wl1271_acx_group_address_tbl(wl, wlvif, fp->enabled, fp->mc_list, fp->mc_list_length); if (ret < 0) goto out_sleep; } } /* * the fw doesn't provide an api to configure the filters. instead, * the filters configuration is based on the active roles / ROC * state. */ out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); kfree(fp); } static int wl1271_record_ap_key(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 id, u8 key_type, u8 key_size, const u8 *key, u8 hlid, u32 tx_seq_32, u16 tx_seq_16) { struct wl1271_ap_key *ap_key; int i; wl1271_debug(DEBUG_CRYPT, "record ap key id %d", (int)id); if (key_size > MAX_KEY_SIZE) return -EINVAL; /* * Find next free entry in ap_keys. Also check we are not replacing * an existing key. */ for (i = 0; i < MAX_NUM_KEYS; i++) { if (wlvif->ap.recorded_keys[i] == NULL) break; if (wlvif->ap.recorded_keys[i]->id == id) { wl1271_warning("trying to record key replacement"); return -EINVAL; } } if (i == MAX_NUM_KEYS) return -EBUSY; ap_key = kzalloc(sizeof(*ap_key), GFP_KERNEL); if (!ap_key) return -ENOMEM; ap_key->id = id; ap_key->key_type = key_type; ap_key->key_size = key_size; memcpy(ap_key->key, key, key_size); ap_key->hlid = hlid; ap_key->tx_seq_32 = tx_seq_32; ap_key->tx_seq_16 = tx_seq_16; wlvif->ap.recorded_keys[i] = ap_key; return 0; } static void wl1271_free_ap_keys(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int i; for (i = 0; i < MAX_NUM_KEYS; i++) { kfree(wlvif->ap.recorded_keys[i]); wlvif->ap.recorded_keys[i] = NULL; } } static int wl1271_ap_init_hwenc(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int i, ret = 0; struct wl1271_ap_key *key; bool wep_key_added = false; for (i = 0; i < MAX_NUM_KEYS; i++) { u8 hlid; if (wlvif->ap.recorded_keys[i] == NULL) break; key = wlvif->ap.recorded_keys[i]; hlid = key->hlid; if (hlid == WL12XX_INVALID_LINK_ID) hlid = wlvif->ap.bcast_hlid; ret = wl1271_cmd_set_ap_key(wl, wlvif, KEY_ADD_OR_REPLACE, key->id, key->key_type, key->key_size, key->key, hlid, key->tx_seq_32, key->tx_seq_16); if (ret < 0) goto out; if (key->key_type == KEY_WEP) wep_key_added = true; } if (wep_key_added) { ret = wl12xx_cmd_set_default_wep_key(wl, wlvif->default_key, wlvif->ap.bcast_hlid); if (ret < 0) goto out; } out: wl1271_free_ap_keys(wl, wlvif); return ret; } static int wl1271_set_key(struct wl1271 *wl, struct wl12xx_vif *wlvif, u16 action, u8 id, u8 key_type, u8 key_size, const u8 *key, u32 tx_seq_32, u16 tx_seq_16, struct ieee80211_sta *sta) { int ret; bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS); if (is_ap) { struct wl1271_station *wl_sta; u8 hlid; if (sta) { wl_sta = (struct wl1271_station *)sta->drv_priv; hlid = wl_sta->hlid; } else { hlid = wlvif->ap.bcast_hlid; } if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) { /* * We do not support removing keys after AP shutdown. * Pretend we do to make mac80211 happy. */ if (action != KEY_ADD_OR_REPLACE) return 0; ret = wl1271_record_ap_key(wl, wlvif, id, key_type, key_size, key, hlid, tx_seq_32, tx_seq_16); } else { ret = wl1271_cmd_set_ap_key(wl, wlvif, action, id, key_type, key_size, key, hlid, tx_seq_32, tx_seq_16); } if (ret < 0) return ret; } else { const u8 *addr; static const u8 bcast_addr[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; /* * A STA set to GEM cipher requires 2 tx spare blocks. * Return to default value when GEM cipher key is removed */ if (key_type == KEY_GEM) { if (action == KEY_ADD_OR_REPLACE) wl->tx_spare_blocks = 2; else if (action == KEY_REMOVE) wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT; } addr = sta ? sta->addr : bcast_addr; if (is_zero_ether_addr(addr)) { /* We dont support TX only encryption */ return -EOPNOTSUPP; } /* The wl1271 does not allow to remove unicast keys - they will be cleared automatically on next CMD_JOIN. Ignore the request silently, as we dont want the mac80211 to emit an error message. */ if (action == KEY_REMOVE && !is_broadcast_ether_addr(addr)) return 0; /* don't remove key if hlid was already deleted */ if (action == KEY_REMOVE && wlvif->sta.hlid == WL12XX_INVALID_LINK_ID) return 0; ret = wl1271_cmd_set_sta_key(wl, wlvif, action, id, key_type, key_size, key, addr, tx_seq_32, tx_seq_16); if (ret < 0) return ret; /* the default WEP key needs to be configured at least once */ if (key_type == KEY_WEP) { ret = wl12xx_cmd_set_default_wep_key(wl, wlvif->default_key, wlvif->sta.hlid); if (ret < 0) return ret; } } return 0; } static int wl1271_op_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key_conf) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret; u32 tx_seq_32 = 0; u16 tx_seq_16 = 0; u8 key_type; wl1271_debug(DEBUG_MAC80211, "mac80211 set key"); wl1271_debug(DEBUG_CRYPT, "CMD: 0x%x sta: %p", cmd, sta); wl1271_debug(DEBUG_CRYPT, "Key: algo:0x%x, id:%d, len:%d flags 0x%x", key_conf->cipher, key_conf->keyidx, key_conf->keylen, key_conf->flags); wl1271_dump(DEBUG_CRYPT, "KEY: ", key_conf->key, key_conf->keylen); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EAGAIN; goto out_unlock; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out_unlock; switch (key_conf->cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: key_type = KEY_WEP; key_conf->hw_key_idx = key_conf->keyidx; break; case WLAN_CIPHER_SUITE_TKIP: key_type = KEY_TKIP; key_conf->hw_key_idx = key_conf->keyidx; tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq); tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq); break; case WLAN_CIPHER_SUITE_CCMP: key_type = KEY_AES; key_conf->flags |= IEEE80211_KEY_FLAG_PUT_IV_SPACE; tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq); tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq); break; case WL1271_CIPHER_SUITE_GEM: key_type = KEY_GEM; tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq); tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq); break; default: wl1271_error("Unknown key algo 0x%x", key_conf->cipher); ret = -EOPNOTSUPP; goto out_sleep; } switch (cmd) { case SET_KEY: ret = wl1271_set_key(wl, wlvif, KEY_ADD_OR_REPLACE, key_conf->keyidx, key_type, key_conf->keylen, key_conf->key, tx_seq_32, tx_seq_16, sta); if (ret < 0) { wl1271_error("Could not add or replace key"); goto out_sleep; } /* * reconfiguring arp response if the unicast (or common) * encryption key type was changed */ if (wlvif->bss_type == BSS_TYPE_STA_BSS && (sta || key_type == KEY_WEP) && wlvif->encryption_type != key_type) { wlvif->encryption_type = key_type; ret = wl1271_cmd_build_arp_rsp(wl, wlvif); if (ret < 0) { wl1271_warning("build arp rsp failed: %d", ret); goto out_sleep; } } break; case DISABLE_KEY: ret = wl1271_set_key(wl, wlvif, KEY_REMOVE, key_conf->keyidx, key_type, key_conf->keylen, key_conf->key, 0, 0, sta); if (ret < 0) { wl1271_error("Could not remove key"); goto out_sleep; } break; default: wl1271_error("Unsupported key cmd 0x%x", cmd); ret = -EOPNOTSUPP; break; } out_sleep: wl1271_ps_elp_sleep(wl); out_unlock: mutex_unlock(&wl->mutex); return ret; } static int wl1271_op_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_scan_request *req) { struct wl1271 *wl = hw->priv; int ret; u8 *ssid = NULL; size_t len = 0; wl1271_debug(DEBUG_MAC80211, "mac80211 hw scan"); if (req->n_ssids) { ssid = req->ssids[0].ssid; len = req->ssids[0].ssid_len; } mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) { /* * We cannot return -EBUSY here because cfg80211 will expect * a call to ieee80211_scan_completed if we do - in this case * there won't be any call. */ ret = -EAGAIN; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; /* fail if there is any role in ROC */ if (find_first_bit(wl->roc_map, WL12XX_MAX_ROLES) < WL12XX_MAX_ROLES) { /* don't allow scanning right now */ ret = -EBUSY; goto out_sleep; } ret = wl1271_scan(hw->priv, vif, ssid, len, req); out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static void wl1271_op_cancel_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 cancel hw scan"); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) goto out; if (wl->scan.state == WL1271_SCAN_STATE_IDLE) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; if (wl->scan.state != WL1271_SCAN_STATE_DONE) { ret = wl1271_scan_stop(wl); if (ret < 0) goto out_sleep; } /* * Rearm the tx watchdog just before idling scan. This * prevents just-finished scans from triggering the watchdog */ wl12xx_rearm_tx_watchdog_locked(wl); wl->scan.state = WL1271_SCAN_STATE_IDLE; memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch)); wl->scan_vif = NULL; wl->scan.req = NULL; ieee80211_scan_completed(wl->hw, true); out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); cancel_delayed_work_sync(&wl->scan_complete_work); } static int wl1271_op_sched_scan_start(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_sched_scan_request *req, struct ieee80211_sched_scan_ies *ies) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret; wl1271_debug(DEBUG_MAC80211, "wl1271_op_sched_scan_start"); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) { ret = -EAGAIN; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl1271_scan_sched_scan_config(wl, wlvif, req, ies); if (ret < 0) goto out_sleep; ret = wl1271_scan_sched_scan_start(wl, wlvif); if (ret < 0) goto out_sleep; wl->sched_scanning = true; out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static void wl1271_op_sched_scan_stop(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; int ret; wl1271_debug(DEBUG_MAC80211, "wl1271_op_sched_scan_stop"); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl1271_scan_sched_scan_stop(wl); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static int wl1271_op_set_frag_threshold(struct ieee80211_hw *hw, u32 value) { struct wl1271 *wl = hw->priv; int ret = 0; mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EAGAIN; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl1271_acx_frag_threshold(wl, value); if (ret < 0) wl1271_warning("wl1271_op_set_frag_threshold failed: %d", ret); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static int wl1271_op_set_rts_threshold(struct ieee80211_hw *hw, u32 value) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; int ret = 0; mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EAGAIN; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl12xx_for_each_wlvif(wl, wlvif) { ret = wl1271_acx_rts_threshold(wl, wlvif, value); if (ret < 0) wl1271_warning("set rts threshold failed: %d", ret); } wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static int wl1271_ssid_set(struct ieee80211_vif *vif, struct sk_buff *skb, int offset) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); u8 ssid_len; const u8 *ptr = cfg80211_find_ie(WLAN_EID_SSID, skb->data + offset, skb->len - offset); if (!ptr) { wl1271_error("No SSID in IEs!"); return -ENOENT; } ssid_len = ptr[1]; if (ssid_len > IEEE80211_MAX_SSID_LEN) { wl1271_error("SSID is too long!"); return -EINVAL; } wlvif->ssid_len = ssid_len; memcpy(wlvif->ssid, ptr+2, ssid_len); return 0; } static void wl12xx_remove_ie(struct sk_buff *skb, u8 eid, int ieoffset) { int len; const u8 *next, *end = skb->data + skb->len; u8 *ie = (u8 *)cfg80211_find_ie(eid, skb->data + ieoffset, skb->len - ieoffset); if (!ie) return; len = ie[1] + 2; next = ie + len; memmove(ie, next, end - next); skb_trim(skb, skb->len - len); } static void wl12xx_remove_vendor_ie(struct sk_buff *skb, unsigned int oui, u8 oui_type, int ieoffset) { int len; const u8 *next, *end = skb->data + skb->len; u8 *ie = (u8 *)cfg80211_find_vendor_ie(oui, oui_type, skb->data + ieoffset, skb->len - ieoffset); if (!ie) return; len = ie[1] + 2; next = ie + len; memmove(ie, next, end - next); skb_trim(skb, skb->len - len); } static int wl1271_ap_set_probe_resp_tmpl(struct wl1271 *wl, u32 rates, struct ieee80211_vif *vif) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct sk_buff *skb; int ret; skb = ieee80211_proberesp_get(wl->hw, vif); if (!skb) return -EOPNOTSUPP; ret = wl1271_cmd_template_set(wl, wlvif->role_id, CMD_TEMPL_AP_PROBE_RESPONSE, skb->data, skb->len, 0, rates); dev_kfree_skb(skb); return ret; } static int wl1271_ap_set_probe_resp_tmpl_legacy(struct wl1271 *wl, struct ieee80211_vif *vif, u8 *probe_rsp_data, size_t probe_rsp_len, u32 rates) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct ieee80211_bss_conf *bss_conf = &vif->bss_conf; u8 probe_rsp_templ[WL1271_CMD_TEMPL_MAX_SIZE]; int ssid_ie_offset, ie_offset, templ_len; const u8 *ptr; /* no need to change probe response if the SSID is set correctly */ if (wlvif->ssid_len > 0) return wl1271_cmd_template_set(wl, wlvif->role_id, CMD_TEMPL_AP_PROBE_RESPONSE, probe_rsp_data, probe_rsp_len, 0, rates); if (probe_rsp_len + bss_conf->ssid_len > WL1271_CMD_TEMPL_MAX_SIZE) { wl1271_error("probe_rsp template too big"); return -EINVAL; } /* start searching from IE offset */ ie_offset = offsetof(struct ieee80211_mgmt, u.probe_resp.variable); ptr = cfg80211_find_ie(WLAN_EID_SSID, probe_rsp_data + ie_offset, probe_rsp_len - ie_offset); if (!ptr) { wl1271_error("No SSID in beacon!"); return -EINVAL; } ssid_ie_offset = ptr - probe_rsp_data; ptr += (ptr[1] + 2); memcpy(probe_rsp_templ, probe_rsp_data, ssid_ie_offset); /* insert SSID from bss_conf */ probe_rsp_templ[ssid_ie_offset] = WLAN_EID_SSID; probe_rsp_templ[ssid_ie_offset + 1] = bss_conf->ssid_len; memcpy(probe_rsp_templ + ssid_ie_offset + 2, bss_conf->ssid, bss_conf->ssid_len); templ_len = ssid_ie_offset + 2 + bss_conf->ssid_len; memcpy(probe_rsp_templ + ssid_ie_offset + 2 + bss_conf->ssid_len, ptr, probe_rsp_len - (ptr - probe_rsp_data)); templ_len += probe_rsp_len - (ptr - probe_rsp_data); return wl1271_cmd_template_set(wl, wlvif->role_id, CMD_TEMPL_AP_PROBE_RESPONSE, probe_rsp_templ, templ_len, 0, rates); } static int wl1271_bss_erp_info_changed(struct wl1271 *wl, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret = 0; if (changed & BSS_CHANGED_ERP_SLOT) { if (bss_conf->use_short_slot) ret = wl1271_acx_slot(wl, wlvif, SLOT_TIME_SHORT); else ret = wl1271_acx_slot(wl, wlvif, SLOT_TIME_LONG); if (ret < 0) { wl1271_warning("Set slot time failed %d", ret); goto out; } } if (changed & BSS_CHANGED_ERP_PREAMBLE) { if (bss_conf->use_short_preamble) wl1271_acx_set_preamble(wl, wlvif, ACX_PREAMBLE_SHORT); else wl1271_acx_set_preamble(wl, wlvif, ACX_PREAMBLE_LONG); } if (changed & BSS_CHANGED_ERP_CTS_PROT) { if (bss_conf->use_cts_prot) ret = wl1271_acx_cts_protect(wl, wlvif, CTSPROTECT_ENABLE); else ret = wl1271_acx_cts_protect(wl, wlvif, CTSPROTECT_DISABLE); if (ret < 0) { wl1271_warning("Set ctsprotect failed %d", ret); goto out; } } out: return ret; } static int wl1271_bss_beacon_info_changed(struct wl1271 *wl, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS); int ret = 0; if ((changed & BSS_CHANGED_BEACON_INT)) { wl1271_debug(DEBUG_MASTER, "beacon interval updated: %d", bss_conf->beacon_int); wlvif->beacon_int = bss_conf->beacon_int; } if ((changed & BSS_CHANGED_AP_PROBE_RESP) && is_ap) { u32 rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); if (!wl1271_ap_set_probe_resp_tmpl(wl, rate, vif)) { wl1271_debug(DEBUG_AP, "probe response updated"); set_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags); } } if ((changed & BSS_CHANGED_BEACON)) { struct ieee80211_hdr *hdr; u32 min_rate; int ieoffset = offsetof(struct ieee80211_mgmt, u.beacon.variable); struct sk_buff *beacon = ieee80211_beacon_get(wl->hw, vif); u16 tmpl_id; if (!beacon) { ret = -EINVAL; goto out; } wl1271_debug(DEBUG_MASTER, "beacon updated"); ret = wl1271_ssid_set(vif, beacon, ieoffset); if (ret < 0) { dev_kfree_skb(beacon); goto out; } min_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); tmpl_id = is_ap ? CMD_TEMPL_AP_BEACON : CMD_TEMPL_BEACON; ret = wl1271_cmd_template_set(wl, wlvif->role_id, tmpl_id, beacon->data, beacon->len, 0, min_rate); if (ret < 0) { dev_kfree_skb(beacon); goto out; } /* * In case we already have a probe-resp beacon set explicitly * by usermode, don't use the beacon data. */ if (test_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags)) goto end_bcn; /* remove TIM ie from probe response */ wl12xx_remove_ie(beacon, WLAN_EID_TIM, ieoffset); /* * remove p2p ie from probe response. * the fw reponds to probe requests that don't include * the p2p ie. probe requests with p2p ie will be passed, * and will be responded by the supplicant (the spec * forbids including the p2p ie when responding to probe * requests that didn't include it). */ wl12xx_remove_vendor_ie(beacon, WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P, ieoffset); hdr = (struct ieee80211_hdr *) beacon->data; hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_PROBE_RESP); if (is_ap) ret = wl1271_ap_set_probe_resp_tmpl_legacy(wl, vif, beacon->data, beacon->len, min_rate); else ret = wl1271_cmd_template_set(wl, wlvif->role_id, CMD_TEMPL_PROBE_RESPONSE, beacon->data, beacon->len, 0, min_rate); end_bcn: dev_kfree_skb(beacon); if (ret < 0) goto out; } out: if (ret != 0) wl1271_error("beacon info change failed: %d", ret); return ret; } /* AP mode changes */ static void wl1271_bss_info_changed_ap(struct wl1271 *wl, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret = 0; if ((changed & BSS_CHANGED_BASIC_RATES)) { u32 rates = bss_conf->basic_rates; wlvif->basic_rate_set = wl1271_tx_enabled_rates_get(wl, rates, wlvif->band); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_init_ap_rates(wl, wlvif); if (ret < 0) { wl1271_error("AP rate policy change failed %d", ret); goto out; } ret = wl1271_ap_init_templates(wl, vif); if (ret < 0) goto out; } ret = wl1271_bss_beacon_info_changed(wl, vif, bss_conf, changed); if (ret < 0) goto out; if ((changed & BSS_CHANGED_BEACON_ENABLED)) { if (bss_conf->enable_beacon) { if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) { ret = wl12xx_cmd_role_start_ap(wl, wlvif); if (ret < 0) goto out; ret = wl1271_ap_init_hwenc(wl, wlvif); if (ret < 0) goto out; set_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags); wl1271_debug(DEBUG_AP, "started AP"); } } else { if (test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) { ret = wl12xx_cmd_role_stop_ap(wl, wlvif); if (ret < 0) goto out; clear_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags); clear_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags); wl1271_debug(DEBUG_AP, "stopped AP"); } } } ret = wl1271_bss_erp_info_changed(wl, vif, bss_conf, changed); if (ret < 0) goto out; /* Handle HT information change */ if ((changed & BSS_CHANGED_HT) && (bss_conf->channel_type != NL80211_CHAN_NO_HT)) { ret = wl1271_acx_set_ht_information(wl, wlvif, bss_conf->ht_operation_mode); if (ret < 0) { wl1271_warning("Set ht information failed %d", ret); goto out; } } out: return; } /* STA/IBSS mode changes */ static void wl1271_bss_info_changed_sta(struct wl1271 *wl, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); bool do_join = false, set_assoc = false; bool is_ibss = (wlvif->bss_type == BSS_TYPE_IBSS); bool ibss_joined = false; u32 sta_rate_set = 0; int ret; struct ieee80211_sta *sta; bool sta_exists = false; struct ieee80211_sta_ht_cap sta_ht_cap; if (is_ibss) { ret = wl1271_bss_beacon_info_changed(wl, vif, bss_conf, changed); if (ret < 0) goto out; } if (changed & BSS_CHANGED_IBSS) { if (bss_conf->ibss_joined) { set_bit(WLVIF_FLAG_IBSS_JOINED, &wlvif->flags); ibss_joined = true; } else { if (test_and_clear_bit(WLVIF_FLAG_IBSS_JOINED, &wlvif->flags)) wl1271_unjoin(wl, wlvif); } } if ((changed & BSS_CHANGED_BEACON_INT) && ibss_joined) do_join = true; /* Need to update the SSID (for filtering etc) */ if ((changed & BSS_CHANGED_BEACON) && ibss_joined) do_join = true; if ((changed & BSS_CHANGED_BEACON_ENABLED) && ibss_joined) { wl1271_debug(DEBUG_ADHOC, "ad-hoc beaconing: %s", bss_conf->enable_beacon ? "enabled" : "disabled"); do_join = true; } if (changed & BSS_CHANGED_IDLE && !is_ibss) { ret = wl1271_sta_handle_idle(wl, wlvif, bss_conf->idle); if (ret < 0) wl1271_warning("idle mode change failed %d", ret); } if ((changed & BSS_CHANGED_CQM)) { bool enable = false; if (bss_conf->cqm_rssi_thold) enable = true; ret = wl1271_acx_rssi_snr_trigger(wl, wlvif, enable, bss_conf->cqm_rssi_thold, bss_conf->cqm_rssi_hyst); if (ret < 0) goto out; wlvif->rssi_thold = bss_conf->cqm_rssi_thold; } if (changed & BSS_CHANGED_BSSID && (is_ibss || bss_conf->assoc)) if (!is_zero_ether_addr(bss_conf->bssid)) { ret = wl12xx_cmd_build_null_data(wl, wlvif); if (ret < 0) goto out; ret = wl1271_build_qos_null_data(wl, vif); if (ret < 0) goto out; /* Need to update the BSSID (for filtering etc) */ do_join = true; } if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_HT)) { rcu_read_lock(); sta = ieee80211_find_sta(vif, bss_conf->bssid); if (!sta) goto sta_not_found; /* save the supp_rates of the ap */ sta_rate_set = sta->supp_rates[wl->hw->conf.channel->band]; if (sta->ht_cap.ht_supported) sta_rate_set |= (sta->ht_cap.mcs.rx_mask[0] << HW_HT_RATES_OFFSET); sta_ht_cap = sta->ht_cap; sta_exists = true; sta_not_found: rcu_read_unlock(); } if ((changed & BSS_CHANGED_ASSOC)) { if (bss_conf->assoc) { u32 rates; int ieoffset; wlvif->aid = bss_conf->aid; wlvif->beacon_int = bss_conf->beacon_int; set_assoc = true; /* * use basic rates from AP, and determine lowest rate * to use with control frames. */ rates = bss_conf->basic_rates; wlvif->basic_rate_set = wl1271_tx_enabled_rates_get(wl, rates, wlvif->band); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); if (sta_rate_set) wlvif->rate_set = wl1271_tx_enabled_rates_get(wl, sta_rate_set, wlvif->band); ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) goto out; /* * with wl1271, we don't need to update the * beacon_int and dtim_period, because the firmware * updates it by itself when the first beacon is * received after a join. */ ret = wl1271_cmd_build_ps_poll(wl, wlvif, wlvif->aid); if (ret < 0) goto out; /* * Get a template for hardware connection maintenance */ dev_kfree_skb(wlvif->probereq); wlvif->probereq = wl1271_cmd_build_ap_probe_req(wl, wlvif, NULL); ieoffset = offsetof(struct ieee80211_mgmt, u.probe_req.variable); wl1271_ssid_set(vif, wlvif->probereq, ieoffset); /* enable the connection monitoring feature */ ret = wl1271_acx_conn_monit_params(wl, wlvif, true); if (ret < 0) goto out; } else { /* use defaults when not associated */ bool was_assoc = !!test_and_clear_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags); bool was_ifup = !!test_and_clear_bit(WLVIF_FLAG_STA_STATE_SENT, &wlvif->flags); wlvif->aid = 0; /* free probe-request template */ dev_kfree_skb(wlvif->probereq); wlvif->probereq = NULL; /* revert back to minimum rates for the current band */ wl1271_set_band_rate(wl, wlvif); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) goto out; /* disable connection monitor features */ ret = wl1271_acx_conn_monit_params(wl, wlvif, false); /* Disable the keep-alive feature */ ret = wl1271_acx_keep_alive_mode(wl, wlvif, false); if (ret < 0) goto out; /* restore the bssid filter and go to dummy bssid */ if (was_assoc) { /* * we might have to disable roc, if there was * no IF_OPER_UP notification. */ if (!was_ifup) { ret = wl12xx_croc(wl, wlvif->role_id); if (ret < 0) goto out; } /* * (we also need to disable roc in case of * roaming on the same channel. until we will * have a better flow...) */ if (test_bit(wlvif->dev_role_id, wl->roc_map)) { ret = wl12xx_croc(wl, wlvif->dev_role_id); if (ret < 0) goto out; } wl1271_unjoin(wl, wlvif); if (!bss_conf->idle) wl12xx_start_dev(wl, wlvif); } } } if (changed & BSS_CHANGED_IBSS) { wl1271_debug(DEBUG_ADHOC, "ibss_joined: %d", bss_conf->ibss_joined); if (bss_conf->ibss_joined) { u32 rates = bss_conf->basic_rates; wlvif->basic_rate_set = wl1271_tx_enabled_rates_get(wl, rates, wlvif->band); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); /* by default, use 11b + OFDM rates */ wlvif->rate_set = CONF_TX_IBSS_DEFAULT_RATES; ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) goto out; } } ret = wl1271_bss_erp_info_changed(wl, vif, bss_conf, changed); if (ret < 0) goto out; if (do_join) { ret = wl1271_join(wl, wlvif, set_assoc); if (ret < 0) { wl1271_warning("cmd join failed %d", ret); goto out; } /* ROC until connected (after EAPOL exchange) */ if (!is_ibss) { ret = wl12xx_roc(wl, wlvif, wlvif->role_id); if (ret < 0) goto out; if (test_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags)) wl12xx_set_authorized(wl, wlvif); } /* * stop device role if started (we might already be in * STA/IBSS role). */ if (wl12xx_dev_role_started(wlvif)) { ret = wl12xx_stop_dev(wl, wlvif); if (ret < 0) goto out; } } /* Handle new association with HT. Do this after join. */ if (sta_exists) { if ((changed & BSS_CHANGED_HT) && (bss_conf->channel_type != NL80211_CHAN_NO_HT)) { ret = wl1271_acx_set_ht_capabilities(wl, &sta_ht_cap, true, wlvif->sta.hlid); if (ret < 0) { wl1271_warning("Set ht cap true failed %d", ret); goto out; } } /* handle new association without HT and disassociation */ else if (changed & BSS_CHANGED_ASSOC) { ret = wl1271_acx_set_ht_capabilities(wl, &sta_ht_cap, false, wlvif->sta.hlid); if (ret < 0) { wl1271_warning("Set ht cap false failed %d", ret); goto out; } } } /* Handle HT information change. Done after join. */ if ((changed & BSS_CHANGED_HT) && (bss_conf->channel_type != NL80211_CHAN_NO_HT)) { ret = wl1271_acx_set_ht_information(wl, wlvif, bss_conf->ht_operation_mode); if (ret < 0) { wl1271_warning("Set ht information failed %d", ret); goto out; } } /* Handle arp filtering. Done after join. */ if ((changed & BSS_CHANGED_ARP_FILTER) || (!is_ibss && (changed & BSS_CHANGED_QOS))) { __be32 addr = bss_conf->arp_addr_list[0]; wlvif->sta.qos = bss_conf->qos; WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS); if (bss_conf->arp_addr_cnt == 1 && bss_conf->arp_filter_enabled) { wlvif->ip_addr = addr; /* * The template should have been configured only upon * association. however, it seems that the correct ip * isn't being set (when sending), so we have to * reconfigure the template upon every ip change. */ ret = wl1271_cmd_build_arp_rsp(wl, wlvif); if (ret < 0) { wl1271_warning("build arp rsp failed: %d", ret); goto out; } ret = wl1271_acx_arp_ip_filter(wl, wlvif, (ACX_ARP_FILTER_ARP_FILTERING | ACX_ARP_FILTER_AUTO_ARP), addr); } else { wlvif->ip_addr = 0; ret = wl1271_acx_arp_ip_filter(wl, wlvif, 0, addr); } if (ret < 0) goto out; } out: return; } static void wl1271_op_bss_info_changed(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS); int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 bss info changed 0x%x", (int)changed); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; if (unlikely(!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags))) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; if (is_ap) wl1271_bss_info_changed_ap(wl, vif, bss_conf, changed); else wl1271_bss_info_changed_sta(wl, vif, bss_conf, changed); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static int wl1271_op_conf_tx(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u16 queue, const struct ieee80211_tx_queue_params *params) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); u8 ps_scheme; int ret = 0; mutex_lock(&wl->mutex); wl1271_debug(DEBUG_MAC80211, "mac80211 conf tx %d", queue); if (params->uapsd) ps_scheme = CONF_PS_SCHEME_UPSD_TRIGGER; else ps_scheme = CONF_PS_SCHEME_LEGACY; if (!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; /* * the txop is confed in units of 32us by the mac80211, * we need us */ ret = wl1271_acx_ac_cfg(wl, wlvif, wl1271_tx_get_queue(queue), params->cw_min, params->cw_max, params->aifs, params->txop << 5); if (ret < 0) goto out_sleep; ret = wl1271_acx_tid_cfg(wl, wlvif, wl1271_tx_get_queue(queue), CONF_CHANNEL_TYPE_EDCF, wl1271_tx_get_queue(queue), ps_scheme, CONF_ACK_POLICY_LEGACY, 0, 0); out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static u64 wl1271_op_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); u64 mactime = ULLONG_MAX; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 get tsf"); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl12xx_acx_tsf_info(wl, wlvif, &mactime); if (ret < 0) goto out_sleep; out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return mactime; } static int wl1271_op_get_survey(struct ieee80211_hw *hw, int idx, struct survey_info *survey) { struct wl1271 *wl = hw->priv; struct ieee80211_conf *conf = &hw->conf; if (idx != 0) return -ENOENT; survey->channel = conf->channel; survey->filled = SURVEY_INFO_NOISE_DBM; survey->noise = wl->noise; return 0; } static int wl1271_allocate_sta(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_sta *sta) { struct wl1271_station *wl_sta; int ret; if (wl->active_sta_count >= AP_MAX_STATIONS) { wl1271_warning("could not allocate HLID - too much stations"); return -EBUSY; } wl_sta = (struct wl1271_station *)sta->drv_priv; ret = wl12xx_allocate_link(wl, wlvif, &wl_sta->hlid); if (ret < 0) { wl1271_warning("could not allocate HLID - too many links"); return -EBUSY; } set_bit(wl_sta->hlid, wlvif->ap.sta_hlid_map); memcpy(wl->links[wl_sta->hlid].addr, sta->addr, ETH_ALEN); wl->active_sta_count++; return 0; } void wl1271_free_sta(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 hlid) { if (!test_bit(hlid, wlvif->ap.sta_hlid_map)) return; clear_bit(hlid, wlvif->ap.sta_hlid_map); memset(wl->links[hlid].addr, 0, ETH_ALEN); wl->links[hlid].ba_bitmap = 0; __clear_bit(hlid, &wl->ap_ps_map); __clear_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map); wl12xx_free_link(wl, wlvif, &hlid); wl->active_sta_count--; /* * rearm the tx watchdog when the last STA is freed - give the FW a * chance to return STA-buffered packets before complaining. */ if (wl->active_sta_count == 0) wl12xx_rearm_tx_watchdog_locked(wl); } static int wl12xx_sta_add(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_sta *sta) { struct wl1271_station *wl_sta; int ret = 0; u8 hlid; wl1271_debug(DEBUG_MAC80211, "mac80211 add sta %d", (int)sta->aid); ret = wl1271_allocate_sta(wl, wlvif, sta); if (ret < 0) return ret; wl_sta = (struct wl1271_station *)sta->drv_priv; hlid = wl_sta->hlid; ret = wl12xx_cmd_add_peer(wl, wlvif, sta, hlid); if (ret < 0) wl1271_free_sta(wl, wlvif, hlid); return ret; } static int wl12xx_sta_remove(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_sta *sta) { struct wl1271_station *wl_sta; int ret = 0, id; wl1271_debug(DEBUG_MAC80211, "mac80211 remove sta %d", (int)sta->aid); wl_sta = (struct wl1271_station *)sta->drv_priv; id = wl_sta->hlid; if (WARN_ON(!test_bit(id, wlvif->ap.sta_hlid_map))) return -EINVAL; ret = wl12xx_cmd_remove_peer(wl, wl_sta->hlid); if (ret < 0) return ret; wl1271_free_sta(wl, wlvif, wl_sta->hlid); return ret; } static int wl12xx_update_sta_state(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_sta *sta, enum ieee80211_sta_state old_state, enum ieee80211_sta_state new_state) { struct wl1271_station *wl_sta; u8 hlid; bool is_ap = wlvif->bss_type == BSS_TYPE_AP_BSS; bool is_sta = wlvif->bss_type == BSS_TYPE_STA_BSS; int ret; wl_sta = (struct wl1271_station *)sta->drv_priv; hlid = wl_sta->hlid; /* Add station (AP mode) */ if (is_ap && old_state == IEEE80211_STA_NOTEXIST && new_state == IEEE80211_STA_NONE) return wl12xx_sta_add(wl, wlvif, sta); /* Remove station (AP mode) */ if (is_ap && old_state == IEEE80211_STA_NONE && new_state == IEEE80211_STA_NOTEXIST) { /* must not fail */ wl12xx_sta_remove(wl, wlvif, sta); return 0; } /* Authorize station (AP mode) */ if (is_ap && new_state == IEEE80211_STA_AUTHORIZED) { ret = wl12xx_cmd_set_peer_state(wl, hlid); if (ret < 0) return ret; ret = wl1271_acx_set_ht_capabilities(wl, &sta->ht_cap, true, hlid); return ret; } /* Authorize station */ if (is_sta && new_state == IEEE80211_STA_AUTHORIZED) { set_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags); return wl12xx_set_authorized(wl, wlvif); } if (is_sta && old_state == IEEE80211_STA_AUTHORIZED && new_state == IEEE80211_STA_ASSOC) { clear_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags); return 0; } return 0; } static int wl12xx_op_sta_state(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, enum ieee80211_sta_state old_state, enum ieee80211_sta_state new_state) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 sta %d state=%d->%d", sta->aid, old_state, new_state); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EBUSY; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl12xx_update_sta_state(wl, wlvif, sta, old_state, new_state); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); if (new_state < old_state) return 0; return ret; } static int wl1271_op_ampdu_action(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum ieee80211_ampdu_mlme_action action, struct ieee80211_sta *sta, u16 tid, u16 *ssn, u8 buf_size) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret; u8 hlid, *ba_bitmap; wl1271_debug(DEBUG_MAC80211, "mac80211 ampdu action %d tid %d", action, tid); /* sanity check - the fields in FW are only 8bits wide */ if (WARN_ON(tid > 0xFF)) return -ENOTSUPP; mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EAGAIN; goto out; } if (wlvif->bss_type == BSS_TYPE_STA_BSS) { hlid = wlvif->sta.hlid; ba_bitmap = &wlvif->sta.ba_rx_bitmap; } else if (wlvif->bss_type == BSS_TYPE_AP_BSS) { struct wl1271_station *wl_sta; wl_sta = (struct wl1271_station *)sta->drv_priv; hlid = wl_sta->hlid; ba_bitmap = &wl->links[hlid].ba_bitmap; } else { ret = -EINVAL; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl1271_debug(DEBUG_MAC80211, "mac80211 ampdu: Rx tid %d action %d", tid, action); switch (action) { case IEEE80211_AMPDU_RX_START: if (!wlvif->ba_support || !wlvif->ba_allowed) { ret = -ENOTSUPP; break; } if (wl->ba_rx_session_count >= RX_BA_MAX_SESSIONS) { ret = -EBUSY; wl1271_error("exceeded max RX BA sessions"); break; } if (*ba_bitmap & BIT(tid)) { ret = -EINVAL; wl1271_error("cannot enable RX BA session on active " "tid: %d", tid); break; } ret = wl12xx_acx_set_ba_receiver_session(wl, tid, *ssn, true, hlid); if (!ret) { *ba_bitmap |= BIT(tid); wl->ba_rx_session_count++; } break; case IEEE80211_AMPDU_RX_STOP: if (!(*ba_bitmap & BIT(tid))) { ret = -EINVAL; wl1271_error("no active RX BA session on tid: %d", tid); break; } ret = wl12xx_acx_set_ba_receiver_session(wl, tid, 0, false, hlid); if (!ret) { *ba_bitmap &= ~BIT(tid); wl->ba_rx_session_count--; } break; /* * The BA initiator session management in FW independently. * Falling break here on purpose for all TX APDU commands. */ case IEEE80211_AMPDU_TX_START: case IEEE80211_AMPDU_TX_STOP: case IEEE80211_AMPDU_TX_OPERATIONAL: ret = -EINVAL; break; default: wl1271_error("Incorrect ampdu action id=%x\n", action); ret = -EINVAL; } wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static int wl12xx_set_bitrate_mask(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const struct cfg80211_bitrate_mask *mask) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct wl1271 *wl = hw->priv; int i, ret = 0; wl1271_debug(DEBUG_MAC80211, "mac80211 set_bitrate_mask 0x%x 0x%x", mask->control[NL80211_BAND_2GHZ].legacy, mask->control[NL80211_BAND_5GHZ].legacy); mutex_lock(&wl->mutex); for (i = 0; i < IEEE80211_NUM_BANDS; i++) wlvif->bitrate_masks[i] = wl1271_tx_enabled_rates_get(wl, mask->control[i].legacy, i); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; if (wlvif->bss_type == BSS_TYPE_STA_BSS && !test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) { ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl1271_set_band_rate(wl, wlvif); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_acx_sta_rate_policies(wl, wlvif); wl1271_ps_elp_sleep(wl); } out: mutex_unlock(&wl->mutex); return ret; } static void wl12xx_op_channel_switch(struct ieee80211_hw *hw, struct ieee80211_channel_switch *ch_switch) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 channel switch"); wl1271_tx_flush(wl); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { wl12xx_for_each_wlvif_sta(wl, wlvif) { struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif); ieee80211_chswitch_done(vif, false); } goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; /* TODO: change mac80211 to pass vif as param */ wl12xx_for_each_wlvif_sta(wl, wlvif) { ret = wl12xx_cmd_channel_switch(wl, wlvif, ch_switch); if (!ret) set_bit(WLVIF_FLAG_CS_PROGRESS, &wlvif->flags); } wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static bool wl1271_tx_frames_pending(struct ieee80211_hw *hw) { struct wl1271 *wl = hw->priv; bool ret = false; mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; /* packets are considered pending if in the TX queue or the FW */ ret = (wl1271_tx_total_queue_count(wl) > 0) || (wl->tx_frames_cnt > 0); out: mutex_unlock(&wl->mutex); return ret; } /* can't be const, mac80211 writes to this */ static struct ieee80211_rate wl1271_rates[] = { { .bitrate = 10, .hw_value = CONF_HW_BIT_RATE_1MBPS, .hw_value_short = CONF_HW_BIT_RATE_1MBPS, }, { .bitrate = 20, .hw_value = CONF_HW_BIT_RATE_2MBPS, .hw_value_short = CONF_HW_BIT_RATE_2MBPS, .flags = IEEE80211_RATE_SHORT_PREAMBLE }, { .bitrate = 55, .hw_value = CONF_HW_BIT_RATE_5_5MBPS, .hw_value_short = CONF_HW_BIT_RATE_5_5MBPS, .flags = IEEE80211_RATE_SHORT_PREAMBLE }, { .bitrate = 110, .hw_value = CONF_HW_BIT_RATE_11MBPS, .hw_value_short = CONF_HW_BIT_RATE_11MBPS, .flags = IEEE80211_RATE_SHORT_PREAMBLE }, { .bitrate = 60, .hw_value = CONF_HW_BIT_RATE_6MBPS, .hw_value_short = CONF_HW_BIT_RATE_6MBPS, }, { .bitrate = 90, .hw_value = CONF_HW_BIT_RATE_9MBPS, .hw_value_short = CONF_HW_BIT_RATE_9MBPS, }, { .bitrate = 120, .hw_value = CONF_HW_BIT_RATE_12MBPS, .hw_value_short = CONF_HW_BIT_RATE_12MBPS, }, { .bitrate = 180, .hw_value = CONF_HW_BIT_RATE_18MBPS, .hw_value_short = CONF_HW_BIT_RATE_18MBPS, }, { .bitrate = 240, .hw_value = CONF_HW_BIT_RATE_24MBPS, .hw_value_short = CONF_HW_BIT_RATE_24MBPS, }, { .bitrate = 360, .hw_value = CONF_HW_BIT_RATE_36MBPS, .hw_value_short = CONF_HW_BIT_RATE_36MBPS, }, { .bitrate = 480, .hw_value = CONF_HW_BIT_RATE_48MBPS, .hw_value_short = CONF_HW_BIT_RATE_48MBPS, }, { .bitrate = 540, .hw_value = CONF_HW_BIT_RATE_54MBPS, .hw_value_short = CONF_HW_BIT_RATE_54MBPS, }, }; /* can't be const, mac80211 writes to this */ static struct ieee80211_channel wl1271_channels[] = { { .hw_value = 1, .center_freq = 2412, .max_power = 25 }, { .hw_value = 2, .center_freq = 2417, .max_power = 25 }, { .hw_value = 3, .center_freq = 2422, .max_power = 25 }, { .hw_value = 4, .center_freq = 2427, .max_power = 25 }, { .hw_value = 5, .center_freq = 2432, .max_power = 25 }, { .hw_value = 6, .center_freq = 2437, .max_power = 25 }, { .hw_value = 7, .center_freq = 2442, .max_power = 25 }, { .hw_value = 8, .center_freq = 2447, .max_power = 25 }, { .hw_value = 9, .center_freq = 2452, .max_power = 25 }, { .hw_value = 10, .center_freq = 2457, .max_power = 25 }, { .hw_value = 11, .center_freq = 2462, .max_power = 25 }, { .hw_value = 12, .center_freq = 2467, .max_power = 25 }, { .hw_value = 13, .center_freq = 2472, .max_power = 25 }, { .hw_value = 14, .center_freq = 2484, .max_power = 25 }, }; /* mapping to indexes for wl1271_rates */ static const u8 wl1271_rate_to_idx_2ghz[] = { /* MCS rates are used only with 11n */ 7, /* CONF_HW_RXTX_RATE_MCS7_SGI */ 7, /* CONF_HW_RXTX_RATE_MCS7 */ 6, /* CONF_HW_RXTX_RATE_MCS6 */ 5, /* CONF_HW_RXTX_RATE_MCS5 */ 4, /* CONF_HW_RXTX_RATE_MCS4 */ 3, /* CONF_HW_RXTX_RATE_MCS3 */ 2, /* CONF_HW_RXTX_RATE_MCS2 */ 1, /* CONF_HW_RXTX_RATE_MCS1 */ 0, /* CONF_HW_RXTX_RATE_MCS0 */ 11, /* CONF_HW_RXTX_RATE_54 */ 10, /* CONF_HW_RXTX_RATE_48 */ 9, /* CONF_HW_RXTX_RATE_36 */ 8, /* CONF_HW_RXTX_RATE_24 */ /* TI-specific rate */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_22 */ 7, /* CONF_HW_RXTX_RATE_18 */ 6, /* CONF_HW_RXTX_RATE_12 */ 3, /* CONF_HW_RXTX_RATE_11 */ 5, /* CONF_HW_RXTX_RATE_9 */ 4, /* CONF_HW_RXTX_RATE_6 */ 2, /* CONF_HW_RXTX_RATE_5_5 */ 1, /* CONF_HW_RXTX_RATE_2 */ 0 /* CONF_HW_RXTX_RATE_1 */ }; /* 11n STA capabilities */ #define HW_RX_HIGHEST_RATE 72 #define WL12XX_HT_CAP { \ .cap = IEEE80211_HT_CAP_GRN_FLD | IEEE80211_HT_CAP_SGI_20 | \ (1 << IEEE80211_HT_CAP_RX_STBC_SHIFT), \ .ht_supported = true, \ .ampdu_factor = IEEE80211_HT_MAX_AMPDU_8K, \ .ampdu_density = IEEE80211_HT_MPDU_DENSITY_8, \ .mcs = { \ .rx_mask = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, \ .rx_highest = cpu_to_le16(HW_RX_HIGHEST_RATE), \ .tx_params = IEEE80211_HT_MCS_TX_DEFINED, \ }, \ } /* can't be const, mac80211 writes to this */ static struct ieee80211_supported_band wl1271_band_2ghz = { .channels = wl1271_channels, .n_channels = ARRAY_SIZE(wl1271_channels), .bitrates = wl1271_rates, .n_bitrates = ARRAY_SIZE(wl1271_rates), .ht_cap = WL12XX_HT_CAP, }; /* 5 GHz data rates for WL1273 */ static struct ieee80211_rate wl1271_rates_5ghz[] = { { .bitrate = 60, .hw_value = CONF_HW_BIT_RATE_6MBPS, .hw_value_short = CONF_HW_BIT_RATE_6MBPS, }, { .bitrate = 90, .hw_value = CONF_HW_BIT_RATE_9MBPS, .hw_value_short = CONF_HW_BIT_RATE_9MBPS, }, { .bitrate = 120, .hw_value = CONF_HW_BIT_RATE_12MBPS, .hw_value_short = CONF_HW_BIT_RATE_12MBPS, }, { .bitrate = 180, .hw_value = CONF_HW_BIT_RATE_18MBPS, .hw_value_short = CONF_HW_BIT_RATE_18MBPS, }, { .bitrate = 240, .hw_value = CONF_HW_BIT_RATE_24MBPS, .hw_value_short = CONF_HW_BIT_RATE_24MBPS, }, { .bitrate = 360, .hw_value = CONF_HW_BIT_RATE_36MBPS, .hw_value_short = CONF_HW_BIT_RATE_36MBPS, }, { .bitrate = 480, .hw_value = CONF_HW_BIT_RATE_48MBPS, .hw_value_short = CONF_HW_BIT_RATE_48MBPS, }, { .bitrate = 540, .hw_value = CONF_HW_BIT_RATE_54MBPS, .hw_value_short = CONF_HW_BIT_RATE_54MBPS, }, }; /* 5 GHz band channels for WL1273 */ static struct ieee80211_channel wl1271_channels_5ghz[] = { { .hw_value = 7, .center_freq = 5035, .max_power = 25 }, { .hw_value = 8, .center_freq = 5040, .max_power = 25 }, { .hw_value = 9, .center_freq = 5045, .max_power = 25 }, { .hw_value = 11, .center_freq = 5055, .max_power = 25 }, { .hw_value = 12, .center_freq = 5060, .max_power = 25 }, { .hw_value = 16, .center_freq = 5080, .max_power = 25 }, { .hw_value = 34, .center_freq = 5170, .max_power = 25 }, { .hw_value = 36, .center_freq = 5180, .max_power = 25 }, { .hw_value = 38, .center_freq = 5190, .max_power = 25 }, { .hw_value = 40, .center_freq = 5200, .max_power = 25 }, { .hw_value = 42, .center_freq = 5210, .max_power = 25 }, { .hw_value = 44, .center_freq = 5220, .max_power = 25 }, { .hw_value = 46, .center_freq = 5230, .max_power = 25 }, { .hw_value = 48, .center_freq = 5240, .max_power = 25 }, { .hw_value = 52, .center_freq = 5260, .max_power = 25 }, { .hw_value = 56, .center_freq = 5280, .max_power = 25 }, { .hw_value = 60, .center_freq = 5300, .max_power = 25 }, { .hw_value = 64, .center_freq = 5320, .max_power = 25 }, { .hw_value = 100, .center_freq = 5500, .max_power = 25 }, { .hw_value = 104, .center_freq = 5520, .max_power = 25 }, { .hw_value = 108, .center_freq = 5540, .max_power = 25 }, { .hw_value = 112, .center_freq = 5560, .max_power = 25 }, { .hw_value = 116, .center_freq = 5580, .max_power = 25 }, { .hw_value = 120, .center_freq = 5600, .max_power = 25 }, { .hw_value = 124, .center_freq = 5620, .max_power = 25 }, { .hw_value = 128, .center_freq = 5640, .max_power = 25 }, { .hw_value = 132, .center_freq = 5660, .max_power = 25 }, { .hw_value = 136, .center_freq = 5680, .max_power = 25 }, { .hw_value = 140, .center_freq = 5700, .max_power = 25 }, { .hw_value = 149, .center_freq = 5745, .max_power = 25 }, { .hw_value = 153, .center_freq = 5765, .max_power = 25 }, { .hw_value = 157, .center_freq = 5785, .max_power = 25 }, { .hw_value = 161, .center_freq = 5805, .max_power = 25 }, { .hw_value = 165, .center_freq = 5825, .max_power = 25 }, }; /* mapping to indexes for wl1271_rates_5ghz */ static const u8 wl1271_rate_to_idx_5ghz[] = { /* MCS rates are used only with 11n */ 7, /* CONF_HW_RXTX_RATE_MCS7_SGI */ 7, /* CONF_HW_RXTX_RATE_MCS7 */ 6, /* CONF_HW_RXTX_RATE_MCS6 */ 5, /* CONF_HW_RXTX_RATE_MCS5 */ 4, /* CONF_HW_RXTX_RATE_MCS4 */ 3, /* CONF_HW_RXTX_RATE_MCS3 */ 2, /* CONF_HW_RXTX_RATE_MCS2 */ 1, /* CONF_HW_RXTX_RATE_MCS1 */ 0, /* CONF_HW_RXTX_RATE_MCS0 */ 7, /* CONF_HW_RXTX_RATE_54 */ 6, /* CONF_HW_RXTX_RATE_48 */ 5, /* CONF_HW_RXTX_RATE_36 */ 4, /* CONF_HW_RXTX_RATE_24 */ /* TI-specific rate */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_22 */ 3, /* CONF_HW_RXTX_RATE_18 */ 2, /* CONF_HW_RXTX_RATE_12 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_11 */ 1, /* CONF_HW_RXTX_RATE_9 */ 0, /* CONF_HW_RXTX_RATE_6 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_5_5 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_2 */ CONF_HW_RXTX_RATE_UNSUPPORTED /* CONF_HW_RXTX_RATE_1 */ }; static struct ieee80211_supported_band wl1271_band_5ghz = { .channels = wl1271_channels_5ghz, .n_channels = ARRAY_SIZE(wl1271_channels_5ghz), .bitrates = wl1271_rates_5ghz, .n_bitrates = ARRAY_SIZE(wl1271_rates_5ghz), .ht_cap = WL12XX_HT_CAP, }; static const u8 *wl1271_band_rate_to_idx[] = { [IEEE80211_BAND_2GHZ] = wl1271_rate_to_idx_2ghz, [IEEE80211_BAND_5GHZ] = wl1271_rate_to_idx_5ghz }; static const struct ieee80211_ops wl1271_ops = { .start = wl1271_op_start, .stop = wl1271_op_stop, .add_interface = wl1271_op_add_interface, .remove_interface = wl1271_op_remove_interface, .change_interface = wl12xx_op_change_interface, #ifdef CONFIG_PM .suspend = wl1271_op_suspend, .resume = wl1271_op_resume, #endif .config = wl1271_op_config, .prepare_multicast = wl1271_op_prepare_multicast, .configure_filter = wl1271_op_configure_filter, .tx = wl1271_op_tx, .set_key = wl1271_op_set_key, .hw_scan = wl1271_op_hw_scan, .cancel_hw_scan = wl1271_op_cancel_hw_scan, .sched_scan_start = wl1271_op_sched_scan_start, .sched_scan_stop = wl1271_op_sched_scan_stop, .bss_info_changed = wl1271_op_bss_info_changed, .set_frag_threshold = wl1271_op_set_frag_threshold, .set_rts_threshold = wl1271_op_set_rts_threshold, .conf_tx = wl1271_op_conf_tx, .get_tsf = wl1271_op_get_tsf, .get_survey = wl1271_op_get_survey, .sta_state = wl12xx_op_sta_state, .ampdu_action = wl1271_op_ampdu_action, .tx_frames_pending = wl1271_tx_frames_pending, .set_bitrate_mask = wl12xx_set_bitrate_mask, .channel_switch = wl12xx_op_channel_switch, CFG80211_TESTMODE_CMD(wl1271_tm_cmd) }; u8 wl1271_rate_to_idx(int rate, enum ieee80211_band band) { u8 idx; BUG_ON(band >= sizeof(wl1271_band_rate_to_idx)/sizeof(u8 *)); if (unlikely(rate >= CONF_HW_RXTX_RATE_MAX)) { wl1271_error("Illegal RX rate from HW: %d", rate); return 0; } idx = wl1271_band_rate_to_idx[band][rate]; if (unlikely(idx == CONF_HW_RXTX_RATE_UNSUPPORTED)) { wl1271_error("Unsupported RX rate from HW: %d", rate); return 0; } return idx; } static ssize_t wl1271_sysfs_show_bt_coex_state(struct device *dev, struct device_attribute *attr, char *buf) { struct wl1271 *wl = dev_get_drvdata(dev); ssize_t len; len = PAGE_SIZE; mutex_lock(&wl->mutex); len = snprintf(buf, len, "%d\n\n0 - off\n1 - on\n", wl->sg_enabled); mutex_unlock(&wl->mutex); return len; } static ssize_t wl1271_sysfs_store_bt_coex_state(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct wl1271 *wl = dev_get_drvdata(dev); unsigned long res; int ret; ret = kstrtoul(buf, 10, &res); if (ret < 0) { wl1271_warning("incorrect value written to bt_coex_mode"); return count; } mutex_lock(&wl->mutex); res = !!res; if (res == wl->sg_enabled) goto out; wl->sg_enabled = res; if (wl->state == WL1271_STATE_OFF) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl1271_acx_sg_enable(wl, wl->sg_enabled); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return count; } static DEVICE_ATTR(bt_coex_state, S_IRUGO | S_IWUSR, wl1271_sysfs_show_bt_coex_state, wl1271_sysfs_store_bt_coex_state); static ssize_t wl1271_sysfs_show_hw_pg_ver(struct device *dev, struct device_attribute *attr, char *buf) { struct wl1271 *wl = dev_get_drvdata(dev); ssize_t len; len = PAGE_SIZE; mutex_lock(&wl->mutex); if (wl->hw_pg_ver >= 0) len = snprintf(buf, len, "%d\n", wl->hw_pg_ver); else len = snprintf(buf, len, "n/a\n"); mutex_unlock(&wl->mutex); return len; } static DEVICE_ATTR(hw_pg_ver, S_IRUGO, wl1271_sysfs_show_hw_pg_ver, NULL); static ssize_t wl1271_sysfs_read_fwlog(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buffer, loff_t pos, size_t count) { struct device *dev = container_of(kobj, struct device, kobj); struct wl1271 *wl = dev_get_drvdata(dev); ssize_t len; int ret; ret = mutex_lock_interruptible(&wl->mutex); if (ret < 0) return -ERESTARTSYS; /* Let only one thread read the log at a time, blocking others */ while (wl->fwlog_size == 0) { DEFINE_WAIT(wait); prepare_to_wait_exclusive(&wl->fwlog_waitq, &wait, TASK_INTERRUPTIBLE); if (wl->fwlog_size != 0) { finish_wait(&wl->fwlog_waitq, &wait); break; } mutex_unlock(&wl->mutex); schedule(); finish_wait(&wl->fwlog_waitq, &wait); if (signal_pending(current)) return -ERESTARTSYS; ret = mutex_lock_interruptible(&wl->mutex); if (ret < 0) return -ERESTARTSYS; } /* Check if the fwlog is still valid */ if (wl->fwlog_size < 0) { mutex_unlock(&wl->mutex); return 0; } /* Seeking is not supported - old logs are not kept. Disregard pos. */ len = min(count, (size_t)wl->fwlog_size); wl->fwlog_size -= len; memcpy(buffer, wl->fwlog, len); /* Make room for new messages */ memmove(wl->fwlog, wl->fwlog + len, wl->fwlog_size); mutex_unlock(&wl->mutex); return len; } static struct bin_attribute fwlog_attr = { .attr = {.name = "fwlog", .mode = S_IRUSR}, .read = wl1271_sysfs_read_fwlog, }; static bool wl12xx_mac_in_fuse(struct wl1271 *wl) { bool supported = false; u8 major, minor; if (wl->chip.id == CHIP_ID_1283_PG20) { major = WL128X_PG_GET_MAJOR(wl->hw_pg_ver); minor = WL128X_PG_GET_MINOR(wl->hw_pg_ver); /* in wl128x we have the MAC address if the PG is >= (2, 1) */ if (major > 2 || (major == 2 && minor >= 1)) supported = true; } else { major = WL127X_PG_GET_MAJOR(wl->hw_pg_ver); minor = WL127X_PG_GET_MINOR(wl->hw_pg_ver); /* in wl127x we have the MAC address if the PG is >= (3, 1) */ if (major == 3 && minor >= 1) supported = true; } wl1271_debug(DEBUG_PROBE, "PG Ver major = %d minor = %d, MAC %s present", major, minor, supported ? "is" : "is not"); return supported; } static void wl12xx_derive_mac_addresses(struct wl1271 *wl, u32 oui, u32 nic, int n) { int i; wl1271_debug(DEBUG_PROBE, "base address: oui %06x nic %06x, n %d", oui, nic, n); if (nic + n - 1 > 0xffffff) wl1271_warning("NIC part of the MAC address wraps around!"); for (i = 0; i < n; i++) { wl->addresses[i].addr[0] = (u8)(oui >> 16); wl->addresses[i].addr[1] = (u8)(oui >> 8); wl->addresses[i].addr[2] = (u8) oui; wl->addresses[i].addr[3] = (u8)(nic >> 16); wl->addresses[i].addr[4] = (u8)(nic >> 8); wl->addresses[i].addr[5] = (u8) nic; nic++; } wl->hw->wiphy->n_addresses = n; wl->hw->wiphy->addresses = wl->addresses; } static void wl12xx_get_fuse_mac(struct wl1271 *wl) { u32 mac1, mac2; wl1271_set_partition(wl, &wl12xx_part_table[PART_DRPW]); mac1 = wl1271_read32(wl, WL12XX_REG_FUSE_BD_ADDR_1); mac2 = wl1271_read32(wl, WL12XX_REG_FUSE_BD_ADDR_2); /* these are the two parts of the BD_ADDR */ wl->fuse_oui_addr = ((mac2 & 0xffff) << 8) + ((mac1 & 0xff000000) >> 24); wl->fuse_nic_addr = mac1 & 0xffffff; wl1271_set_partition(wl, &wl12xx_part_table[PART_DOWN]); } static int wl12xx_get_hw_info(struct wl1271 *wl) { int ret; u32 die_info; ret = wl12xx_set_power_on(wl); if (ret < 0) goto out; wl->chip.id = wl1271_read32(wl, CHIP_ID_B); if (wl->chip.id == CHIP_ID_1283_PG20) die_info = wl1271_top_reg_read(wl, WL128X_REG_FUSE_DATA_2_1); else die_info = wl1271_top_reg_read(wl, WL127X_REG_FUSE_DATA_2_1); wl->hw_pg_ver = (s8) (die_info & PG_VER_MASK) >> PG_VER_OFFSET; if (!wl12xx_mac_in_fuse(wl)) { wl->fuse_oui_addr = 0; wl->fuse_nic_addr = 0; } else { wl12xx_get_fuse_mac(wl); } wl1271_power_off(wl); out: return ret; } static int wl1271_register_hw(struct wl1271 *wl) { int ret; u32 oui_addr = 0, nic_addr = 0; if (wl->mac80211_registered) return 0; ret = wl12xx_get_hw_info(wl); if (ret < 0) { wl1271_error("couldn't get hw info"); goto out; } ret = wl1271_fetch_nvs(wl); if (ret == 0) { /* NOTE: The wl->nvs->nvs element must be first, in * order to simplify the casting, we assume it is at * the beginning of the wl->nvs structure. */ u8 *nvs_ptr = (u8 *)wl->nvs; oui_addr = (nvs_ptr[11] << 16) + (nvs_ptr[10] << 8) + nvs_ptr[6]; nic_addr = (nvs_ptr[5] << 16) + (nvs_ptr[4] << 8) + nvs_ptr[3]; } /* if the MAC address is zeroed in the NVS derive from fuse */ if (oui_addr == 0 && nic_addr == 0) { oui_addr = wl->fuse_oui_addr; /* fuse has the BD_ADDR, the WLAN addresses are the next two */ nic_addr = wl->fuse_nic_addr + 1; } wl12xx_derive_mac_addresses(wl, oui_addr, nic_addr, 2); ret = ieee80211_register_hw(wl->hw); if (ret < 0) { wl1271_error("unable to register mac80211 hw: %d", ret); goto out; } wl->mac80211_registered = true; wl1271_debugfs_init(wl); wl1271_notice("loaded"); out: return ret; } static void wl1271_unregister_hw(struct wl1271 *wl) { if (wl->plt) wl1271_plt_stop(wl); ieee80211_unregister_hw(wl->hw); wl->mac80211_registered = false; } static int wl1271_init_ieee80211(struct wl1271 *wl) { static const u32 cipher_suites[] = { WLAN_CIPHER_SUITE_WEP40, WLAN_CIPHER_SUITE_WEP104, WLAN_CIPHER_SUITE_TKIP, WLAN_CIPHER_SUITE_CCMP, WL1271_CIPHER_SUITE_GEM, }; /* The tx descriptor buffer and the TKIP space. */ wl->hw->extra_tx_headroom = WL1271_EXTRA_SPACE_TKIP + sizeof(struct wl1271_tx_hw_descr); /* unit us */ /* FIXME: find a proper value */ wl->hw->channel_change_time = 10000; wl->hw->max_listen_interval = wl->conf.conn.max_listen_interval; wl->hw->flags = IEEE80211_HW_SIGNAL_DBM | IEEE80211_HW_SUPPORTS_PS | IEEE80211_HW_SUPPORTS_DYNAMIC_PS | IEEE80211_HW_SUPPORTS_UAPSD | IEEE80211_HW_HAS_RATE_CONTROL | IEEE80211_HW_CONNECTION_MONITOR | IEEE80211_HW_REPORTS_TX_ACK_STATUS | IEEE80211_HW_SPECTRUM_MGMT | IEEE80211_HW_AP_LINK_PS | IEEE80211_HW_AMPDU_AGGREGATION | IEEE80211_HW_TX_AMPDU_SETUP_IN_HW | IEEE80211_HW_SCAN_WHILE_IDLE; wl->hw->wiphy->cipher_suites = cipher_suites; wl->hw->wiphy->n_cipher_suites = ARRAY_SIZE(cipher_suites); wl->hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) | BIT(NL80211_IFTYPE_ADHOC) | BIT(NL80211_IFTYPE_AP) | BIT(NL80211_IFTYPE_P2P_CLIENT) | BIT(NL80211_IFTYPE_P2P_GO); wl->hw->wiphy->max_scan_ssids = 1; wl->hw->wiphy->max_sched_scan_ssids = 16; wl->hw->wiphy->max_match_sets = 16; /* * Maximum length of elements in scanning probe request templates * should be the maximum length possible for a template, without * the IEEE80211 header of the template */ wl->hw->wiphy->max_scan_ie_len = WL1271_CMD_TEMPL_MAX_SIZE - sizeof(struct ieee80211_header); wl->hw->wiphy->max_sched_scan_ie_len = WL1271_CMD_TEMPL_MAX_SIZE - sizeof(struct ieee80211_header); wl->hw->wiphy->flags |= WIPHY_FLAG_AP_UAPSD; /* make sure all our channels fit in the scanned_ch bitmask */ BUILD_BUG_ON(ARRAY_SIZE(wl1271_channels) + ARRAY_SIZE(wl1271_channels_5ghz) > WL1271_MAX_CHANNELS); /* * We keep local copies of the band structs because we need to * modify them on a per-device basis. */ memcpy(&wl->bands[IEEE80211_BAND_2GHZ], &wl1271_band_2ghz, sizeof(wl1271_band_2ghz)); memcpy(&wl->bands[IEEE80211_BAND_5GHZ], &wl1271_band_5ghz, sizeof(wl1271_band_5ghz)); wl->hw->wiphy->bands[IEEE80211_BAND_2GHZ] = &wl->bands[IEEE80211_BAND_2GHZ]; wl->hw->wiphy->bands[IEEE80211_BAND_5GHZ] = &wl->bands[IEEE80211_BAND_5GHZ]; wl->hw->queues = 4; wl->hw->max_rates = 1; wl->hw->wiphy->reg_notifier = wl1271_reg_notify; /* the FW answers probe-requests in AP-mode */ wl->hw->wiphy->flags |= WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD; wl->hw->wiphy->probe_resp_offload = NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS | NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2 | NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P; SET_IEEE80211_DEV(wl->hw, wl->dev); wl->hw->sta_data_size = sizeof(struct wl1271_station); wl->hw->vif_data_size = sizeof(struct wl12xx_vif); wl->hw->max_rx_aggregation_subframes = 8; return 0; } #define WL1271_DEFAULT_CHANNEL 0 static struct ieee80211_hw *wl1271_alloc_hw(void) { struct ieee80211_hw *hw; struct wl1271 *wl; int i, j, ret; unsigned int order; BUILD_BUG_ON(AP_MAX_STATIONS > WL12XX_MAX_LINKS); hw = ieee80211_alloc_hw(sizeof(*wl), &wl1271_ops); if (!hw) { wl1271_error("could not alloc ieee80211_hw"); ret = -ENOMEM; goto err_hw_alloc; } wl = hw->priv; memset(wl, 0, sizeof(*wl)); INIT_LIST_HEAD(&wl->wlvif_list); wl->hw = hw; for (i = 0; i < NUM_TX_QUEUES; i++) for (j = 0; j < WL12XX_MAX_LINKS; j++) skb_queue_head_init(&wl->links[j].tx_queue[i]); skb_queue_head_init(&wl->deferred_rx_queue); skb_queue_head_init(&wl->deferred_tx_queue); INIT_DELAYED_WORK(&wl->elp_work, wl1271_elp_work); INIT_WORK(&wl->netstack_work, wl1271_netstack_work); INIT_WORK(&wl->tx_work, wl1271_tx_work); INIT_WORK(&wl->recovery_work, wl1271_recovery_work); INIT_DELAYED_WORK(&wl->scan_complete_work, wl1271_scan_complete_work); INIT_DELAYED_WORK(&wl->tx_watchdog_work, wl12xx_tx_watchdog_work); wl->freezable_wq = create_freezable_workqueue("wl12xx_wq"); if (!wl->freezable_wq) { ret = -ENOMEM; goto err_hw; } wl->channel = WL1271_DEFAULT_CHANNEL; wl->rx_counter = 0; wl->power_level = WL1271_DEFAULT_POWER_LEVEL; wl->band = IEEE80211_BAND_2GHZ; wl->flags = 0; wl->sg_enabled = true; wl->hw_pg_ver = -1; wl->ap_ps_map = 0; wl->ap_fw_ps_map = 0; wl->quirks = 0; wl->platform_quirks = 0; wl->sched_scanning = false; wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT; wl->system_hlid = WL12XX_SYSTEM_HLID; wl->active_sta_count = 0; wl->fwlog_size = 0; init_waitqueue_head(&wl->fwlog_waitq); /* The system link is always allocated */ __set_bit(WL12XX_SYSTEM_HLID, wl->links_map); memset(wl->tx_frames_map, 0, sizeof(wl->tx_frames_map)); for (i = 0; i < ACX_TX_DESCRIPTORS; i++) wl->tx_frames[i] = NULL; spin_lock_init(&wl->wl_lock); wl->state = WL1271_STATE_OFF; wl->fw_type = WL12XX_FW_TYPE_NONE; mutex_init(&wl->mutex); /* Apply default driver configuration. */ wl1271_conf_init(wl); order = get_order(WL1271_AGGR_BUFFER_SIZE); wl->aggr_buf = (u8 *)__get_free_pages(GFP_KERNEL, order); if (!wl->aggr_buf) { ret = -ENOMEM; goto err_wq; } wl->dummy_packet = wl12xx_alloc_dummy_packet(wl); if (!wl->dummy_packet) { ret = -ENOMEM; goto err_aggr; } /* Allocate one page for the FW log */ wl->fwlog = (u8 *)get_zeroed_page(GFP_KERNEL); if (!wl->fwlog) { ret = -ENOMEM; goto err_dummy_packet; } return hw; err_dummy_packet: dev_kfree_skb(wl->dummy_packet); err_aggr: free_pages((unsigned long)wl->aggr_buf, order); err_wq: destroy_workqueue(wl->freezable_wq); err_hw: wl1271_debugfs_exit(wl); ieee80211_free_hw(hw); err_hw_alloc: return ERR_PTR(ret); } static int wl1271_free_hw(struct wl1271 *wl) { /* Unblock any fwlog readers */ mutex_lock(&wl->mutex); wl->fwlog_size = -1; wake_up_interruptible_all(&wl->fwlog_waitq); mutex_unlock(&wl->mutex); device_remove_bin_file(wl->dev, &fwlog_attr); device_remove_file(wl->dev, &dev_attr_hw_pg_ver); device_remove_file(wl->dev, &dev_attr_bt_coex_state); free_page((unsigned long)wl->fwlog); dev_kfree_skb(wl->dummy_packet); free_pages((unsigned long)wl->aggr_buf, get_order(WL1271_AGGR_BUFFER_SIZE)); wl1271_debugfs_exit(wl); vfree(wl->fw); wl->fw = NULL; wl->fw_type = WL12XX_FW_TYPE_NONE; kfree(wl->nvs); wl->nvs = NULL; kfree(wl->fw_status); kfree(wl->tx_res_if); destroy_workqueue(wl->freezable_wq); ieee80211_free_hw(wl->hw); return 0; } static irqreturn_t wl12xx_hardirq(int irq, void *cookie) { struct wl1271 *wl = cookie; unsigned long flags; wl1271_debug(DEBUG_IRQ, "IRQ"); /* complete the ELP completion */ spin_lock_irqsave(&wl->wl_lock, flags); set_bit(WL1271_FLAG_IRQ_RUNNING, &wl->flags); if (wl->elp_compl) { complete(wl->elp_compl); wl->elp_compl = NULL; } if (test_bit(WL1271_FLAG_SUSPENDED, &wl->flags)) { /* don't enqueue a work right now. mark it as pending */ set_bit(WL1271_FLAG_PENDING_WORK, &wl->flags); wl1271_debug(DEBUG_IRQ, "should not enqueue work"); disable_irq_nosync(wl->irq); pm_wakeup_event(wl->dev, 0); spin_unlock_irqrestore(&wl->wl_lock, flags); return IRQ_HANDLED; } spin_unlock_irqrestore(&wl->wl_lock, flags); return IRQ_WAKE_THREAD; } static int __devinit wl12xx_probe(struct platform_device *pdev) { struct wl12xx_platform_data *pdata = pdev->dev.platform_data; struct ieee80211_hw *hw; struct wl1271 *wl; unsigned long irqflags; int ret = -ENODEV; hw = wl1271_alloc_hw(); if (IS_ERR(hw)) { wl1271_error("can't allocate hw"); ret = PTR_ERR(hw); goto out; } wl = hw->priv; wl->irq = platform_get_irq(pdev, 0); wl->ref_clock = pdata->board_ref_clock; wl->tcxo_clock = pdata->board_tcxo_clock; wl->platform_quirks = pdata->platform_quirks; wl->set_power = pdata->set_power; wl->dev = &pdev->dev; wl->if_ops = pdata->ops; platform_set_drvdata(pdev, wl); #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,32) irqflags = IRQF_TRIGGER_RISING; #else if (wl->platform_quirks & WL12XX_PLATFORM_QUIRK_EDGE_IRQ) irqflags = IRQF_TRIGGER_RISING; else irqflags = IRQF_TRIGGER_HIGH | IRQF_ONESHOT; #endif #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31) ret = compat_request_threaded_irq(&wl->irq_compat, wl->irq, wl12xx_hardirq, wl1271_irq, irqflags, pdev->name, wl); #else ret = request_threaded_irq(wl->irq, wl12xx_hardirq, wl1271_irq, irqflags, pdev->name, wl); #endif if (ret < 0) { wl1271_error("request_irq() failed: %d", ret); goto out_free_hw; } ret = enable_irq_wake(wl->irq); if (!ret) { wl->irq_wake_enabled = true; device_init_wakeup(wl->dev, 1); if (pdata->pwr_in_suspend) hw->wiphy->wowlan.flags = WIPHY_WOWLAN_ANY; } disable_irq(wl->irq); ret = wl1271_init_ieee80211(wl); if (ret) goto out_irq; ret = wl1271_register_hw(wl); if (ret) goto out_irq; /* Create sysfs file to control bt coex state */ ret = device_create_file(wl->dev, &dev_attr_bt_coex_state); if (ret < 0) { wl1271_error("failed to create sysfs file bt_coex_state"); goto out_irq; } /* Create sysfs file to get HW PG version */ ret = device_create_file(wl->dev, &dev_attr_hw_pg_ver); if (ret < 0) { wl1271_error("failed to create sysfs file hw_pg_ver"); goto out_bt_coex_state; } /* Create sysfs file for the FW log */ ret = device_create_bin_file(wl->dev, &fwlog_attr); if (ret < 0) { wl1271_error("failed to create sysfs file fwlog"); goto out_hw_pg_ver; } return 0; out_hw_pg_ver: device_remove_file(wl->dev, &dev_attr_hw_pg_ver); out_bt_coex_state: device_remove_file(wl->dev, &dev_attr_bt_coex_state); out_irq: #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31) compat_free_threaded_irq(&wl->irq_compat); #else free_irq(wl->irq, wl); #endif out_free_hw: wl1271_free_hw(wl); out: return ret; } static int __devexit wl12xx_remove(struct platform_device *pdev) { struct wl1271 *wl = platform_get_drvdata(pdev); if (wl->irq_wake_enabled) { device_init_wakeup(wl->dev, 0); disable_irq_wake(wl->irq); } wl1271_unregister_hw(wl); #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31) compat_free_threaded_irq(&wl->irq_compat); compat_destroy_threaded_irq(&wl->irq_compat); #else free_irq(wl->irq, wl); #endif wl1271_free_hw(wl); return 0; } #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30) static const struct platform_device_id wl12xx_id_table[] __devinitconst = { { "wl12xx", 0 }, { } /* Terminating Entry */ }; MODULE_DEVICE_TABLE(platform, wl12xx_id_table); #endif static struct platform_driver wl12xx_driver = { .probe = wl12xx_probe, .remove = __devexit_p(wl12xx_remove), #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30) .id_table = wl12xx_id_table, #endif .driver = { .name = "wl12xx_driver", .owner = THIS_MODULE, } }; static int __init wl12xx_init(void) { return platform_driver_register(&wl12xx_driver); } module_init(wl12xx_init); static void __exit wl12xx_exit(void) { platform_driver_unregister(&wl12xx_driver); } module_exit(wl12xx_exit); u32 wl12xx_debug_level = DEBUG_NONE; EXPORT_SYMBOL_GPL(wl12xx_debug_level); module_param_named(debug_level, wl12xx_debug_level, uint, S_IRUSR | S_IWUSR); MODULE_PARM_DESC(debug_level, "wl12xx debugging level"); module_param_named(fwlog, fwlog_param, charp, 0); MODULE_PARM_DESC(fwlog, "FW logger options: continuous, ondemand, dbgpins or disable"); module_param(bug_on_recovery, bool, S_IRUSR | S_IWUSR); MODULE_PARM_DESC(bug_on_recovery, "BUG() on fw recovery"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Luciano Coelho <coelho@ti.com>"); MODULE_AUTHOR("Juuso Oikarinen <juuso.oikarinen@nokia.com>");
TouchpadCM/compat-wireless-3.4-rc3-1
drivers/net/wireless/wl12xx/main.c
C
gpl-2.0
147,286
/* * CDE - Common Desktop Environment * * Copyright (c) 1993-2012, The Open Group. All rights reserved. * * These libraries and programs are free software; you can * redistribute them and/or modify them under the terms of the GNU * Lesser General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * These libraries and programs are distributed in the hope that * they 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 these librararies and programs; if not, write * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth * Floor, Boston, MA 02110-1301 USA */ /* * File: Symbolic.c $XConsortium: Symbolic.c /main/5 1996/09/27 19:00:23 drk $ * Language: C * * (c) Copyright 1988, Hewlett-Packard Company, all rights reserved. * * (c) Copyright 1993, 1994 Hewlett-Packard Company * * (c) Copyright 1993, 1994 International Business Machines Corp. * * (c) Copyright 1993, 1994 Sun Microsystems, Inc. * * (c) Copyright 1993, 1994 Novell, Inc. * */ #ifdef __osf__ #define SBSTDINC_H_NO_REDEFINE #endif #include <Dt/UserMsg.h> #include <bms/sbport.h> /* NOTE: sbport.h must be the first include. */ #include <assert.h> #include <bms/bms.h> #include <bms/XeUserMsg.h> #include <bms/MemoryMgr.h> #include <bms/Symbolic.h> #include <codelibs/stringx.h> /* strhash */ #include "DtSvcLock.h" /******************************************************************************/ /* HASHING */ /* This is the default symbol table to use */ /* --------------------------------------- */ #define XE_END_OF_HASH_TABLE (XeSymtabList) -1 static XeSymTable D_sym_table = NULL; typedef struct _unknown_entry_data { XeString name; } *unknown_entry_data; /******************************************************************************/ /* Symbol (hash) Table */ /*------------------------------------------------------------------------+*/ static unsigned int keyhash(XeSymTable t, void *key) /*------------------------------------------------------------------------+*/ { unsigned int hash; if (t->hash_fn) { hash = t->hash_fn( key, t->hashsize ); if (hash >= t->hashsize) _DtSimpleError(XeProgName, XeInternalError, NULL, (XeString) "Symbolic.c: Hash value from user hash function out of range", NULL); /* We don't come back from the error routine */ } else { hash = strhash( (const char *) key ); hash = hash & (t->hashsize - 1); } return hash; } /*------------------------------------------------------------------------+*/ static unsigned int trap_bad_hash_fn(void * UNUSED_PARM(ptr), unsigned int UNUSED_PARM(size)) /*------------------------------------------------------------------------+*/ { _DtSimpleError(XeProgName, XeInternalError, NULL, (XeString) "Symbolic.c: Hash table at must be power of 2", NULL); /* We don't come back from the error routine */ return 1; } /*------------------------------------------------------------------------+*/ XeSymTable Xe_new_symtab(unsigned int hashsize) /*------------------------------------------------------------------------+*/ /* Note, hashsize must be power of 2 if using default hash function */ { int i; XeSymTable t = (XeSymTable) XeMalloc( sizeof (struct _XeSymTable) ); t->hashsize = hashsize; t->list = (XeSymtabList *)XeMalloc( sizeof( XeSymtabList ) * hashsize ); for (i = 0; i < hashsize; i++) t->list[i] = (XeSymtabList)NULL; t->curr_list = XE_END_OF_HASH_TABLE; t->curr_hash = 0; Xe_set_sym_fns(t, (XeSymFn_cmp)NULL, (XeSymFn_init)NULL, (XeSymFn_clean)NULL, (XeSymFn_hash)NULL); /* If not a power of two, user better have a hash function */ /* that handles that. Install hash function trap so that if */ /* he does not install one, we catch it. */ /* --------------------------------------------------------- */ if (hashsize & (hashsize - 1)) t->hash_fn = trap_bad_hash_fn; return t; } /*------------------------------------------------------------------------+*/ XeSymTable Xe_default_symtab(void) /*------------------------------------------------------------------------+*/ { #define D_HASHSIZE 256 _DtSvcProcessLock(); if (D_sym_table) { _DtSvcProcessUnlock(); return D_sym_table; } D_sym_table = Xe_new_symtab(D_HASHSIZE); _DtSvcProcessUnlock(); return(D_sym_table); } /*------------------------------------------------------------------------+*/ static XeSymtabList NukeOneItem(XeSymTable t, XeSymtabList l) /*------------------------------------------------------------------------+*/ { XeSymtabList next; /* For standard XeSymbols: */ /* 1) Free the name */ /* 2) Call free function if configured */ /* 3) Free the XeSymbol entry */ /* ---------------------------------------- */ if (l->data_is_XeSymbol) { XeFree( ((XeSymbol)l->data)->name ); if (t->clean_fn) t->clean_fn( ((XeSymbol)l->data)->value ); XeFree( l->data ); } /* For "anysym" symbols: */ /* 1) Call free function if configured */ /* 2) If we malloced the data, free it */ /* ---------------------------------------- */ else { if (t->clean_fn) t->clean_fn( l->data ); if (l->data_is_malloc_mem) XeFree(l->data); } next = l->rest; XeFree(l); return next; } /*------------------------------------------------------------------------+*/ XeSymTable Xe_set_sym_fns(XeSymTable t, XeSymFn_cmp cmp_fn, XeSymFn_init init_fn, XeSymFn_clean clean_fn, XeSymFn_hash hash_fn) /*------------------------------------------------------------------------+*/ { if (!t) t = Xe_default_symtab(); t->cmp_fn = cmp_fn; t->init_fn = init_fn; t->clean_fn = clean_fn; t->hash_fn = hash_fn; return(t); } /*------------------------------------------------------------------------+*/ static XeSymbol make_sym(XeString name) /*------------------------------------------------------------------------+*/ { XeSymbol sym = Xe_make_struct(_XeSymbol); sym->name = strdup( name ); sym->value = (void*)NULL; return sym; } /*------------------------------------------------------------------------+*/ static void * intern_something(XeSymTable t, void * data, unsigned int size, Boolean is_XeSymbol, Boolean lookup_only, int *bucket) /*------------------------------------------------------------------------+*/ { unsigned int hash; XeSymtabList l; XeSymtabList l0; Boolean match; void * hash_key; /* If no cmp function assume first item of "data" is a string pointer */ /* ------------------------------------------------------------------ */ if (is_XeSymbol) hash_key = data; else hash_key = (t->hash_fn) ? data : ((unknown_entry_data) data)->name; hash = keyhash( t, hash_key ); l = t->list[hash]; if (bucket) *bucket = hash; for (l0 = NULL; l; l0 = l, l = l->rest) { void * cmp_key; void * cmp_key2; if (is_XeSymbol) cmp_key = data; else cmp_key = (t->cmp_fn) ? data : ((unknown_entry_data) data)->name; if (l->data_is_XeSymbol) cmp_key2 = ((XeSymbol) l->data)->name; else cmp_key2 = (t->cmp_fn) ? l->data : ((unknown_entry_data) l->data)->name; /* Use the "compare" function to see if we have a match on our key */ /* --------------------------------------------------------------- */ if (t->cmp_fn) match = (t->cmp_fn( cmp_key, cmp_key2 ) == 0); else match = (strcmp((const char *) cmp_key, (const char *)cmp_key2 ) == 0); if (match) return l->data; } /* If just doing a lookup, don't add a new symbol */ /* ---------------------------------------------- */ if (lookup_only) return (void *) NULL; /* There was no match. We need to create an entry in the hash table. */ /* ------------------------------------------------------------------ */ l = (XeSymtabList) XeMalloc( sizeof(struct _XeSymtabList) ); l->rest = (XeSymtabList)NULL; l->data_is_XeSymbol = is_XeSymbol; l->data_is_malloc_mem = FALSE; if (l0) l0->rest = l; else t->list[hash] = l; /* If we have a standard symbol, make the XeSymbol entry. */ /* -------------------------------------------------------- */ if (is_XeSymbol) { XeSymbol sym = make_sym((XeString)data); l->data = (void*) sym; if (t->init_fn) sym->value = t->init_fn( l->data, size /* will be 0 */ ); } else { /* 1) If "size" != 0, */ /* - malloc "size" bytes, */ /* - copy "data" into malloced space, */ /* - Save pointer to malloc space as user's data pointer */ /* Else */ /* - Save "data" as pointer to user's data */ /* 2) If a "init_fn" is configured, */ /* - call init_fn( user's data pointer, "size" ) */ /* - set user's data pointer to return value of init_fn */ /* ONLY if "size" was zero. */ /* */ /* If size is non zero AND there is a user's malloc function, */ /* beware that the return value from the malloc function is not*/ /* save anywhere by these routines. If size was zero, the */ /* return value of the user's function is kept. */ /* ------------------------------------------------------------------ */ if (size) { l->data = XeMalloc( size ); memcpy(l->data, data, size); l->data_is_malloc_mem = TRUE; } else l->data = data; if (t->init_fn) { void * new_data = t->init_fn( l->data, size ); if (!size) l->data = new_data; } } /* appended to the end of the hash chain (if any). */ /* --------------------------------------------------------------- */ t->curr_list = l; t->curr_hash = hash; #ifdef DEBUG printf("Added data %p in list[%d] @ %p\n", l->data, hash, l); #endif return l->data; } /*------------------------------------------------------------------------+*/ XeSymbol Xe_intern(XeSymTable t, ConstXeString const name) /*------------------------------------------------------------------------+*/ { if (!name) return (XeSymbol)NULL; if (!t) t = Xe_default_symtab(); return (XeSymbol)intern_something(t, (void *)name, 0, TRUE, FALSE, (int*)NULL); } /*------------------------------------------------------------------------+*/ XeSymbol Xe_lookup(XeSymTable t, ConstXeString const name) /*------------------------------------------------------------------------+*/ { if (!name) return (XeSymbol)NULL; if (!t) t = Xe_default_symtab(); return (XeSymbol)intern_something(t, (void *)name, 0, TRUE, TRUE, (int*)NULL); } /******************************************************************************/ /* LISTS */ /*------------------------------------------------------------------------+*/ XeList Xe_make_list(void * data, XeList rest) /*------------------------------------------------------------------------+*/ { XeList temp = Xe_make_struct(_XeList); temp->data = data; temp->rest = rest; return temp; } /******************************************************************************/ /* QUEUES */ /*------------------------------------------------------------------------+*/ XeQueue Xe_init_queue(XeQueue q, void * nullval) /*------------------------------------------------------------------------+*/ { q->head = 0; q->null = nullval; return q; } /*------------------------------------------------------------------------+*/ XeQueue Xe_make_queue(void * nullval) /*------------------------------------------------------------------------+*/ { return Xe_init_queue(Xe_make_struct(_XeQueue), nullval); } /*------------------------------------------------------------------------+*/ void * Xe_pop_queue(XeQueue q) /*------------------------------------------------------------------------+*/ { XeList head = q->head; if (head) { void * val = head->data; q->head = head->rest; XeFree(head); return val; } else return q->null; } /*------------------------------------------------------------------------+*/ void * Xe_delete_queue_element(XeQueue q, void * val) /*------------------------------------------------------------------------+*/ { XeList last = 0, head = q->head; while (head) if (head->data == val) { if (last) last->rest = head->rest; else q->head = head->rest; if (q->tail == head) q->tail = last; XeFree(head); return val; } else last = head, head = head->rest; return q->null; } /*------------------------------------------------------------------------+*/ void Xe_push_queue(XeQueue q, void * val) /*------------------------------------------------------------------------+*/ { XeList new_ptr = Xe_make_list(val, 0); if (q->head) q->tail->rest = new_ptr; else q->head = new_ptr; q->tail = new_ptr; } /*------------------------------------------------------------------------+*/ void Xe_release_queue(XeQueue q) /*------------------------------------------------------------------------+*/ { if (q) { while (q->head) Xe_pop_queue(q); XeFree(q); } }
sTeeLM/MINIME
toolkit/srpm/SOURCES/cde-2.2.4/lib/DtSvc/DtEncap/Symbolic.c
C
gpl-2.0
14,105
/* * Copyright (C) 2011-2014 MediaTek Inc. * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ /* ** Id: //Department/DaVinci/BRANCHES/MT6620_WIFI_DRIVER_V2_3/os/linux/gl_init.c#7 */ /*! \file gl_init.c \brief Main routines of Linux driver This file contains the main routines of Linux driver for MediaTek Inc. 802.11 Wireless LAN Adapters. */ /* ** Log: gl_init.c ** ** 09 03 2013 cp.wu ** add path for reassociation * * 07 17 2012 yuche.tsai * NULL * Fix compile error. * * 07 17 2012 yuche.tsai * NULL * Fix compile error for JB. * * 07 17 2012 yuche.tsai * NULL * Let netdev bring up. * * 07 17 2012 yuche.tsai * NULL * Compile no error before trial run. * * 06 13 2012 yuche.tsai * NULL * Update maintrunk driver. * Add support for driver compose assoc request frame. * * 05 25 2012 yuche.tsai * NULL * Fix reset KE issue. * * 05 11 2012 cp.wu * [WCXRP00001237] [MT6620 Wi-Fi][Driver] Show MAC address and MAC address source for ACS's convenience * show MAC address & source while initiliazation * * 03 02 2012 terry.wu * NULL * EXPORT_SYMBOL(rsnParseCheckForWFAInfoElem);. * * 03 02 2012 terry.wu * NULL * Snc CFG80211 modification for ICS migration from branch 2.2. * * 03 02 2012 terry.wu * NULL * Sync CFG80211 modification from branch 2,2. * * 03 02 2012 terry.wu * NULL * Enable CFG80211 Support. * * 12 22 2011 george.huang * [WCXRP00000905] [MT6628 Wi-Fi][FW] Code refinement for ROM/ RAM module dependency * using global variable instead of stack for setting wlanoidSetNetworkAddress(), due to buffer may be released before * TX thread handling * * 11 18 2011 yuche.tsai * NULL * CONFIG P2P support RSSI query, default turned off. * * 11 14 2011 yuche.tsai * [WCXRP00001107] [Volunteer Patch][Driver] Large Network Type index assert in FW issue. * Fix large network type index assert in FW issue. * * 11 14 2011 cm.chang * NULL * Fix compiling warning * * 11 11 2011 yuche.tsai * NULL * Fix work thread cancel issue. * * 11 10 2011 cp.wu * [WCXRP00001098] [MT6620 Wi-Fi][Driver] Replace printk by DBG LOG macros in linux porting layer * 1. eliminaite direct calls to printk in porting layer. * 2. replaced by DBGLOG, which would be XLOG on ALPS platforms. * * 10 06 2011 eddie.chen * [WCXRP00001027] [MT6628 Wi-Fi][Firmware/Driver] Tx fragmentation * Add rlmDomainGetChnlList symbol. * * 09 22 2011 cm.chang * NULL * Safer writng stype to avoid unitialized regitry structure * * 09 21 2011 cm.chang * [WCXRP00000969] [MT6620 Wi-Fi][Driver][FW] Channel list for 5G band based on country code * Avoid possible structure alignment problem * * 09 20 2011 chinglan.wang * [WCXRP00000989] [WiFi Direct] [Driver] Add a new io control API to start the formation for the sigma test. * . * * 09 08 2011 cm.chang * [WCXRP00000969] [MT6620 Wi-Fi][Driver][FW] Channel list for 5G band based on country code * Use new fields ucChannelListMap and ucChannelListIndex in NVRAM * * 08 31 2011 cm.chang * [WCXRP00000969] [MT6620 Wi-Fi][Driver][FW] Channel list for 5G band based on country code * . * * 08 11 2011 cp.wu * [WCXRP00000830] [MT6620 Wi-Fi][Firmware] Use MDRDY counter to detect empty channel for shortening scan time * expose scnQuerySparseChannel() for P2P-FSM. * * 08 11 2011 cp.wu * [WCXRP00000830] [MT6620 Wi-Fi][Firmware] Use MDRDY counter to detect empty channel for shortening scan time * sparse channel detection: * driver: collect sparse channel information with scan-done event * * 08 02 2011 yuche.tsai * [WCXRP00000896] [Volunteer Patch][WiFi Direct][Driver] GO with multiple client, TX deauth to a disconnecting * device issue. * Fix GO send deauth frame issue. * * 07 07 2011 wh.su * [WCXRP00000839] [MT6620 Wi-Fi][Driver] Add the dumpMemory8 and dumpMemory32 EXPORT_SYMBOL * Add the dumpMemory8 symbol export for debug mode. * * 07 06 2011 terry.wu * [WCXRP00000735] [MT6620 Wi-Fi][BoW][FW/Driver] Protect BoW connection establishment * Improve BoW connection establishment speed. * * 07 05 2011 yuche.tsai * [WCXRP00000821] [Volunteer Patch][WiFi Direct][Driver] WiFi Direct Connection Speed Issue * Export one symbol for enhancement. * * 06 13 2011 eddie.chen * [WCXRP00000779] [MT6620 Wi-Fi][DRV] Add tx rx statistics in linux and use netif_rx_ni * Add tx rx statistics and netif_rx_ni. * * 05 27 2011 cp.wu * [WCXRP00000749] [MT6620 Wi-Fi][Driver] Add band edge tx power control to Wi-Fi NVRAM * invoke CMD_ID_SET_EDGE_TXPWR_LIMIT when there is valid data exist in NVRAM content. * * 05 18 2011 cp.wu * [WCXRP00000734] [MT6620 Wi-Fi][Driver] Pass PHY_PARAM in NVRAM to firmware domain * pass PHY_PARAM in NVRAM from driver to firmware. * * 05 09 2011 jeffrey.chang * [WCXRP00000710] [MT6620 Wi-Fi] Support pattern filter update function on IP address change * support ARP filter through kernel notifier * * 05 03 2011 chinghwa.yu * [WCXRP00000065] Update BoW design and settings * Use kalMemAlloc to allocate event buffer for kalIndicateBOWEvent. * * 04 27 2011 george.huang * [WCXRP00000684] [MT6620 Wi-Fi][Driver] Support P2P setting ARP filter * Support P2P ARP filter setting on early suspend/ late resume * * 04 18 2011 terry.wu * [WCXRP00000660] [MT6620 Wi-Fi][Driver] Remove flag CFG_WIFI_DIRECT_MOVED * Remove flag CFG_WIFI_DIRECT_MOVED. * * 04 15 2011 chinghwa.yu * [WCXRP00000065] Update BoW design and settings * Add BOW short range mode. * * 04 14 2011 yuche.tsai * [WCXRP00000646] [Volunteer Patch][MT6620][FW/Driver] Sigma Test Modification for some test case. * Modify some driver connection flow or behavior to pass Sigma test more easier.. * * 04 12 2011 cm.chang * [WCXRP00000634] [MT6620 Wi-Fi][Driver][FW] 2nd BSS will not support 40MHz bandwidth for concurrency * . * * 04 11 2011 george.huang * [WCXRP00000621] [MT6620 Wi-Fi][Driver] Support P2P supplicant to set power mode * export wlan functions to p2p * * 04 08 2011 pat.lu * [WCXRP00000623] [MT6620 Wi-Fi][Driver] use ARCH define to distinguish PC Linux driver * Use CONFIG_X86 instead of PC_LINUX_DRIVER_USE option to have proper compile setting for PC Linux driver * * 04 08 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * glBusFreeIrq() should use the same pvCookie as glBusSetIrq() or request_irq()/free_irq() won't work as a pair. * * 04 08 2011 eddie.chen * [WCXRP00000617] [MT6620 Wi-Fi][DRV/FW] Fix for sigma * Fix for sigma * * 04 06 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * 1. do not check for pvData inside wlanNetCreate() due to it is NULL for eHPI port * 2. update perm_addr as well for MAC address * 3. not calling check_mem_region() anymore for eHPI * 4. correct MSC_CS macro for 0-based notation * * 03 29 2011 cp.wu * [WCXRP00000598] [MT6620 Wi-Fi][Driver] Implementation of interface for communicating with user space process for * RESET_START and RESET_END events * fix typo. * * 03 29 2011 cp.wu * [WCXRP00000598] [MT6620 Wi-Fi][Driver] Implementation of interface for communicating with user space process for * RESET_START and RESET_END events * implement kernel-to-userspace communication via generic netlink socket for whole-chip resetting mechanism * * 03 23 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * apply multi-queue operation only for linux kernel > 2.6.26 * * 03 22 2011 pat.lu * [WCXRP00000592] [MT6620 Wi-Fi][Driver] Support PC Linux Environment Driver Build * Add a compiler option "PC_LINUX_DRIVER_USE" for building driver in PC Linux environment. * * 03 21 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * portability for compatible with linux 2.6.12. * * 03 21 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * improve portability for awareness of early version of linux kernel and wireless extension. * * 03 21 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * portability improvement * * 03 18 2011 jeffrey.chang * [WCXRP00000512] [MT6620 Wi-Fi][Driver] modify the net device relative functions to support the H/W multiple queue * remove early suspend functions * * 03 17 2011 cp.wu * [WCXRP00000562] [MT6620 Wi-Fi][Driver] I/O buffer pre-allocation to avoid physically continuous memory shortage * after system running for a long period * reverse order to prevent probing racing. * * 03 16 2011 cp.wu * [WCXRP00000562] [MT6620 Wi-Fi][Driver] I/O buffer pre-allocation to avoid physically continuous memory shortage * after system running for a long period * 1. pre-allocate physical continuous buffer while module is being loaded * 2. use pre-allocated physical continuous buffer for TX/RX DMA transfer * * The windows part remained the same as before, but added similar APIs to hide the difference. * * 03 15 2011 jeffrey.chang * [WCXRP00000558] [MT6620 Wi-Fi][MT6620 Wi-Fi][Driver] refine the queue selection algorithm for WMM * refine the queue_select function * * 03 10 2011 cp.wu * [WCXRP00000532] [MT6620 Wi-Fi][Driver] Migrate NVRAM configuration procedures from MT6620 E2 to MT6620 E3 * deprecate configuration used by MT6620 E2 * * 03 10 2011 terry.wu * [WCXRP00000505] [MT6620 Wi-Fi][Driver/FW] WiFi Direct Integration * Remove unnecessary assert and message. * * 03 08 2011 terry.wu * [WCXRP00000505] [MT6620 Wi-Fi][Driver/FW] WiFi Direct Integration * Export nicQmUpdateWmmParms. * * 03 03 2011 jeffrey.chang * [WCXRP00000512] [MT6620 Wi-Fi][Driver] modify the net device relative functions to support the H/W multiple queue * support concurrent network * * 03 03 2011 jeffrey.chang * [WCXRP00000512] [MT6620 Wi-Fi][Driver] modify the net device relative functions to support the H/W multiple queue * modify net device relative functions to support multiple H/W queues * * 02 24 2011 george.huang * [WCXRP00000495] [MT6620 Wi-Fi][FW] Support pattern filter for unwanted ARP frames * Support ARP filter during suspended * * 02 21 2011 cp.wu * [WCXRP00000482] [MT6620 Wi-Fi][Driver] Simplify logic for checking NVRAM existence in driver domain * simplify logic for checking NVRAM existence only once. * * 02 17 2011 terry.wu * [WCXRP00000459] [MT6620 Wi-Fi][Driver] Fix deference null pointer problem in wlanRemove * Fix deference a null pointer problem in wlanRemove. * * 02 16 2011 jeffrey.chang * NULL * fix compilig error * * 02 16 2011 jeffrey.chang * NULL * Add query ipv4 and ipv6 address during early suspend and late resume * * 02 15 2011 jeffrey.chang * NULL * to support early suspend in android * * 02 11 2011 yuche.tsai * [WCXRP00000431] [Volunteer Patch][MT6620][Driver] Add MLME support for deauthentication under AP(Hot-Spot) mode. * Add one more export symbol. * * 02 10 2011 yuche.tsai * [WCXRP00000431] [Volunteer Patch][MT6620][Driver] Add MLME support for deauthentication under AP(Hot-Spot) mode. * Add RX deauthentication & disassociation process under Hot-Spot mode. * * 02 09 2011 terry.wu * [WCXRP00000383] [MT6620 Wi-Fi][Driver] Separate WiFi and P2P driver into two modules * Halt p2p module init and exit until TxThread finished p2p register and unregister. * * 02 08 2011 george.huang * [WCXRP00000422] [MT6620 Wi-Fi][Driver] support query power mode OID handler * Support querying power mode OID. * * 02 08 2011 yuche.tsai * [WCXRP00000421] [Volunteer Patch][MT6620][Driver] Fix incorrect SSID length Issue * Export Deactivation Network. * * 02 01 2011 jeffrey.chang * [WCXRP00000414] KAL Timer is not unregistered when driver not loaded * Unregister the KAL timer during driver unloading * * 01 26 2011 cm.chang * [WCXRP00000395] [MT6620 Wi-Fi][Driver][FW] Search STA_REC with additional net type index argument * Allocate system RAM if fixed message or mgmt buffer is not available * * 01 19 2011 cp.wu * [WCXRP00000371] [MT6620 Wi-Fi][Driver] make linux glue layer portable for Android 2.3.1 with Linux 2.6.35.7 * add compile option to check linux version 2.6.35 for different usage of system API to improve portability * * 01 12 2011 cp.wu * [WCXRP00000357] [MT6620 Wi-Fi][Driver][Bluetooth over Wi-Fi] add another net device interface for BT AMP * implementation of separate BT_OVER_WIFI data path. * * 01 10 2011 cp.wu * [WCXRP00000349] [MT6620 Wi-Fi][Driver] make kalIoctl() of linux port as a thread safe API to avoid potential issues * due to multiple access * use mutex to protect kalIoctl() for thread safe. * * 01 04 2011 cp.wu * [WCXRP00000338] [MT6620 Wi-Fi][Driver] Separate kalMemAlloc into kmalloc and vmalloc implementations to ease * physically continuous memory demands * separate kalMemAlloc() into virtually-continuous and physically-continuous type to ease slab system pressure * * 12 15 2010 cp.wu * [WCXRP00000265] [MT6620 Wi-Fi][Driver] Remove set_mac_address routine from legacy Wi-Fi Android driver * remove set MAC address. MAC address is always loaded from NVRAM instead. * * 12 10 2010 kevin.huang * [WCXRP00000128] [MT6620 Wi-Fi][Driver] Add proc support to Android Driver for debug and driver status check * Add Linux Proc Support * * 11 01 2010 yarco.yang * [WCXRP00000149] [MT6620 WI-Fi][Driver]Fine tune performance on MT6516 platform * Add GPIO debug function * * 11 01 2010 cp.wu * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000150] [MT6620 Wi-Fi][Driver] * Add implementation for querying current TX rate from firmware auto rate module * 1) Query link speed (TX rate) from firmware directly with buffering mechanism to reduce overhead * 2) Remove CNM CH-RECOVER event handling * 3) cfg read/write API renamed with kal prefix for unified naming rules. * * 10 26 2010 cp.wu * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000137] [MT6620 Wi-Fi] [FW] * Support NIC capability query command * 1) update NVRAM content template to ver 1.02 * 2) add compile option for querying NIC capability (default: off) * 3) modify AIS 5GHz support to run-time option, which could be turned on by registry or NVRAM setting * 4) correct auto-rate compiler error under linux (treat warning as error) * 5) simplify usage of NVRAM and REG_INFO_T * 6) add version checking between driver and firmware * * 10 21 2010 chinghwa.yu * [WCXRP00000065] Update BoW design and settings * . * * 10 19 2010 jeffrey.chang * [WCXRP00000120] [MT6620 Wi-Fi][Driver] Refine linux kernel module to the license of MTK propietary and enable MTK * HIF by default * Refine linux kernel module to the license of MTK and enable MTK HIF * * 10 18 2010 jeffrey.chang * [WCXRP00000106] [MT6620 Wi-Fi][Driver] Enable setting multicast callback in Android * . * * 10 18 2010 cp.wu * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000086] [MT6620 Wi-Fi][Driver] * The mac address is all zero at android * complete implementation of Android NVRAM access * * 09 27 2010 chinghwa.yu * [WCXRP00000063] Update BCM CoEx design and settings[WCXRP00000065] Update BoW design and settings * Update BCM/BoW design and settings. * * 09 23 2010 cp.wu * [WCXRP00000051] [MT6620 Wi-Fi][Driver] WHQL test fail in MAC address changed item * use firmware reported mac address right after wlanAdapterStart() as permanent address * * 09 21 2010 kevin.huang * [WCXRP00000052] [MT6620 Wi-Fi][Driver] Eliminate Linux Compile Warning * Eliminate Linux Compile Warning * * 09 03 2010 kevin.huang * NULL * Refine #include sequence and solve recursive/nested #include issue * * 09 01 2010 wh.su * NULL * adding the wapi support for integration test. * * 08 18 2010 yarco.yang * NULL * 1. Fixed HW checksum offload function not work under Linux issue. * 2. Add debug message. * * 08 16 2010 yarco.yang * NULL * Support Linux x86 * * 08 02 2010 jeffrey.chang * NULL * 1) modify tx service thread to avoid busy looping * 2) add spin lock declartion for linux build * * 07 29 2010 jeffrey.chang * NULL * fix memory leak for module unloading * * 07 28 2010 jeffrey.chang * NULL * 1) remove unused spinlocks * 2) enable encyption ioctls * 3) fix scan ioctl which may cause supplicant to hang * * 07 23 2010 jeffrey.chang * * bug fix: allocate regInfo when disabling firmware download * * 07 23 2010 jeffrey.chang * * use glue layer api to decrease or increase counter atomically * * 07 22 2010 jeffrey.chang * * add new spinlock * * 07 19 2010 jeffrey.chang * * modify cmd/data path for new design * * 07 08 2010 cp.wu * * [WPD00003833] [MT6620 and MT5931] Driver migration - move to new repository. * * 06 06 2010 kevin.huang * [WPD00003832][MT6620 5931] Create driver base * [MT6620 5931] Create driver base * * 05 26 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * 1) Modify set mac address code * 2) remove power management macro * * 05 10 2010 cp.wu * [WPD00003831][MT6620 Wi-Fi] Add framework for Wi-Fi Direct support * implement basic wi-fi direct framework * * 05 07 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * prevent supplicant accessing driver during resume * * 05 07 2010 cp.wu * [WPD00003831][MT6620 Wi-Fi] Add framework for Wi-Fi Direct support * add basic framework for implementating P2P driver hook. * * 04 27 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * 1) fix firmware download bug * 2) remove query statistics for acelerating firmware download * * 04 27 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * follow Linux's firmware framework, and remove unused kal API * * 04 21 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * add for private ioctl support * * 04 19 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * Query statistics from firmware * * 04 19 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * modify tcp/ip checksum offload flags * * 04 16 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * fix tcp/ip checksum offload bug * * 04 13 2010 cp.wu * [WPD00003823][MT6620 Wi-Fi] Add Bluetooth-over-Wi-Fi support * add framework for BT-over-Wi-Fi support. * * * * * * * * * * * * * * * * * 1) prPendingCmdInfo is replaced by queue for multiple handler * * * * * * * * * * * * * * * * * capability * * * * * * * * * * * * * * * * * 2) command sequence number is now increased atomically * * * * * * * * * * * * * * * * * 3) private data could be hold and taken use for other purpose * * 04 09 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * fix spinlock usage * * 04 07 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * Set MAC address from firmware * * 04 07 2010 cp.wu * [WPD00001943]Create WiFi test driver framework on WinXP * rWlanInfo should be placed at adapter rather than glue due to most operations * * * * * * are done in adapter layer. * * 04 07 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * (1)improve none-glue code portability * * (2) disable set Multicast address during atomic context * * 04 06 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * adding debug module * * 03 31 2010 wh.su * [WPD00003816][MT6620 Wi-Fi] Adding the security support * modify the wapi related code for new driver's design. * * 03 30 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * emulate NDIS Pending OID facility * * 03 26 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * fix f/w download start and load address by using config.h * * 03 26 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * [WPD00003826] Initial import for Linux port * adding firmware download support * * 03 24 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * initial import for Linux port ** \main\maintrunk.MT5921\52 2009-10-27 22:49:59 GMT mtk01090 ** Fix compile error for Linux EHPI driver ** \main\maintrunk.MT5921\51 2009-10-20 17:38:22 GMT mtk01090 ** Refine driver unloading and clean up procedure. Block requests, stop main thread and clean up queued requests, ** and then stop hw. ** \main\maintrunk.MT5921\50 2009-10-08 10:33:11 GMT mtk01090 ** Avoid accessing private data of net_device directly. Replace with netdev_priv(). Add more checking for input ** parameters and pointers. ** \main\maintrunk.MT5921\49 2009-09-28 20:19:05 GMT mtk01090 ** Add private ioctl to carry OID structures. Restructure public/private ioctl interfaces to Linux kernel. ** \main\maintrunk.MT5921\48 2009-09-03 13:58:46 GMT mtk01088 ** remove non-used code ** \main\maintrunk.MT5921\47 2009-09-03 11:40:25 GMT mtk01088 ** adding the module parameter for wapi ** \main\maintrunk.MT5921\46 2009-08-18 22:56:41 GMT mtk01090 ** Add Linux SDIO (with mmc core) support. ** Add Linux 2.6.21, 2.6.25, 2.6.26. ** Fix compile warning in Linux. ** \main\maintrunk.MT5921\45 2009-07-06 20:53:00 GMT mtk01088 ** adding the code to check the wapi 1x frame ** \main\maintrunk.MT5921\44 2009-06-23 23:18:55 GMT mtk01090 ** Add build option BUILD_USE_EEPROM and compile option CFG_SUPPORT_EXT_CONFIG for NVRAM support ** \main\maintrunk.MT5921\43 2009-02-16 23:46:51 GMT mtk01461 ** Revise the order of increasing u4TxPendingFrameNum because of CFG_TX_RET_TX_CTRL_EARLY ** \main\maintrunk.MT5921\42 2009-01-22 13:11:59 GMT mtk01088 ** set the tid and 1x value at same packet reserved field ** \main\maintrunk.MT5921\41 2008-10-20 22:43:53 GMT mtk01104 ** Fix wrong variable name "prDev" in wlanStop() ** \main\maintrunk.MT5921\40 2008-10-16 15:37:10 GMT mtk01461 ** add handle WLAN_STATUS_SUCCESS in wlanHardStartXmit() for CFG_TX_RET_TX_CTRL_EARLY ** \main\maintrunk.MT5921\39 2008-09-25 15:56:21 GMT mtk01461 ** Update driver for Code review ** \main\maintrunk.MT5921\38 2008-09-05 17:25:07 GMT mtk01461 ** Update Driver for Code Review ** \main\maintrunk.MT5921\37 2008-09-02 10:57:06 GMT mtk01461 ** Update driver for code review ** \main\maintrunk.MT5921\36 2008-08-05 01:53:28 GMT mtk01461 ** Add support for linux statistics ** \main\maintrunk.MT5921\35 2008-08-04 16:52:58 GMT mtk01461 ** Fix ASSERT if removing module in BG_SSID_SCAN state ** \main\maintrunk.MT5921\34 2008-06-13 22:52:24 GMT mtk01461 ** Revise status code handling in wlanHardStartXmit() for WLAN_STATUS_SUCCESS ** \main\maintrunk.MT5921\33 2008-05-30 18:56:53 GMT mtk01461 ** Not use wlanoidSetCurrentAddrForLinux() ** \main\maintrunk.MT5921\32 2008-05-30 14:39:40 GMT mtk01461 ** Remove WMM Assoc Flag ** \main\maintrunk.MT5921\31 2008-05-23 10:26:40 GMT mtk01084 ** modify wlanISR interface ** \main\maintrunk.MT5921\30 2008-05-03 18:52:36 GMT mtk01461 ** Fix Unset Broadcast filter when setMulticast ** \main\maintrunk.MT5921\29 2008-05-03 15:17:26 GMT mtk01461 ** Move Query Media Status to GLUE ** \main\maintrunk.MT5921\28 2008-04-24 22:48:21 GMT mtk01461 ** Revise set multicast function by using windows oid style for LP own back ** \main\maintrunk.MT5921\27 2008-04-24 12:00:08 GMT mtk01461 ** Fix multicast setting in Linux and add comment ** \main\maintrunk.MT5921\26 2008-03-28 10:40:22 GMT mtk01461 ** Fix set mac address func in Linux ** \main\maintrunk.MT5921\25 2008-03-26 15:37:26 GMT mtk01461 ** Add set MAC Address ** \main\maintrunk.MT5921\24 2008-03-26 14:24:53 GMT mtk01461 ** For Linux, set net_device has feature with checksum offload by default ** \main\maintrunk.MT5921\23 2008-03-11 14:50:52 GMT mtk01461 ** Fix typo ** \main\maintrunk.MT5921\22 2008-02-29 15:35:20 GMT mtk01088 ** add 1x decide code for sw port control ** \main\maintrunk.MT5921\21 2008-02-21 15:01:54 GMT mtk01461 ** Rearrange the set off place of GLUE spin lock in HardStartXmit ** \main\maintrunk.MT5921\20 2008-02-12 23:26:50 GMT mtk01461 ** Add debug option - Packet Order for Linux and add debug level - Event ** \main\maintrunk.MT5921\19 2007-12-11 00:11:12 GMT mtk01461 ** Fix SPIN_LOCK protection ** \main\maintrunk.MT5921\18 2007-11-30 17:02:25 GMT mtk01425 ** 1. Set Rx multicast packets mode before setting the address list ** \main\maintrunk.MT5921\17 2007-11-26 19:44:24 GMT mtk01461 ** Add OS_TIMESTAMP to packet ** \main\maintrunk.MT5921\16 2007-11-21 15:47:20 GMT mtk01088 ** fixed the unload module issue ** \main\maintrunk.MT5921\15 2007-11-07 18:37:38 GMT mtk01461 ** Fix compile warnning ** \main\maintrunk.MT5921\14 2007-11-02 01:03:19 GMT mtk01461 ** Unify TX Path for Normal and IBSS Power Save + IBSS neighbor learning ** \main\maintrunk.MT5921\13 2007-10-30 10:42:33 GMT mtk01425 ** 1. Refine for multicast list ** \main\maintrunk.MT5921\12 2007-10-25 18:08:13 GMT mtk01461 ** Add VOIP SCAN Support & Refine Roaming ** Revision 1.4 2007/07/05 07:25:33 MTK01461 ** Add Linux initial code, modify doc, add 11BB, RF init code ** ** Revision 1.3 2007/06/27 02:18:50 MTK01461 ** Update SCAN_FSM, Initial(Can Load Module), Proc(Can do Reg R/W), TX API ** ** Revision 1.2 2007/06/25 06:16:24 MTK01461 ** Update illustrations, gl_init.c, gl_kal.c, gl_kal.h, gl_os.h and RX API ** */ /******************************************************************************* * C O M P I L E R F L A G S ******************************************************************************** */ /******************************************************************************* * E X T E R N A L R E F E R E N C E S ******************************************************************************** */ #include "gl_os.h" #include "debug.h" #include "wlan_lib.h" #include "gl_wext.h" #include "gl_cfg80211.h" #include "precomp.h" #if CFG_SUPPORT_AGPS_ASSIST #include "gl_kal.h" #endif #if defined(CONFIG_MTK_TC1_FEATURE) #include <tc1_partition.h> #endif #include "gl_vendor.h" /******************************************************************************* * C O N S T A N T S ******************************************************************************** */ /* #define MAX_IOREQ_NUM 10 */ BOOLEAN fgIsUnderSuspend = false; struct semaphore g_halt_sem; int g_u4HaltFlag = 1; #if CFG_ENABLE_WIFI_DIRECT spinlock_t g_p2p_lock; int g_u4P2PEnding = 0; int g_u4P2POnOffing = 0; #endif /******************************************************************************* * D A T A T Y P E S ******************************************************************************** */ /* Tasklet mechanism is like buttom-half in Linux. We just want to * send a signal to OS for interrupt defer processing. All resources * are NOT allowed reentry, so txPacket, ISR-DPC and ioctl must avoid preempty. */ typedef struct _WLANDEV_INFO_T { struct net_device *prDev; } WLANDEV_INFO_T, *P_WLANDEV_INFO_T; /******************************************************************************* * P U B L I C D A T A ******************************************************************************** */ MODULE_AUTHOR(NIC_AUTHOR); MODULE_DESCRIPTION(NIC_DESC); MODULE_SUPPORTED_DEVICE(NIC_NAME); MODULE_LICENSE("GPL"); #define NIC_INF_NAME "wlan%d" /* interface name */ #if CFG_TC1_FEATURE #define NIC_INF_NAME_IN_AP_MODE "legacy%d" #endif /* support to change debug module info dynamically */ UINT_8 aucDebugModule[DBG_MODULE_NUM]; UINT_32 u4DebugModule = 0; /* 4 2007/06/26, mikewu, now we don't use this, we just fix the number of wlan device to 1 */ static WLANDEV_INFO_T arWlanDevInfo[CFG_MAX_WLAN_DEVICES] = { {0} }; static UINT_32 u4WlanDevNum; /* How many NICs coexist now */ /**20150205 added work queue for sched_scan to avoid cfg80211 stop schedule scan dead loack**/ struct delayed_work sched_workq; /******************************************************************************* * P R I V A T E D A T A ******************************************************************************** */ #if CFG_ENABLE_WIFI_DIRECT static SUB_MODULE_HANDLER rSubModHandler[SUB_MODULE_NUM] = { {NULL} }; #endif #define CHAN2G(_channel, _freq, _flags) \ { \ .band = IEEE80211_BAND_2GHZ, \ .center_freq = (_freq), \ .hw_value = (_channel), \ .flags = (_flags), \ .max_antenna_gain = 0, \ .max_power = 30, \ } static struct ieee80211_channel mtk_2ghz_channels[] = { CHAN2G(1, 2412, 0), CHAN2G(2, 2417, 0), CHAN2G(3, 2422, 0), CHAN2G(4, 2427, 0), CHAN2G(5, 2432, 0), CHAN2G(6, 2437, 0), CHAN2G(7, 2442, 0), CHAN2G(8, 2447, 0), CHAN2G(9, 2452, 0), CHAN2G(10, 2457, 0), CHAN2G(11, 2462, 0), CHAN2G(12, 2467, 0), CHAN2G(13, 2472, 0), CHAN2G(14, 2484, 0), }; #define CHAN5G(_channel, _flags) \ { \ .band = IEEE80211_BAND_5GHZ, \ .center_freq = 5000 + (5 * (_channel)), \ .hw_value = (_channel), \ .flags = (_flags), \ .max_antenna_gain = 0, \ .max_power = 30, \ } static struct ieee80211_channel mtk_5ghz_channels[] = { CHAN5G(34, 0), CHAN5G(36, 0), CHAN5G(38, 0), CHAN5G(40, 0), CHAN5G(42, 0), CHAN5G(44, 0), CHAN5G(46, 0), CHAN5G(48, 0), CHAN5G(52, 0), CHAN5G(56, 0), CHAN5G(60, 0), CHAN5G(64, 0), CHAN5G(100, 0), CHAN5G(104, 0), CHAN5G(108, 0), CHAN5G(112, 0), CHAN5G(116, 0), CHAN5G(120, 0), CHAN5G(124, 0), CHAN5G(128, 0), CHAN5G(132, 0), CHAN5G(136, 0), CHAN5G(140, 0), CHAN5G(149, 0), CHAN5G(153, 0), CHAN5G(157, 0), CHAN5G(161, 0), CHAN5G(165, 0), CHAN5G(169, 0), CHAN5G(173, 0), CHAN5G(184, 0), CHAN5G(188, 0), CHAN5G(192, 0), CHAN5G(196, 0), CHAN5G(200, 0), CHAN5G(204, 0), CHAN5G(208, 0), CHAN5G(212, 0), CHAN5G(216, 0), }; /* for cfg80211 - rate table */ static struct ieee80211_rate mtk_rates[] = { RATETAB_ENT(10, 0x1000, 0), RATETAB_ENT(20, 0x1001, 0), RATETAB_ENT(55, 0x1002, 0), RATETAB_ENT(110, 0x1003, 0), /* 802.11b */ RATETAB_ENT(60, 0x2000, 0), RATETAB_ENT(90, 0x2001, 0), RATETAB_ENT(120, 0x2002, 0), RATETAB_ENT(180, 0x2003, 0), RATETAB_ENT(240, 0x2004, 0), RATETAB_ENT(360, 0x2005, 0), RATETAB_ENT(480, 0x2006, 0), RATETAB_ENT(540, 0x2007, 0), /* 802.11a/g */ }; #define mtk_a_rates (mtk_rates + 4) #define mtk_a_rates_size (sizeof(mtk_rates) / sizeof(mtk_rates[0]) - 4) #define mtk_g_rates (mtk_rates + 0) #define mtk_g_rates_size (sizeof(mtk_rates) / sizeof(mtk_rates[0]) - 0) #define MT6620_MCS_INFO \ { \ .rx_mask = {0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0},\ .rx_highest = 0, \ .tx_params = IEEE80211_HT_MCS_TX_DEFINED, \ } #define MT6620_HT_CAP \ { \ .ht_supported = true, \ .cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 \ | IEEE80211_HT_CAP_SM_PS \ | IEEE80211_HT_CAP_GRN_FLD \ | IEEE80211_HT_CAP_SGI_20 \ | IEEE80211_HT_CAP_SGI_40, \ .ampdu_factor = IEEE80211_HT_MAX_AMPDU_64K, \ .ampdu_density = IEEE80211_HT_MPDU_DENSITY_NONE, \ .mcs = MT6620_MCS_INFO, \ } /* public for both Legacy Wi-Fi / P2P access */ struct ieee80211_supported_band mtk_band_2ghz = { .band = IEEE80211_BAND_2GHZ, .channels = mtk_2ghz_channels, .n_channels = ARRAY_SIZE(mtk_2ghz_channels), .bitrates = mtk_g_rates, .n_bitrates = mtk_g_rates_size, .ht_cap = MT6620_HT_CAP, }; /* public for both Legacy Wi-Fi / P2P access */ struct ieee80211_supported_band mtk_band_5ghz = { .band = IEEE80211_BAND_5GHZ, .channels = mtk_5ghz_channels, .n_channels = ARRAY_SIZE(mtk_5ghz_channels), .bitrates = mtk_a_rates, .n_bitrates = mtk_a_rates_size, .ht_cap = MT6620_HT_CAP, }; static const UINT_32 mtk_cipher_suites[] = { /* keep WEP first, it may be removed below */ WLAN_CIPHER_SUITE_WEP40, WLAN_CIPHER_SUITE_WEP104, WLAN_CIPHER_SUITE_TKIP, WLAN_CIPHER_SUITE_CCMP, /* keep last -- depends on hw flags! */ WLAN_CIPHER_SUITE_AES_CMAC }; static struct cfg80211_ops mtk_wlan_ops = { .suspend = mtk_cfg80211_suspend, .resume = mtk_cfg80211_resume, .change_virtual_intf = mtk_cfg80211_change_iface, .add_key = mtk_cfg80211_add_key, .get_key = mtk_cfg80211_get_key, .del_key = mtk_cfg80211_del_key, .set_default_key = mtk_cfg80211_set_default_key, .set_default_mgmt_key = mtk_cfg80211_set_default_mgmt_key, .get_station = mtk_cfg80211_get_station, .change_station = mtk_cfg80211_change_station, .add_station = mtk_cfg80211_add_station, .del_station = mtk_cfg80211_del_station, .scan = mtk_cfg80211_scan, .connect = mtk_cfg80211_connect, .disconnect = mtk_cfg80211_disconnect, .join_ibss = mtk_cfg80211_join_ibss, .leave_ibss = mtk_cfg80211_leave_ibss, .set_power_mgmt = mtk_cfg80211_set_power_mgmt, .set_pmksa = mtk_cfg80211_set_pmksa, .del_pmksa = mtk_cfg80211_del_pmksa, .flush_pmksa = mtk_cfg80211_flush_pmksa, .assoc = mtk_cfg80211_assoc, /* Action Frame TX/RX */ .remain_on_channel = mtk_cfg80211_remain_on_channel, .cancel_remain_on_channel = mtk_cfg80211_cancel_remain_on_channel, .mgmt_tx = mtk_cfg80211_mgmt_tx, /* .mgmt_tx_cancel_wait = mtk_cfg80211_mgmt_tx_cancel_wait, */ .mgmt_frame_register = mtk_cfg80211_mgmt_frame_register, #ifdef CONFIG_NL80211_TESTMODE .testmode_cmd = mtk_cfg80211_testmode_cmd, #endif #if (CFG_SUPPORT_TDLS == 1) .tdls_mgmt = TdlsexCfg80211TdlsMgmt, .tdls_oper = TdlsexCfg80211TdlsOper, #endif /* CFG_SUPPORT_TDLS */ #if 1 /* Remove schedule_scan because we need more verification for NLO */ .sched_scan_start = mtk_cfg80211_sched_scan_start, .sched_scan_stop = mtk_cfg80211_sched_scan_stop, #endif }; static const struct wiphy_vendor_command mtk_wlan_vendor_ops[] = { { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_GET_CAPABILITIES}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_get_gscan_capabilities}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_SET_CONFIG}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_set_config}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_SET_SCAN_CONFIG}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV, .doit = mtk_cfg80211_vendor_set_scan_config}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_ENABLE_GSCAN}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_enable_scan}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_ENABLE_FULL_SCAN_RESULTS}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_enable_full_scan_results}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_GET_SCAN_RESULTS}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_get_scan_results}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_GET_CHANNEL_LIST}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_get_channel_list}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_SET_SIGNIFICANT_CHANGE_CONFIG}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_set_significant_change}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_SET_HOTLIST}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_set_hotlist}, /*Link Layer Statistics */ { { .vendor_id = GOOGLE_OUI, .subcmd = LSTATS_SUBCMD_GET_INFO}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_llstats_get_info}, { { .vendor_id = GOOGLE_OUI, .subcmd = RTT_SUBCMD_GETCAPABILITY}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_get_rtt_capabilities}, }; static const struct nl80211_vendor_cmd_info mtk_wlan_vendor_events[] = { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_SIGNIFICANT_CHANGE_RESULTS}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_HOTLIST_RESULTS_FOUND}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_SCAN_RESULTS_AVAILABLE}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_FULL_SCAN_RESULTS}, { .vendor_id = GOOGLE_OUI, .subcmd = RTT_EVENT_COMPLETE}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_COMPLETE_SCAN}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_HOTLIST_RESULTS_LOST}, }; /* There isn't a lot of sense in it, but you can transmit anything you like */ static const struct ieee80211_txrx_stypes mtk_cfg80211_ais_default_mgmt_stypes[NUM_NL80211_IFTYPES] = { [NL80211_IFTYPE_ADHOC] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_ACTION >> 4) }, [NL80211_IFTYPE_STATION] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_ACTION >> 4) | BIT(IEEE80211_STYPE_PROBE_REQ >> 4) }, [NL80211_IFTYPE_AP] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_PROBE_REQ >> 4) | BIT(IEEE80211_STYPE_ACTION >> 4) }, [NL80211_IFTYPE_AP_VLAN] = { /* copy AP */ .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) | BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) | BIT(IEEE80211_STYPE_PROBE_REQ >> 4) | BIT(IEEE80211_STYPE_DISASSOC >> 4) | BIT(IEEE80211_STYPE_AUTH >> 4) | BIT(IEEE80211_STYPE_DEAUTH >> 4) | BIT(IEEE80211_STYPE_ACTION >> 4) }, [NL80211_IFTYPE_P2P_CLIENT] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_ACTION >> 4) | BIT(IEEE80211_STYPE_PROBE_REQ >> 4) }, [NL80211_IFTYPE_P2P_GO] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_PROBE_REQ >> 4) | BIT(IEEE80211_STYPE_ACTION >> 4) } }; /******************************************************************************* * M A C R O S ******************************************************************************** */ /******************************************************************************* * F U N C T I O N D E C L A R A T I O N S ******************************************************************************** */ /******************************************************************************* * F U N C T I O N S ******************************************************************************** */ /*----------------------------------------------------------------------------*/ /*! * \brief Override the implementation of select queue * * \param[in] dev Pointer to struct net_device * \param[in] skb Pointer to struct skb_buff * * \return (none) */ /*----------------------------------------------------------------------------*/ unsigned int _cfg80211_classify8021d(struct sk_buff *skb) { unsigned int dscp = 0; /* skb->priority values from 256->263 are magic values * directly indicate a specific 802.1d priority. This is * to allow 802.1d priority to be passed directly in from * tags */ if (skb->priority >= 256 && skb->priority <= 263) return skb->priority - 256; switch (skb->protocol) { case htons(ETH_P_IP): dscp = ip_hdr(skb)->tos & 0xfc; break; } return dscp >> 5; } static const UINT_16 au16Wlan1dToQueueIdx[8] = { 1, 0, 0, 1, 2, 2, 3, 3 }; static UINT_16 wlanSelectQueue(struct net_device *dev, struct sk_buff *skb, void *accel_priv, select_queue_fallback_t fallback) { skb->priority = _cfg80211_classify8021d(skb); return au16Wlan1dToQueueIdx[skb->priority]; } /*----------------------------------------------------------------------------*/ /*! * \brief Load NVRAM data and translate it into REG_INFO_T * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * \param[out] prRegInfo Pointer to struct REG_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ static void glLoadNvram(IN P_GLUE_INFO_T prGlueInfo, OUT P_REG_INFO_T prRegInfo) { UINT_32 i, j; UINT_8 aucTmp[2]; PUINT_8 pucDest; ASSERT(prGlueInfo); ASSERT(prRegInfo); if ((!prGlueInfo) || (!prRegInfo)) return; if (kalCfgDataRead16(prGlueInfo, sizeof(WIFI_CFG_PARAM_STRUCT) - sizeof(UINT_16), (PUINT_16) aucTmp) == TRUE) { prGlueInfo->fgNvramAvailable = TRUE; /* load MAC Address */ #if !defined(CONFIG_MTK_TC1_FEATURE) for (i = 0; i < PARAM_MAC_ADDR_LEN; i += sizeof(UINT_16)) { kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucMacAddress) + i, (PUINT_16) (((PUINT_8) prRegInfo->aucMacAddr) + i)); } #else TC1_FAC_NAME(FacReadWifiMacAddr) ((unsigned char *)prRegInfo->aucMacAddr); #endif /* load country code */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucCountryCode[0]), (PUINT_16) aucTmp); /* cast to wide characters */ prRegInfo->au2CountryCode[0] = (UINT_16) aucTmp[0]; prRegInfo->au2CountryCode[1] = (UINT_16) aucTmp[1]; /* load default normal TX power */ for (i = 0; i < sizeof(TX_PWR_PARAM_T); i += sizeof(UINT_16)) { kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, rTxPwr) + i, (PUINT_16) (((PUINT_8) &(prRegInfo->rTxPwr)) + i)); } /* load feature flags */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, ucTxPwrValid), (PUINT_16) aucTmp); prRegInfo->ucTxPwrValid = aucTmp[0]; prRegInfo->ucSupport5GBand = aucTmp[1]; kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, uc2G4BwFixed20M), (PUINT_16) aucTmp); prRegInfo->uc2G4BwFixed20M = aucTmp[0]; prRegInfo->uc5GBwFixed20M = aucTmp[1]; kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, ucEnable5GBand), (PUINT_16) aucTmp); prRegInfo->ucEnable5GBand = aucTmp[0]; /* load EFUSE overriding part */ for (i = 0; i < sizeof(prRegInfo->aucEFUSE); i += sizeof(UINT_16)) { kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucEFUSE) + i, (PUINT_16) (((PUINT_8) &(prRegInfo->aucEFUSE)) + i)); } /* load band edge tx power control */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, fg2G4BandEdgePwrUsed), (PUINT_16) aucTmp); prRegInfo->fg2G4BandEdgePwrUsed = (BOOLEAN) aucTmp[0]; if (aucTmp[0]) { prRegInfo->cBandEdgeMaxPwrCCK = (INT_8) aucTmp[1]; kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, cBandEdgeMaxPwrOFDM20), (PUINT_16) aucTmp); prRegInfo->cBandEdgeMaxPwrOFDM20 = (INT_8) aucTmp[0]; prRegInfo->cBandEdgeMaxPwrOFDM40 = (INT_8) aucTmp[1]; } /* load regulation subbands */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, ucRegChannelListMap), (PUINT_16) aucTmp); prRegInfo->eRegChannelListMap = (ENUM_REG_CH_MAP_T) aucTmp[0]; prRegInfo->ucRegChannelListIndex = aucTmp[1]; if (prRegInfo->eRegChannelListMap == REG_CH_MAP_CUSTOMIZED) { for (i = 0; i < MAX_SUBBAND_NUM; i++) { pucDest = (PUINT_8) &prRegInfo->rDomainInfo.rSubBand[i]; for (j = 0; j < 6; j += sizeof(UINT_16)) { kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucRegSubbandInfo) + (i * 6 + j), (PUINT_16) aucTmp); *pucDest++ = aucTmp[0]; *pucDest++ = aucTmp[1]; } } } /* load RSSI compensation */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, uc2GRssiCompensation), (PUINT_16) aucTmp); prRegInfo->uc2GRssiCompensation = aucTmp[0]; prRegInfo->uc5GRssiCompensation = aucTmp[1]; kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, fgRssiCompensationValidbit), (PUINT_16) aucTmp); prRegInfo->fgRssiCompensationValidbit = aucTmp[0]; prRegInfo->ucRxAntennanumber = aucTmp[1]; } else { prGlueInfo->fgNvramAvailable = FALSE; } } #if CFG_ENABLE_WIFI_DIRECT /*----------------------------------------------------------------------------*/ /*! * \brief called by txthread, run sub module init function * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ VOID wlanSubModRunInit(P_GLUE_INFO_T prGlueInfo) { /*now, we only have p2p module */ if (rSubModHandler[P2P_MODULE].fgIsInited == FALSE) { rSubModHandler[P2P_MODULE].subModInit(prGlueInfo); rSubModHandler[P2P_MODULE].fgIsInited = TRUE; } } /*----------------------------------------------------------------------------*/ /*! * \brief called by txthread, run sub module exit function * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ VOID wlanSubModRunExit(P_GLUE_INFO_T prGlueInfo) { /*now, we only have p2p module */ if (rSubModHandler[P2P_MODULE].fgIsInited == TRUE) { rSubModHandler[P2P_MODULE].subModExit(prGlueInfo); rSubModHandler[P2P_MODULE].fgIsInited = FALSE; } } /*----------------------------------------------------------------------------*/ /*! * \brief set sub module init flag, force TxThread to run sub modle init * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ BOOLEAN wlanSubModInit(P_GLUE_INFO_T prGlueInfo) { /* 4 Mark HALT, notify main thread to finish current job */ prGlueInfo->ulFlag |= GLUE_FLAG_SUB_MOD_INIT; /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); /* wait main thread finish sub module INIT */ wait_for_completion_interruptible(&prGlueInfo->rSubModComp); #if 0 if (prGlueInfo->prAdapter->fgIsP2PRegistered) p2pNetRegister(prGlueInfo); #endif return TRUE; } /*----------------------------------------------------------------------------*/ /*! * \brief set sub module exit flag, force TxThread to run sub modle exit * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ BOOLEAN wlanSubModExit(P_GLUE_INFO_T prGlueInfo) { #if 0 if (prGlueInfo->prAdapter->fgIsP2PRegistered) p2pNetUnregister(prGlueInfo); #endif /* 4 Mark HALT, notify main thread to finish current job */ prGlueInfo->ulFlag |= GLUE_FLAG_SUB_MOD_EXIT; /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); /* wait main thread finish sub module EXIT */ wait_for_completion_interruptible(&prGlueInfo->rSubModComp); return TRUE; } /*----------------------------------------------------------------------------*/ /*! * \brief set by sub module, indicate sub module is already inserted * * \param[in] rSubModInit, function pointer point to sub module init function * \param[in] rSubModExit, function pointer point to sub module exit function * \param[in] eSubModIdx, sub module index * * \return (none) */ /*----------------------------------------------------------------------------*/ VOID wlanSubModRegisterInitExit(SUB_MODULE_INIT rSubModInit, SUB_MODULE_EXIT rSubModExit, ENUM_SUB_MODULE_IDX_T eSubModIdx) { rSubModHandler[eSubModIdx].subModInit = rSubModInit; rSubModHandler[eSubModIdx].subModExit = rSubModExit; rSubModHandler[eSubModIdx].fgIsInited = FALSE; } #if 0 /*----------------------------------------------------------------------------*/ /*! * \brief check wlan is launched or not * * \param[in] (none) * * \return TRUE, wlan is already started * FALSE, wlan is not started yet */ /*----------------------------------------------------------------------------*/ BOOLEAN wlanIsLaunched(VOID) { struct net_device *prDev = NULL; P_GLUE_INFO_T prGlueInfo = NULL; /* 4 <0> Sanity check */ ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES); if (0 == u4WlanDevNum) return FALSE; prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; ASSERT(prDev); if (NULL == prDev) return FALSE; prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); if (NULL == prGlueInfo) return FALSE; return prGlueInfo->prAdapter->fgIsWlanLaunched; } #endif /*----------------------------------------------------------------------------*/ /*! * \brief Export wlan GLUE_INFO_T pointer to p2p module * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return TRUE: get GlueInfo pointer successfully * FALSE: wlan is not started yet */ /*---------------------------------------------------------------------------*/ BOOLEAN wlanExportGlueInfo(P_GLUE_INFO_T *prGlueInfoExpAddr) { struct net_device *prDev = NULL; P_GLUE_INFO_T prGlueInfo = NULL; if (0 == u4WlanDevNum) return FALSE; prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; if (NULL == prDev) return FALSE; prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); if (NULL == prGlueInfo) return FALSE; if (FALSE == prGlueInfo->prAdapter->fgIsWlanLaunched) return FALSE; *prGlueInfoExpAddr = prGlueInfo; return TRUE; } #endif /*----------------------------------------------------------------------------*/ /*! * \brief Release prDev from wlandev_array and free tasklet object related to it. * * \param[in] prDev Pointer to struct net_device * * \return (none) */ /*----------------------------------------------------------------------------*/ static void wlanClearDevIdx(struct net_device *prDev) { int i; ASSERT(prDev); for (i = 0; i < CFG_MAX_WLAN_DEVICES; i++) { if (arWlanDevInfo[i].prDev == prDev) { arWlanDevInfo[i].prDev = NULL; u4WlanDevNum--; } } } /* end of wlanClearDevIdx() */ /*----------------------------------------------------------------------------*/ /*! * \brief Allocate an unique interface index, net_device::ifindex member for this * wlan device. Store the net_device in wlandev_array, and initialize * tasklet object related to it. * * \param[in] prDev Pointer to struct net_device * * \retval >= 0 The device number. * \retval -1 Fail to get index. */ /*----------------------------------------------------------------------------*/ static int wlanGetDevIdx(struct net_device *prDev) { int i; ASSERT(prDev); for (i = 0; i < CFG_MAX_WLAN_DEVICES; i++) { if (arWlanDevInfo[i].prDev == (struct net_device *)NULL) { /* Reserve 2 bytes space to store one digit of * device number and NULL terminator. */ arWlanDevInfo[i].prDev = prDev; u4WlanDevNum++; return i; } } return -1; } /* end of wlanGetDevIdx() */ /*----------------------------------------------------------------------------*/ /*! * \brief A method of struct net_device, a primary SOCKET interface to configure * the interface lively. Handle an ioctl call on one of our devices. * Everything Linux ioctl specific is done here. Then we pass the contents * of the ifr->data to the request message handler. * * \param[in] prDev Linux kernel netdevice * * \param[in] prIFReq Our private ioctl request structure, typed for the generic * struct ifreq so we can use ptr to function * * \param[in] cmd Command ID * * \retval WLAN_STATUS_SUCCESS The IOCTL command is executed successfully. * \retval OTHER The execution of IOCTL command is failed. */ /*----------------------------------------------------------------------------*/ int wlanDoIOCTL(struct net_device *prDev, struct ifreq *prIFReq, int i4Cmd) { P_GLUE_INFO_T prGlueInfo = NULL; int ret = 0; /* Verify input parameters for the following functions */ ASSERT(prDev && prIFReq); if (!prDev || !prIFReq) { DBGLOG(INIT, WARN, "%s Invalid input data\n", __func__); return -EINVAL; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); if (!prGlueInfo) { DBGLOG(INIT, WARN, "%s No glue info\n", __func__); return -EFAULT; } if (prGlueInfo->u4ReadyFlag == 0) return -EINVAL; /* printk ("ioctl %x\n", i4Cmd); */ if (i4Cmd == SIOCGIWPRIV) { /* 0x8B0D, get private ioctl table */ ret = wext_get_priv(prDev, prIFReq); } else if ((i4Cmd >= SIOCIWFIRST) && (i4Cmd < SIOCIWFIRSTPRIV)) { /* 0x8B00 ~ 0x8BDF, wireless extension region */ ret = wext_support_ioctl(prDev, prIFReq, i4Cmd); } else if ((i4Cmd >= SIOCIWFIRSTPRIV) && (i4Cmd < SIOCIWLASTPRIV)) { /* 0x8BE0 ~ 0x8BFF, private ioctl region */ ret = priv_support_ioctl(prDev, prIFReq, i4Cmd); } else if (i4Cmd == SIOCDEVPRIVATE + 1) { ret = priv_support_driver_cmd(prDev, prIFReq, i4Cmd); } else { DBGLOG(INIT, WARN, "Unexpected ioctl command: 0x%04x\n", i4Cmd); /* return 0 for safe? */ } return ret; } /* end of wlanDoIOCTL() */ /*----------------------------------------------------------------------------*/ /*! * \brief This function is to set multicast list and set rx mode. * * \param[in] prDev Pointer to struct net_device * * \return (none) */ /*----------------------------------------------------------------------------*/ static struct delayed_work workq; static struct net_device *gPrDev; static BOOLEAN fgIsWorkMcStart = FALSE; static BOOLEAN fgIsWorkMcEverInit = FALSE; static struct wireless_dev *gprWdev; #ifdef CONFIG_PM static const struct wiphy_wowlan_support wlan_wowlan_support = { .flags = WIPHY_WOWLAN_DISCONNECT | WIPHY_WOWLAN_ANY, }; #endif static void createWirelessDevice(void) { struct wiphy *prWiphy = NULL; struct wireless_dev *prWdev = NULL; #if CFG_SUPPORT_PERSIST_NETDEV struct net_device *prNetDev = NULL; #endif /* <1.1> Create wireless_dev */ prWdev = kzalloc(sizeof(struct wireless_dev), GFP_KERNEL); if (!prWdev) { DBGLOG(INIT, ERROR, "Allocating memory to wireless_dev context failed\n"); return; } /* initialize semaphore for ioctl */ sema_init(&g_halt_sem, 1); g_u4HaltFlag = 1; /* <1.2> Create wiphy */ prWiphy = wiphy_new(&mtk_wlan_ops, sizeof(GLUE_INFO_T)); if (!prWiphy) { DBGLOG(INIT, ERROR, "Allocating memory to wiphy device failed\n"); goto free_wdev; } /* <1.3> configure wireless_dev & wiphy */ prWdev->iftype = NL80211_IFTYPE_STATION; prWiphy->max_scan_ssids = 1; /* FIXME: for combo scan */ prWiphy->max_scan_ie_len = 512; prWiphy->max_sched_scan_ssids = CFG_SCAN_SSID_MAX_NUM; prWiphy->max_match_sets = CFG_SCAN_SSID_MATCH_MAX_NUM; prWiphy->max_sched_scan_ie_len = CFG_CFG80211_IE_BUF_LEN; prWiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) | BIT(NL80211_IFTYPE_ADHOC); prWiphy->bands[IEEE80211_BAND_2GHZ] = &mtk_band_2ghz; /* always assign 5Ghz bands here, if the chip is not support 5Ghz, bands[IEEE80211_BAND_5GHZ] will be assign to NULL */ prWiphy->bands[IEEE80211_BAND_5GHZ] = &mtk_band_5ghz; prWiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM; prWiphy->cipher_suites = (const u32 *)mtk_cipher_suites; prWiphy->n_cipher_suites = ARRAY_SIZE(mtk_cipher_suites); prWiphy->flags = WIPHY_FLAG_SUPPORTS_FW_ROAM | WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL | WIPHY_FLAG_SUPPORTS_SCHED_SCAN; prWiphy->regulatory_flags = REGULATORY_CUSTOM_REG; #if (CFG_SUPPORT_TDLS == 1) TDLSEX_WIPHY_FLAGS_INIT(prWiphy->flags); #endif /* CFG_SUPPORT_TDLS */ prWiphy->max_remain_on_channel_duration = 5000; prWiphy->mgmt_stypes = mtk_cfg80211_ais_default_mgmt_stypes; prWiphy->vendor_commands = mtk_wlan_vendor_ops; prWiphy->n_vendor_commands = sizeof(mtk_wlan_vendor_ops) / sizeof(struct wiphy_vendor_command); prWiphy->vendor_events = mtk_wlan_vendor_events; prWiphy->n_vendor_events = ARRAY_SIZE(mtk_wlan_vendor_events); /* <1.4> wowlan support */ #ifdef CONFIG_PM prWiphy->wowlan = &wlan_wowlan_support; #endif #ifdef CONFIG_CFG80211_WEXT /* <1.5> Use wireless extension to replace IOCTL */ prWiphy->wext = &wext_handler_def; #endif if (wiphy_register(prWiphy) < 0) { DBGLOG(INIT, ERROR, "wiphy_register error\n"); goto free_wiphy; } prWdev->wiphy = prWiphy; #if CFG_SUPPORT_PERSIST_NETDEV /* <2> allocate and register net_device */ #if CFG_TC1_FEATURE if (wlan_if_changed) prNetDev = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME_IN_AP_MODE, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); else #else prNetDev = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); #endif if (!prNetDev) { DBGLOG(INIT, ERROR, "Allocating memory to net_device context failed\n"); goto unregister_wiphy; } *((P_GLUE_INFO_T *) netdev_priv(prNetDev)) = (P_GLUE_INFO_T) wiphy_priv(prWiphy); prNetDev->netdev_ops = &wlan_netdev_ops; #ifdef CONFIG_WIRELESS_EXT prNetDev->wireless_handlers = &wext_handler_def; #endif netif_carrier_off(prNetDev); netif_tx_stop_all_queues(prNetDev); /* <2.1> co-relate with wireless_dev bi-directionally */ prNetDev->ieee80211_ptr = prWdev; prWdev->netdev = prNetDev; #if CFG_TCP_IP_CHKSUM_OFFLOAD prNetDev->features = NETIF_F_HW_CSUM; #endif /* <2.2> co-relate net device & device tree */ SET_NETDEV_DEV(prNetDev, wiphy_dev(prWiphy)); /* <2.3> register net_device */ if (register_netdev(prWdev->netdev) < 0) { DBGLOG(INIT, ERROR, "wlanNetRegister: net_device context is not registered.\n"); goto unregister_wiphy; } #endif /* CFG_SUPPORT_PERSIST_NETDEV */ gprWdev = prWdev; DBGLOG(INIT, INFO, "create wireless device success\n"); return; #if CFG_SUPPORT_PERSIST_NETDEV unregister_wiphy: wiphy_unregister(prWiphy); #endif free_wiphy: wiphy_free(prWiphy); free_wdev: kfree(prWdev); } static void destroyWirelessDevice(void) { #if CFG_SUPPORT_PERSIST_NETDEV unregister_netdev(gprWdev->netdev); free_netdev(gprWdev->netdev); #endif wiphy_unregister(gprWdev->wiphy); wiphy_free(gprWdev->wiphy); kfree(gprWdev); gprWdev = NULL; } static void wlanSetMulticastList(struct net_device *prDev) { gPrDev = prDev; schedule_delayed_work(&workq, 0); } /* FIXME: Since we cannot sleep in the wlanSetMulticastList, we arrange * another workqueue for sleeping. We don't want to block * tx_thread, so we can't let tx_thread to do this */ static void wlanSetMulticastListWorkQueue(struct work_struct *work) { P_GLUE_INFO_T prGlueInfo = NULL; UINT_32 u4PacketFilter = 0; UINT_32 u4SetInfoLen; struct net_device *prDev = gPrDev; fgIsWorkMcStart = TRUE; DBGLOG(INIT, INFO, "wlanSetMulticastListWorkQueue start...\n"); down(&g_halt_sem); if (g_u4HaltFlag) { fgIsWorkMcStart = FALSE; up(&g_halt_sem); return; } prGlueInfo = (NULL != prDev) ? *((P_GLUE_INFO_T *) netdev_priv(prDev)) : NULL; ASSERT(prDev); ASSERT(prGlueInfo); if (!prDev || !prGlueInfo) { DBGLOG(INIT, WARN, "abnormal dev or skb: prDev(0x%p), prGlueInfo(0x%p)\n", prDev, prGlueInfo); fgIsWorkMcStart = FALSE; up(&g_halt_sem); return; } if (prDev->flags & IFF_PROMISC) u4PacketFilter |= PARAM_PACKET_FILTER_PROMISCUOUS; if (prDev->flags & IFF_BROADCAST) u4PacketFilter |= PARAM_PACKET_FILTER_BROADCAST; if (prDev->flags & IFF_MULTICAST) { if ((prDev->flags & IFF_ALLMULTI) || (netdev_mc_count(prDev) > MAX_NUM_GROUP_ADDR)) { u4PacketFilter |= PARAM_PACKET_FILTER_ALL_MULTICAST; } else { u4PacketFilter |= PARAM_PACKET_FILTER_MULTICAST; } } up(&g_halt_sem); if (kalIoctl(prGlueInfo, wlanoidSetCurrentPacketFilter, &u4PacketFilter, sizeof(u4PacketFilter), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen) != WLAN_STATUS_SUCCESS) { fgIsWorkMcStart = FALSE; return; } if (u4PacketFilter & PARAM_PACKET_FILTER_MULTICAST) { /* Prepare multicast address list */ struct netdev_hw_addr *ha; PUINT_8 prMCAddrList = NULL; UINT_32 i = 0; down(&g_halt_sem); if (g_u4HaltFlag) { fgIsWorkMcStart = FALSE; up(&g_halt_sem); return; } prMCAddrList = kalMemAlloc(MAX_NUM_GROUP_ADDR * ETH_ALEN, VIR_MEM_TYPE); netdev_for_each_mc_addr(ha, prDev) { if (i < MAX_NUM_GROUP_ADDR) { memcpy((prMCAddrList + i * ETH_ALEN), ha->addr, ETH_ALEN); i++; } } up(&g_halt_sem); kalIoctl(prGlueInfo, wlanoidSetMulticastList, prMCAddrList, (i * ETH_ALEN), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); kalMemFree(prMCAddrList, VIR_MEM_TYPE, MAX_NUM_GROUP_ADDR * ETH_ALEN); } fgIsWorkMcStart = FALSE; DBGLOG(INIT, INFO, "wlanSetMulticastListWorkQueue end\n"); } /* end of wlanSetMulticastList() */ /*----------------------------------------------------------------------------*/ /*! * \brief To indicate scheduled scan has been stopped * * \param[in] * prGlueInfo * * \return * None */ /*----------------------------------------------------------------------------*/ VOID wlanSchedScanStoppedWorkQueue(struct work_struct *work) { P_GLUE_INFO_T prGlueInfo = NULL; struct net_device *prDev = gPrDev; prGlueInfo = (NULL != prDev) ? *((P_GLUE_INFO_T *) netdev_priv(prDev)) : NULL; if (!prGlueInfo) { DBGLOG(SCN, ERROR, "prGlueInfo == NULL unexpected\n"); return; } /* 2. indication to cfg80211 */ /* 20150205 change cfg80211_sched_scan_stopped to work queue due to sched_scan_mtx dead lock issue */ cfg80211_sched_scan_stopped(priv_to_wiphy(prGlueInfo)); DBGLOG(SCN, INFO, "cfg80211_sched_scan_stopped event send done\n"); } /* FIXME: Since we cannot sleep in the wlanSetMulticastList, we arrange * another workqueue for sleeping. We don't want to block * tx_thread, so we can't let tx_thread to do this */ void p2pSetMulticastListWorkQueueWrapper(P_GLUE_INFO_T prGlueInfo) { ASSERT(prGlueInfo); if (!prGlueInfo) { DBGLOG(INIT, WARN, "abnormal dev or skb: prGlueInfo(0x%p)\n", prGlueInfo); return; } #if CFG_ENABLE_WIFI_DIRECT if (prGlueInfo->prAdapter->fgIsP2PRegistered) mtk_p2p_wext_set_Multicastlist(prGlueInfo); #endif } /* end of p2pSetMulticastListWorkQueueWrapper() */ /*----------------------------------------------------------------------------*/ /*! * \brief This function is TX entry point of NET DEVICE. * * \param[in] prSkb Pointer of the sk_buff to be sent * \param[in] prDev Pointer to struct net_device * * \retval NETDEV_TX_OK - on success. * \retval NETDEV_TX_BUSY - on failure, packet will be discarded by upper layer. */ /*----------------------------------------------------------------------------*/ int wlanHardStartXmit(struct sk_buff *prSkb, struct net_device *prDev) { P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); P_QUE_ENTRY_T prQueueEntry = NULL; P_QUE_T prTxQueue = NULL; UINT_16 u2QueueIdx = 0; #if (CFG_SUPPORT_TDLS_DBG == 1) UINT16 u2Identifier = 0; #endif #if CFG_BOW_TEST UINT_32 i; #endif GLUE_SPIN_LOCK_DECLARATION(); ASSERT(prSkb); ASSERT(prDev); ASSERT(prGlueInfo); #if (CFG_SUPPORT_TDLS_DBG == 1) { UINT8 *pkt = prSkb->data; if ((*(pkt + 12) == 0x08) && (*(pkt + 13) == 0x00)) { /* ip */ u2Identifier = ((*(pkt + 18)) << 8) | (*(pkt + 19)); /* u2TdlsTxSeq[u4TdlsTxSeqId ++] = u2Identifier; */ DBGLOG(INIT, INFO, "<s> %d\n", u2Identifier); } } #endif /* check if WiFi is halt */ if (prGlueInfo->ulFlag & GLUE_FLAG_HALT) { DBGLOG(INIT, INFO, "GLUE_FLAG_HALT skip tx\n"); dev_kfree_skb(prSkb); return NETDEV_TX_OK; } #if CFG_SUPPORT_HOTSPOT_2_0 if (prGlueInfo->fgIsDad) { /* kalPrint("[Passpoint R2] Due to ipv4_dad...TX is forbidden\n"); */ dev_kfree_skb(prSkb); return NETDEV_TX_OK; } if (prGlueInfo->fgIs6Dad) { /* kalPrint("[Passpoint R2] Due to ipv6_dad...TX is forbidden\n"); */ dev_kfree_skb(prSkb); return NETDEV_TX_OK; } #endif STATS_TX_TIME_ARRIVE(prSkb); prQueueEntry = (P_QUE_ENTRY_T) GLUE_GET_PKT_QUEUE_ENTRY(prSkb); prTxQueue = &prGlueInfo->rTxQueue; #if CFG_BOW_TEST DBGLOG(BOW, TRACE, "sk_buff->len: %d\n", prSkb->len); DBGLOG(BOW, TRACE, "sk_buff->data_len: %d\n", prSkb->data_len); DBGLOG(BOW, TRACE, "sk_buff->data:\n"); for (i = 0; i < prSkb->len; i++) { DBGLOG(BOW, TRACE, "%4x", prSkb->data[i]); if ((i + 1) % 16 == 0) DBGLOG(BOW, TRACE, "\n"); } DBGLOG(BOW, TRACE, "\n"); #endif if (wlanProcessSecurityFrame(prGlueInfo->prAdapter, (P_NATIVE_PACKET) prSkb) == FALSE) { /* non-1x packets */ #if CFG_DBG_GPIO_PINS { /* TX request from OS */ mtk_wcn_stp_debug_gpio_assert(IDX_TX_REQ, DBG_TIE_LOW); kalUdelay(1); mtk_wcn_stp_debug_gpio_assert(IDX_TX_REQ, DBG_TIE_HIGH); } #endif u2QueueIdx = skb_get_queue_mapping(prSkb); ASSERT(u2QueueIdx < CFG_MAX_TXQ_NUM); #if CFG_ENABLE_PKT_LIFETIME_PROFILE GLUE_SET_PKT_ARRIVAL_TIME(prSkb, kalGetTimeTick()); #endif GLUE_INC_REF_CNT(prGlueInfo->i4TxPendingFrameNum); if (u2QueueIdx < CFG_MAX_TXQ_NUM) GLUE_INC_REF_CNT(prGlueInfo->ai4TxPendingFrameNumPerQueue[NETWORK_TYPE_AIS_INDEX][u2QueueIdx]); GLUE_ACQUIRE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_TX_QUE); QUEUE_INSERT_TAIL(prTxQueue, prQueueEntry); GLUE_RELEASE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_TX_QUE); /* GLUE_INC_REF_CNT(prGlueInfo->i4TxPendingFrameNum); */ /* GLUE_INC_REF_CNT(prGlueInfo->ai4TxPendingFrameNumPerQueue[NETWORK_TYPE_AIS_INDEX][u2QueueIdx]); */ if (u2QueueIdx < CFG_MAX_TXQ_NUM) { if (prGlueInfo->ai4TxPendingFrameNumPerQueue[NETWORK_TYPE_AIS_INDEX][u2QueueIdx] >= CFG_TX_STOP_NETIF_PER_QUEUE_THRESHOLD) { netif_stop_subqueue(prDev, u2QueueIdx); #if (CONF_HIF_LOOPBACK_AUTO == 1) prGlueInfo->rHifInfo.HifLoopbkFlg |= 0x01; #endif /* CONF_HIF_LOOPBACK_AUTO */ } } } else { /* printk("is security frame\n"); */ GLUE_INC_REF_CNT(prGlueInfo->i4TxPendingSecurityFrameNum); } DBGLOG(TX, EVENT, "\n+++++ pending frame %d len = %d +++++\n", prGlueInfo->i4TxPendingFrameNum, prSkb->len); prGlueInfo->rNetDevStats.tx_bytes += prSkb->len; prGlueInfo->rNetDevStats.tx_packets++; if (netif_carrier_ok(prDev)) kalPerMonStart(prGlueInfo); /* set GLUE_FLAG_TXREQ_BIT */ /* pr->u4Flag |= GLUE_FLAG_TXREQ; */ /* wake_up_interruptible(&prGlueInfo->waitq); */ kalSetEvent(prGlueInfo); /* For Linux, we'll always return OK FLAG, because we'll free this skb by ourself */ return NETDEV_TX_OK; } /* end of wlanHardStartXmit() */ /*----------------------------------------------------------------------------*/ /*! * \brief A method of struct net_device, to get the network interface statistical * information. * * Whenever an application needs to get statistics for the interface, this method * is called. This happens, for example, when ifconfig or netstat -i is run. * * \param[in] prDev Pointer to struct net_device. * * \return net_device_stats buffer pointer. */ /*----------------------------------------------------------------------------*/ struct net_device_stats *wlanGetStats(IN struct net_device *prDev) { P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); #if 0 WLAN_STATUS rStatus; UINT_32 u4XmitError = 0; UINT_32 u4XmitOk = 0; UINT_32 u4RecvError = 0; UINT_32 u4RecvOk = 0; UINT_32 u4BufLen; ASSERT(prDev); /* @FIX ME: need a more clear way to do this */ rStatus = kalIoctl(prGlueInfo, wlanoidQueryXmitError, &u4XmitError, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen); rStatus = kalIoctl(prGlueInfo, wlanoidQueryXmitOk, &u4XmitOk, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen); rStatus = kalIoctl(prGlueInfo, wlanoidQueryRcvOk, &u4RecvOk, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen); rStatus = kalIoctl(prGlueInfo, wlanoidQueryRcvError, &u4RecvError, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen); prGlueInfo->rNetDevStats.rx_packets = u4RecvOk; prGlueInfo->rNetDevStats.tx_packets = u4XmitOk; prGlueInfo->rNetDevStats.tx_errors = u4XmitError; prGlueInfo->rNetDevStats.rx_errors = u4RecvError; /* prGlueInfo->rNetDevStats.rx_bytes = rCustomNetDevStats.u4RxBytes; */ /* prGlueInfo->rNetDevStats.tx_bytes = rCustomNetDevStats.u4TxBytes; */ /* prGlueInfo->rNetDevStats.rx_errors = rCustomNetDevStats.u4RxErrors; */ /* prGlueInfo->rNetDevStats.multicast = rCustomNetDevStats.u4Multicast; */ #endif /* prGlueInfo->rNetDevStats.rx_packets = 0; */ /* prGlueInfo->rNetDevStats.tx_packets = 0; */ prGlueInfo->rNetDevStats.tx_errors = 0; prGlueInfo->rNetDevStats.rx_errors = 0; /* prGlueInfo->rNetDevStats.rx_bytes = 0; */ /* prGlueInfo->rNetDevStats.tx_bytes = 0; */ prGlueInfo->rNetDevStats.rx_errors = 0; prGlueInfo->rNetDevStats.multicast = 0; return &prGlueInfo->rNetDevStats; } /* end of wlanGetStats() */ /*----------------------------------------------------------------------------*/ /*! * \brief A function for prDev->init * * \param[in] prDev Pointer to struct net_device. * * \retval 0 The execution of wlanInit succeeds. * \retval -ENXIO No such device. */ /*----------------------------------------------------------------------------*/ static int wlanInit(struct net_device *prDev) { P_GLUE_INFO_T prGlueInfo = NULL; if (fgIsWorkMcEverInit == FALSE) { if (!prDev) return -ENXIO; prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); INIT_DELAYED_WORK(&workq, wlanSetMulticastListWorkQueue); /* 20150205 work queue for sched_scan */ INIT_DELAYED_WORK(&sched_workq, wlanSchedScanStoppedWorkQueue); fgIsWorkMcEverInit = TRUE; } return 0; /* success */ } /* end of wlanInit() */ /*----------------------------------------------------------------------------*/ /*! * \brief A function for prDev->uninit * * \param[in] prDev Pointer to struct net_device. * * \return (none) */ /*----------------------------------------------------------------------------*/ static void wlanUninit(struct net_device *prDev) { } /* end of wlanUninit() */ /*----------------------------------------------------------------------------*/ /*! * \brief A function for prDev->open * * \param[in] prDev Pointer to struct net_device. * * \retval 0 The execution of wlanOpen succeeds. * \retval < 0 The execution of wlanOpen failed. */ /*----------------------------------------------------------------------------*/ static int wlanOpen(struct net_device *prDev) { ASSERT(prDev); netif_tx_start_all_queues(prDev); return 0; /* success */ } /* end of wlanOpen() */ /*----------------------------------------------------------------------------*/ /*! * \brief A function for prDev->stop * * \param[in] prDev Pointer to struct net_device. * * \retval 0 The execution of wlanStop succeeds. * \retval < 0 The execution of wlanStop failed. */ /*----------------------------------------------------------------------------*/ static int wlanStop(struct net_device *prDev) { P_GLUE_INFO_T prGlueInfo = NULL; struct cfg80211_scan_request *prScanRequest = NULL; GLUE_SPIN_LOCK_DECLARATION(); ASSERT(prDev); prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); /* CFG80211 down */ GLUE_ACQUIRE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_NET_DEV); if (prGlueInfo->prScanRequest != NULL) { prScanRequest = prGlueInfo->prScanRequest; prGlueInfo->prScanRequest = NULL; } GLUE_RELEASE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_NET_DEV); if (prScanRequest) cfg80211_scan_done(prScanRequest, TRUE); netif_tx_stop_all_queues(prDev); return 0; /* success */ } /* end of wlanStop() */ /*----------------------------------------------------------------------------*/ /*! * \brief Update Channel table for cfg80211 for Wi-Fi Direct based on current country code * * \param[in] prGlueInfo Pointer to glue info * * \return none */ /*----------------------------------------------------------------------------*/ VOID wlanUpdateChannelTable(P_GLUE_INFO_T prGlueInfo) { UINT_8 i, j; UINT_8 ucNumOfChannel; RF_CHANNEL_INFO_T aucChannelList[ARRAY_SIZE(mtk_2ghz_channels) + ARRAY_SIZE(mtk_5ghz_channels)]; /* 1. Disable all channel */ for (i = 0; i < ARRAY_SIZE(mtk_2ghz_channels); i++) { mtk_2ghz_channels[i].flags |= IEEE80211_CHAN_DISABLED; mtk_2ghz_channels[i].orig_flags |= IEEE80211_CHAN_DISABLED; } for (i = 0; i < ARRAY_SIZE(mtk_5ghz_channels); i++) { mtk_5ghz_channels[i].flags |= IEEE80211_CHAN_DISABLED; mtk_5ghz_channels[i].orig_flags |= IEEE80211_CHAN_DISABLED; } /* 2. Get current domain channel list */ rlmDomainGetChnlList(prGlueInfo->prAdapter, BAND_NULL, ARRAY_SIZE(mtk_2ghz_channels) + ARRAY_SIZE(mtk_5ghz_channels), &ucNumOfChannel, aucChannelList); /* 3. Enable specific channel based on domain channel list */ for (i = 0; i < ucNumOfChannel; i++) { switch (aucChannelList[i].eBand) { case BAND_2G4: for (j = 0; j < ARRAY_SIZE(mtk_2ghz_channels); j++) { if (mtk_2ghz_channels[j].hw_value == aucChannelList[i].ucChannelNum) { mtk_2ghz_channels[j].flags &= ~IEEE80211_CHAN_DISABLED; mtk_2ghz_channels[j].orig_flags &= ~IEEE80211_CHAN_DISABLED; break; } } break; case BAND_5G: for (j = 0; j < ARRAY_SIZE(mtk_5ghz_channels); j++) { if (mtk_5ghz_channels[j].hw_value == aucChannelList[i].ucChannelNum) { mtk_5ghz_channels[j].flags &= ~IEEE80211_CHAN_DISABLED; mtk_5ghz_channels[j].orig_flags &= ~IEEE80211_CHAN_DISABLED; break; } } break; default: break; } } } /*----------------------------------------------------------------------------*/ /*! * \brief Register the device to the kernel and return the index. * * \param[in] prDev Pointer to struct net_device. * * \retval 0 The execution of wlanNetRegister succeeds. * \retval < 0 The execution of wlanNetRegister failed. */ /*----------------------------------------------------------------------------*/ static INT_32 wlanNetRegister(struct wireless_dev *prWdev) { P_GLUE_INFO_T prGlueInfo; INT_32 i4DevIdx = -1; ASSERT(prWdev); do { if (!prWdev) break; prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); i4DevIdx = wlanGetDevIdx(prWdev->netdev); if (i4DevIdx < 0) { DBGLOG(INIT, ERROR, "wlanNetRegister: net_device number exceeds.\n"); break; } /* adjust channel support status */ wlanUpdateChannelTable(prGlueInfo); #if !CFG_SUPPORT_PERSIST_NETDEV if (register_netdev(prWdev->netdev) < 0) { DBGLOG(INIT, ERROR, "wlanNetRegister: net_device context is not registered.\n"); wiphy_unregister(prWdev->wiphy); wlanClearDevIdx(prWdev->netdev); i4DevIdx = -1; } #endif if (i4DevIdx != -1) prGlueInfo->fgIsRegistered = TRUE; } while (FALSE); return i4DevIdx; /* success */ } /* end of wlanNetRegister() */ /*----------------------------------------------------------------------------*/ /*! * \brief Unregister the device from the kernel * * \param[in] prWdev Pointer to struct net_device. * * \return (none) */ /*----------------------------------------------------------------------------*/ static VOID wlanNetUnregister(struct wireless_dev *prWdev) { P_GLUE_INFO_T prGlueInfo; if (!prWdev) { DBGLOG(INIT, ERROR, "wlanNetUnregister: The device context is NULL\n"); return; } DBGLOG(INIT, TRACE, "unregister net_dev(0x%p)\n", prWdev->netdev); prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); wlanClearDevIdx(prWdev->netdev); #if !CFG_SUPPORT_PERSIST_NETDEV unregister_netdev(prWdev->netdev); #endif prGlueInfo->fgIsRegistered = FALSE; DBGLOG(INIT, INFO, "unregister wireless_dev(0x%p), ifindex=%d\n", prWdev, prWdev->netdev->ifindex); } /* end of wlanNetUnregister() */ static const struct net_device_ops wlan_netdev_ops = { .ndo_open = wlanOpen, .ndo_stop = wlanStop, .ndo_set_rx_mode = wlanSetMulticastList, .ndo_get_stats = wlanGetStats, .ndo_do_ioctl = wlanDoIOCTL, .ndo_start_xmit = wlanHardStartXmit, .ndo_init = wlanInit, .ndo_uninit = wlanUninit, .ndo_select_queue = wlanSelectQueue, }; /*----------------------------------------------------------------------------*/ /*! * \brief A method for creating Linux NET4 struct net_device object and the * private data(prGlueInfo and prAdapter). Setup the IO address to the HIF. * Assign the function pointer to the net_device object * * \param[in] pvData Memory address for the device * * \retval Not null The wireless_dev object. * \retval NULL Fail to create wireless_dev object */ /*----------------------------------------------------------------------------*/ static struct lock_class_key rSpinKey[SPIN_LOCK_NUM]; static struct wireless_dev *wlanNetCreate(PVOID pvData) { P_GLUE_INFO_T prGlueInfo = NULL; struct wireless_dev *prWdev = gprWdev; UINT_32 i; struct device *prDev; if (!prWdev) { DBGLOG(INIT, ERROR, "Allocating memory to wireless_dev context failed\n"); return NULL; } /* 4 <1> co-relate wiphy & prDev */ #if MTK_WCN_HIF_SDIO mtk_wcn_hif_sdio_get_dev(*((MTK_WCN_HIF_SDIO_CLTCTX *) pvData), &prDev); #else /* prDev = &((struct sdio_func *) pvData)->dev; //samp */ prDev = pvData; /* samp */ #endif if (!prDev) DBGLOG(INIT, WARN, "unable to get struct dev for wlan\n"); /* don't set prDev as parent of wiphy->dev, because we have done device_add in driver init. if we set parent here, parent will be not able to know this child, and may occurs a KE in device_shutdown, to free wiphy->dev, because his parent has been freed. */ /*set_wiphy_dev(prWdev->wiphy, prDev);*/ #if !CFG_SUPPORT_PERSIST_NETDEV /* 4 <3> Initial Glue structure */ prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); kalMemZero(prGlueInfo, sizeof(GLUE_INFO_T)); /* 4 <3.1> Create net device */ #if CFG_TC1_FEATURE if (wlan_if_changed) { prGlueInfo->prDevHandler = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME_IN_AP_MODE, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); } else { prGlueInfo->prDevHandler = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); } #else prGlueInfo->prDevHandler = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); #endif if (!prGlueInfo->prDevHandler) { DBGLOG(INIT, ERROR, "Allocating memory to net_device context failed\n"); return NULL; } DBGLOG(INIT, INFO, "net_device prDev(0x%p) allocated ifindex=%d\n", prGlueInfo->prDevHandler, prGlueInfo->prDevHandler->ifindex); /* 4 <3.1.1> initialize net device varaiables */ *((P_GLUE_INFO_T *) netdev_priv(prGlueInfo->prDevHandler)) = prGlueInfo; prGlueInfo->prDevHandler->netdev_ops = &wlan_netdev_ops; #ifdef CONFIG_WIRELESS_EXT prGlueInfo->prDevHandler->wireless_handlers = &wext_handler_def; #endif netif_carrier_off(prGlueInfo->prDevHandler); netif_tx_stop_all_queues(prGlueInfo->prDevHandler); /* 4 <3.1.2> co-relate with wiphy bi-directionally */ prGlueInfo->prDevHandler->ieee80211_ptr = prWdev; #if CFG_TCP_IP_CHKSUM_OFFLOAD prGlueInfo->prDevHandler->features = NETIF_F_HW_CSUM; #endif prWdev->netdev = prGlueInfo->prDevHandler; /* 4 <3.1.3> co-relate net device & prDev */ /*SET_NETDEV_DEV(prGlueInfo->prDevHandler, wiphy_dev(prWdev->wiphy));*/ SET_NETDEV_DEV(prGlueInfo->prDevHandler, prDev); #else /* CFG_SUPPORT_PERSIST_NETDEV */ prGlueInfo->prDevHandler = gprWdev->netdev; #endif /* CFG_SUPPORT_PERSIST_NETDEV */ /* 4 <3.2> initiali glue variables */ prGlueInfo->eParamMediaStateIndicated = PARAM_MEDIA_STATE_DISCONNECTED; prGlueInfo->ePowerState = ParamDeviceStateD0; prGlueInfo->fgIsMacAddrOverride = FALSE; prGlueInfo->fgIsRegistered = FALSE; prGlueInfo->prScanRequest = NULL; #if CFG_SUPPORT_HOTSPOT_2_0 /* Init DAD */ prGlueInfo->fgIsDad = FALSE; prGlueInfo->fgIs6Dad = FALSE; kalMemZero(prGlueInfo->aucDADipv4, 4); kalMemZero(prGlueInfo->aucDADipv6, 16); #endif init_completion(&prGlueInfo->rScanComp); init_completion(&prGlueInfo->rHaltComp); init_completion(&prGlueInfo->rPendComp); #if CFG_ENABLE_WIFI_DIRECT init_completion(&prGlueInfo->rSubModComp); #endif /* initialize timer for OID timeout checker */ kalOsTimerInitialize(prGlueInfo, kalTimeoutHandler); for (i = 0; i < SPIN_LOCK_NUM; i++) { spin_lock_init(&prGlueInfo->rSpinLock[i]); lockdep_set_class(&prGlueInfo->rSpinLock[i], &rSpinKey[i]); } /* initialize semaphore for ioctl */ sema_init(&prGlueInfo->ioctl_sem, 1); glSetHifInfo(prGlueInfo, (ULONG) pvData); /* 4 <8> Init Queues */ init_waitqueue_head(&prGlueInfo->waitq); QUEUE_INITIALIZE(&prGlueInfo->rCmdQueue); QUEUE_INITIALIZE(&prGlueInfo->rTxQueue); /* 4 <4> Create Adapter structure */ prGlueInfo->prAdapter = (P_ADAPTER_T) wlanAdapterCreate(prGlueInfo); if (!prGlueInfo->prAdapter) { DBGLOG(INIT, ERROR, "Allocating memory to adapter failed\n"); return NULL; } KAL_WAKE_LOCK_INIT(prAdapter, &prGlueInfo->rAhbIsrWakeLock, "WLAN AHB ISR"); #if CFG_SUPPORT_PERSIST_NETDEV dev_open(prGlueInfo->prDevHandler); netif_carrier_off(prGlueInfo->prDevHandler); netif_tx_stop_all_queues(prGlueInfo->prDevHandler); #endif return prWdev; } /* end of wlanNetCreate() */ /*----------------------------------------------------------------------------*/ /*! * \brief Destroying the struct net_device object and the private data. * * \param[in] prWdev Pointer to struct wireless_dev. * * \return (none) */ /*----------------------------------------------------------------------------*/ static VOID wlanNetDestroy(struct wireless_dev *prWdev) { P_GLUE_INFO_T prGlueInfo = NULL; ASSERT(prWdev); if (!prWdev) { DBGLOG(INIT, ERROR, "wlanNetDestroy: The device context is NULL\n"); return; } /* prGlueInfo is allocated with net_device */ prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); ASSERT(prGlueInfo); /* destroy kal OS timer */ kalCancelTimer(prGlueInfo); glClearHifInfo(prGlueInfo); wlanAdapterDestroy(prGlueInfo->prAdapter); prGlueInfo->prAdapter = NULL; #if CFG_SUPPORT_PERSIST_NETDEV /* take the net_device to down state */ dev_close(prGlueInfo->prDevHandler); #else /* Free net_device and private data prGlueInfo, which are allocated by alloc_netdev(). */ free_netdev(prWdev->netdev); #endif } /* end of wlanNetDestroy() */ #ifndef CONFIG_X86 UINT_8 g_aucBufIpAddr[32] = { 0 }; static void wlanNotifyFwSuspend(P_GLUE_INFO_T prGlueInfo, BOOLEAN fgSuspend) { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; UINT_32 u4SetInfoLen; rStatus = kalIoctl(prGlueInfo, wlanoidNotifyFwSuspend, (PVOID)&fgSuspend, sizeof(fgSuspend), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); if (rStatus != WLAN_STATUS_SUCCESS) DBGLOG(INIT, INFO, "wlanNotifyFwSuspend fail\n"); } void wlanHandleSystemSuspend(void) { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; struct net_device *prDev = NULL; P_GLUE_INFO_T prGlueInfo = NULL; UINT_8 ip[4] = { 0 }; UINT_32 u4NumIPv4 = 0; #ifdef CONFIG_IPV6 UINT_8 ip6[16] = { 0 }; /* FIX ME: avoid to allocate large memory in stack */ UINT_32 u4NumIPv6 = 0; #endif UINT_32 i; P_PARAM_NETWORK_ADDRESS_IP prParamIpAddr; #if CFG_SUPPORT_DROP_MC_PACKET UINT_32 u4PacketFilter = 0; UINT_32 u4SetInfoLen = 0; #endif /* <1> Sanity check and acquire the net_device */ ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES); if (u4WlanDevNum == 0) { DBGLOG(INIT, ERROR, "wlanEarlySuspend u4WlanDevNum==0 invalid!!\n"); return; } prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; fgIsUnderSuspend = true; prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); #if CFG_SUPPORT_DROP_MC_PACKET /* new filter should not include p2p mask */ #if CFG_ENABLE_WIFI_DIRECT_CFG_80211 u4PacketFilter = prGlueInfo->prAdapter->u4OsPacketFilter & (~PARAM_PACKET_FILTER_P2P_MASK); #endif if (kalIoctl(prGlueInfo, wlanoidSetCurrentPacketFilter, &u4PacketFilter, sizeof(u4PacketFilter), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen) != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, ERROR, "set packet filter failed.\n"); } #endif if (!prDev || !(prDev->ip_ptr) || !((struct in_device *)(prDev->ip_ptr))->ifa_list || !(&(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local))) { goto notify_suspend; } kalMemCopy(ip, &(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local), sizeof(ip)); /* todo: traverse between list to find whole sets of IPv4 addresses */ if (!((ip[0] == 0) && (ip[1] == 0) && (ip[2] == 0) && (ip[3] == 0))) u4NumIPv4++; #ifdef CONFIG_IPV6 if (!prDev || !(prDev->ip6_ptr) || !((struct in_device *)(prDev->ip6_ptr))->ifa_list || !(&(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local))) { goto notify_suspend; } kalMemCopy(ip6, &(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local), sizeof(ip6)); DBGLOG(INIT, INFO, "ipv6 is %d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d\n", ip6[0], ip6[1], ip6[2], ip6[3], ip6[4], ip6[5], ip6[6], ip6[7], ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15] ); /* todo: traverse between list to find whole sets of IPv6 addresses */ if (!((ip6[0] == 0) && (ip6[1] == 0) && (ip6[2] == 0) && (ip6[3] == 0) && (ip6[4] == 0) && (ip6[5] == 0))) { /* Do nothing */ /* u4NumIPv6++; */ } #endif /* <7> set up the ARP filter */ { UINT_32 u4SetInfoLen = 0; UINT_32 u4Len = OFFSET_OF(PARAM_NETWORK_ADDRESS_LIST, arAddress); P_PARAM_NETWORK_ADDRESS_LIST prParamNetAddrList = (P_PARAM_NETWORK_ADDRESS_LIST) g_aucBufIpAddr; P_PARAM_NETWORK_ADDRESS prParamNetAddr = prParamNetAddrList->arAddress; kalMemZero(g_aucBufIpAddr, sizeof(g_aucBufIpAddr)); prParamNetAddrList->u4AddressCount = u4NumIPv4 + u4NumIPv6; prParamNetAddrList->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP; for (i = 0; i < u4NumIPv4; i++) { prParamNetAddr->u2AddressLength = sizeof(PARAM_NETWORK_ADDRESS_IP); /* 4;; */ prParamNetAddr->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP; prParamIpAddr = (P_PARAM_NETWORK_ADDRESS_IP) prParamNetAddr->aucAddress; kalMemCopy(&prParamIpAddr->in_addr, ip, sizeof(ip)); prParamNetAddr = (P_PARAM_NETWORK_ADDRESS) ((ULONG) prParamNetAddr + sizeof(PARAM_NETWORK_ADDRESS)); u4Len += OFFSET_OF(PARAM_NETWORK_ADDRESS, aucAddress) + sizeof(PARAM_NETWORK_ADDRESS); } #ifdef CONFIG_IPV6 for (i = 0; i < u4NumIPv6; i++) { prParamNetAddr->u2AddressLength = 6; prParamNetAddr->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP; kalMemCopy(prParamNetAddr->aucAddress, ip6, sizeof(ip6)); prParamNetAddr = (P_PARAM_NETWORK_ADDRESS) ((ULONG) prParamNetAddr + sizeof(ip6)); u4Len += OFFSET_OF(PARAM_NETWORK_ADDRESS, aucAddress) + sizeof(ip6); } #endif ASSERT(u4Len <= sizeof(g_aucBufIpAddr)); rStatus = kalIoctl(prGlueInfo, wlanoidSetNetworkAddress, (PVOID) prParamNetAddrList, u4Len, FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); } notify_suspend: DBGLOG(INIT, INFO, "IP: %d.%d.%d.%d, rStatus: %u\n", ip[0], ip[1], ip[2], ip[3], rStatus); if (rStatus != WLAN_STATUS_SUCCESS) wlanNotifyFwSuspend(prGlueInfo, TRUE); } void wlanHandleSystemResume(void) { struct net_device *prDev = NULL; P_GLUE_INFO_T prGlueInfo = NULL; WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; UINT_8 ip[4] = { 0 }; #ifdef CONFIG_IPV6 UINT_8 ip6[16] = { 0 }; /* FIX ME: avoid to allocate large memory in stack */ #endif EVENT_AIS_BSS_INFO_T rParam; UINT_32 u4BufLen = 0; #if CFG_SUPPORT_DROP_MC_PACKET UINT_32 u4PacketFilter = 0; UINT_32 u4SetInfoLen = 0; #endif /* <1> Sanity check and acquire the net_device */ ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES); if (u4WlanDevNum == 0) { DBGLOG(INIT, ERROR, "wlanLateResume u4WlanDevNum==0 invalid!!\n"); return; } prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; /* ASSERT(prDev); */ fgIsUnderSuspend = false; if (!prDev) { DBGLOG(INIT, INFO, "prDev == NULL!!!\n"); return; } /* <3> acquire the prGlueInfo */ prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); #if CFG_SUPPORT_DROP_MC_PACKET /* new filter should not include p2p mask */ #if CFG_ENABLE_WIFI_DIRECT_CFG_80211 u4PacketFilter = prGlueInfo->prAdapter->u4OsPacketFilter & (~PARAM_PACKET_FILTER_P2P_MASK); #endif if (kalIoctl(prGlueInfo, wlanoidSetCurrentPacketFilter, &u4PacketFilter, sizeof(u4PacketFilter), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen) != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, ERROR, "set packet filter failed.\n"); } #endif /* We will receive the event in rx, we will check if the status is the same in driver and FW, if not the same, trigger disconnetion procedure. */ kalMemZero(&rParam, sizeof(EVENT_AIS_BSS_INFO_T)); rStatus = kalIoctl(prGlueInfo, wlanoidQueryBSSInfo, &rParam, sizeof(EVENT_AIS_BSS_INFO_T), TRUE, TRUE, TRUE, FALSE, &u4BufLen); if (rStatus != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, ERROR, "Query BSSinfo fail 0x%x!!\n", rStatus); } /* <2> get the IPv4 address */ if (!(prDev->ip_ptr) || !((struct in_device *)(prDev->ip_ptr))->ifa_list || !(&(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local))) { goto notify_resume; } /* <4> copy the IPv4 address */ kalMemCopy(ip, &(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local), sizeof(ip)); #ifdef CONFIG_IPV6 /* <5> get the IPv6 address */ if (!prDev || !(prDev->ip6_ptr) || !((struct in_device *)(prDev->ip6_ptr))->ifa_list || !(&(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local))) { goto notify_resume; } /* <6> copy the IPv6 address */ kalMemCopy(ip6, &(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local), sizeof(ip6)); DBGLOG(INIT, INFO, "ipv6 is %d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d\n", ip6[0], ip6[1], ip6[2], ip6[3], ip6[4], ip6[5], ip6[6], ip6[7], ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15] ); #endif /* <7> clear the ARP filter */ { UINT_32 u4SetInfoLen = 0; /* UINT_8 aucBuf[32] = {0}; */ UINT_32 u4Len = sizeof(PARAM_NETWORK_ADDRESS_LIST); P_PARAM_NETWORK_ADDRESS_LIST prParamNetAddrList = (P_PARAM_NETWORK_ADDRESS_LIST) g_aucBufIpAddr; /* aucBuf; */ kalMemZero(g_aucBufIpAddr, sizeof(g_aucBufIpAddr)); prParamNetAddrList->u4AddressCount = 0; prParamNetAddrList->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP; ASSERT(u4Len <= sizeof(g_aucBufIpAddr /*aucBuf */)); rStatus = kalIoctl(prGlueInfo, wlanoidSetNetworkAddress, (PVOID) prParamNetAddrList, u4Len, FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); } notify_resume: DBGLOG(INIT, INFO, "Query BSS result: %d %d %d, IP: %d.%d.%d.%d, rStatus: %u\n", rParam.eConnectionState, rParam.eCurrentOPMode, rParam.fgIsNetActive, ip[0], ip[1], ip[2], ip[3], rStatus); if (rStatus != WLAN_STATUS_SUCCESS) { wlanNotifyFwSuspend(prGlueInfo, FALSE); } } #endif /* ! CONFIG_X86 */ int set_p2p_mode_handler(struct net_device *netdev, PARAM_CUSTOM_P2P_SET_STRUCT_T p2pmode) { #if 0 P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(netdev)); PARAM_CUSTOM_P2P_SET_STRUCT_T rSetP2P; WLAN_STATUS rWlanStatus = WLAN_STATUS_SUCCESS; UINT_32 u4BufLen = 0; rSetP2P.u4Enable = p2pmode.u4Enable; rSetP2P.u4Mode = p2pmode.u4Mode; if (!rSetP2P.u4Enable) p2pNetUnregister(prGlueInfo, TRUE); rWlanStatus = kalIoctl(prGlueInfo, wlanoidSetP2pMode, (PVOID) &rSetP2P, sizeof(PARAM_CUSTOM_P2P_SET_STRUCT_T), FALSE, FALSE, TRUE, FALSE, &u4BufLen); DBGLOG(INIT, INFO, "ret = %d\n", rWlanStatus); if (rSetP2P.u4Enable) p2pNetRegister(prGlueInfo, TRUE); return 0; #else P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(netdev)); PARAM_CUSTOM_P2P_SET_STRUCT_T rSetP2P; WLAN_STATUS rWlanStatus = WLAN_STATUS_SUCCESS; BOOLEAN fgIsP2PEnding; UINT_32 u4BufLen = 0; GLUE_SPIN_LOCK_DECLARATION(); DBGLOG(INIT, INFO, "%u %u\n", (UINT_32) p2pmode.u4Enable, (UINT_32) p2pmode.u4Mode); /* avoid remove & p2p off command simultaneously */ GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); fgIsP2PEnding = g_u4P2PEnding; g_u4P2POnOffing = 1; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); if (fgIsP2PEnding == 1) { /* skip the command if we are removing */ GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); g_u4P2POnOffing = 0; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); return 0; } rSetP2P.u4Enable = p2pmode.u4Enable; rSetP2P.u4Mode = p2pmode.u4Mode; #if !CFG_SUPPORT_PERSIST_NETDEV if ((!rSetP2P.u4Enable) && (fgIsResetting == FALSE)) p2pNetUnregister(prGlueInfo, TRUE); #endif /* move out to caller to avoid kalIoctrl & suspend/resume deadlock problem ALPS00844864 */ /* Scenario: 1. System enters suspend/resume but not yet enter wlanearlysuspend() or wlanlateresume(); 2. System switches to do PRIV_CMD_P2P_MODE and execute kalIoctl() and get g_halt_sem then do glRegisterEarlySuspend() or glUnregisterEarlySuspend(); But system suspend/resume procedure is not yet finished so we suspend; 3. System switches back to do suspend/resume procedure and execute kalIoctl(). But driver does not yet release g_halt_sem so system suspend in wlanearlysuspend() or wlanlateresume(); ==> deadlock occurs. */ rWlanStatus = kalIoctl(prGlueInfo, wlanoidSetP2pMode, (PVOID) &rSetP2P,/* pu4IntBuf[0]is used as input SubCmd */ sizeof(PARAM_CUSTOM_P2P_SET_STRUCT_T), FALSE, FALSE, TRUE, FALSE, &u4BufLen); #if !CFG_SUPPORT_PERSIST_NETDEV /* Need to check fgIsP2PRegistered, in case of whole chip reset. * in this case, kalIOCTL return success always, * and prGlueInfo->prP2pInfo may be NULL */ if ((rSetP2P.u4Enable) && (prGlueInfo->prAdapter->fgIsP2PRegistered) && (fgIsResetting == FALSE)) p2pNetRegister(prGlueInfo, TRUE); #endif GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); g_u4P2POnOffing = 0; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); return 0; #endif } static void set_dbg_level_handler(unsigned char dbg_lvl[DBG_MODULE_NUM]) { kalMemCopy(aucDebugModule, dbg_lvl, sizeof(aucDebugModule)); kalPrint("[wlan] change debug level"); } /*----------------------------------------------------------------------------*/ /*! * \brief Wlan probe function. This function probes and initializes the device. * * \param[in] pvData data passed by bus driver init function * _HIF_EHPI: NULL * _HIF_SDIO: sdio bus driver handle * * \retval 0 Success * \retval negative value Failed */ /*----------------------------------------------------------------------------*/ static INT_32 wlanProbe(PVOID pvData) { struct wireless_dev *prWdev = NULL; enum probe_fail_reason { BUS_INIT_FAIL, NET_CREATE_FAIL, BUS_SET_IRQ_FAIL, ADAPTER_START_FAIL, NET_REGISTER_FAIL, PROC_INIT_FAIL, FAIL_REASON_NUM } eFailReason; P_WLANDEV_INFO_T prWlandevInfo = NULL; INT_32 i4DevIdx = 0; P_GLUE_INFO_T prGlueInfo = NULL; P_ADAPTER_T prAdapter = NULL; INT_32 i4Status = 0; BOOLEAN bRet = FALSE; eFailReason = FAIL_REASON_NUM; do { /* 4 <1> Initialize the IO port of the interface */ /* GeorgeKuo: pData has different meaning for _HIF_XXX: * _HIF_EHPI: pointer to memory base variable, which will be * initialized by glBusInit(). * _HIF_SDIO: bus driver handle */ bRet = glBusInit(pvData); wlanDebugInit(); /* Cannot get IO address from interface */ if (FALSE == bRet) { DBGLOG(INIT, ERROR, KERN_ALERT "wlanProbe: glBusInit() fail\n"); i4Status = -EIO; eFailReason = BUS_INIT_FAIL; break; } /* 4 <2> Create network device, Adapter, KalInfo, prDevHandler(netdev) */ prWdev = wlanNetCreate(pvData); if (prWdev == NULL) { DBGLOG(INIT, ERROR, "wlanProbe: No memory for dev and its private\n"); i4Status = -ENOMEM; eFailReason = NET_CREATE_FAIL; break; } /* 4 <2.5> Set the ioaddr to HIF Info */ prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); gPrDev = prGlueInfo->prDevHandler; /* 4 <4> Setup IRQ */ prWlandevInfo = &arWlanDevInfo[i4DevIdx]; i4Status = glBusSetIrq(prWdev->netdev, NULL, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev))); if (i4Status != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, ERROR, "wlanProbe: Set IRQ error\n"); eFailReason = BUS_SET_IRQ_FAIL; break; } prGlueInfo->i4DevIdx = i4DevIdx; prAdapter = prGlueInfo->prAdapter; prGlueInfo->u4ReadyFlag = 0; #if CFG_TCP_IP_CHKSUM_OFFLOAD prAdapter->u4CSUMFlags = (CSUM_OFFLOAD_EN_TX_TCP | CSUM_OFFLOAD_EN_TX_UDP | CSUM_OFFLOAD_EN_TX_IP); #endif #if CFG_SUPPORT_CFG_FILE { PUINT_8 pucConfigBuf; UINT_32 u4ConfigReadLen; wlanCfgInit(prAdapter, NULL, 0, 0); pucConfigBuf = (PUINT_8) kalMemAlloc(WLAN_CFG_FILE_BUF_SIZE, VIR_MEM_TYPE); u4ConfigReadLen = 0; DBGLOG(INIT, LOUD, "CFG_FILE: Read File...\n"); if (pucConfigBuf) { kalMemZero(pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE); if (kalReadToFile("/data/misc/wifi.cfg", pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE, &u4ConfigReadLen) == 0) { DBGLOG(INIT, LOUD, "CFG_FILE: Read /data/misc/wifi.cfg\n"); } else if (kalReadToFile("/data/misc/wifi/wifi.cfg", pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE, &u4ConfigReadLen) == 0) { DBGLOG(INIT, LOUD, "CFG_FILE: Read /data/misc/wifi/wifi.cfg\n"); } else if (kalReadToFile("/etc/firmware/wifi.cfg", pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE, &u4ConfigReadLen) == 0) { DBGLOG(INIT, LOUD, "CFG_FILE: Read /etc/firmware/wifi.cfg\n"); } if (pucConfigBuf[0] != '\0' && u4ConfigReadLen > 0) wlanCfgInit(prAdapter, pucConfigBuf, u4ConfigReadLen, 0); kalMemFree(pucConfigBuf, VIR_MEM_TYPE, WLAN_CFG_FILE_BUF_SIZE); } /* pucConfigBuf */ } #endif /* 4 <5> Start Device */ /* */ #if CFG_ENABLE_FW_DOWNLOAD DBGLOG(INIT, TRACE, "start to download firmware...\n"); /* before start adapter, we need to open and load firmware */ { UINT_32 u4FwSize = 0; PVOID prFwBuffer = NULL; P_REG_INFO_T prRegInfo = &prGlueInfo->rRegInfo; /* P_REG_INFO_T prRegInfo = (P_REG_INFO_T) kmalloc(sizeof(REG_INFO_T), GFP_KERNEL); */ kalMemSet(prRegInfo, 0, sizeof(REG_INFO_T)); prRegInfo->u4StartAddress = CFG_FW_START_ADDRESS; prRegInfo->u4LoadAddress = CFG_FW_LOAD_ADDRESS; /* Load NVRAM content to REG_INFO_T */ glLoadNvram(prGlueInfo, prRegInfo); #if CFG_SUPPORT_CFG_FILE wlanCfgApply(prAdapter); #endif /* kalMemCopy(&prGlueInfo->rRegInfo, prRegInfo, sizeof(REG_INFO_T)); */ prRegInfo->u4PowerMode = CFG_INIT_POWER_SAVE_PROF; prRegInfo->fgEnArpFilter = TRUE; if (kalFirmwareImageMapping(prGlueInfo, &prFwBuffer, &u4FwSize) == NULL) { i4Status = -EIO; DBGLOG(INIT, ERROR, "kalFirmwareImageMapping fail!\n"); goto bailout; } else { if (wlanAdapterStart(prAdapter, prRegInfo, prFwBuffer, u4FwSize) != WLAN_STATUS_SUCCESS) { i4Status = -EIO; } } kalFirmwareImageUnmapping(prGlueInfo, NULL, prFwBuffer); bailout: /* kfree(prRegInfo); */ DBGLOG(INIT, TRACE, "download firmware status = %d\n", i4Status); if (i4Status < 0) { GL_HIF_INFO_T *HifInfo; UINT_32 u4FwCnt; DBGLOG(INIT, WARN, "CONNSYS FW CPUINFO:\n"); HifInfo = &prAdapter->prGlueInfo->rHifInfo; for (u4FwCnt = 0; u4FwCnt < 16; u4FwCnt++) DBGLOG(INIT, WARN, "0x%08x ", MCU_REG_READL(HifInfo, CONN_MCU_CPUPCR)); /* CONSYS_REG_READ(CONSYS_CPUPCR_REG) */ /* dump HIF/DMA registers, if fgIsBusAccessFailed is FALSE, otherwise, */ /* dump HIF register may be hung */ if (!fgIsBusAccessFailed) HifRegDump(prGlueInfo->prAdapter); /* if (prGlueInfo->rHifInfo.DmaOps->DmaRegDump != NULL) */ /* prGlueInfo->rHifInfo.DmaOps->DmaRegDump(&prGlueInfo->rHifInfo); */ eFailReason = ADAPTER_START_FAIL; break; } } #else /* P_REG_INFO_T prRegInfo = (P_REG_INFO_T) kmalloc(sizeof(REG_INFO_T), GFP_KERNEL); */ kalMemSet(&prGlueInfo->rRegInfo, 0, sizeof(REG_INFO_T)); P_REG_INFO_T prRegInfo = &prGlueInfo->rRegInfo; /* Load NVRAM content to REG_INFO_T */ glLoadNvram(prGlueInfo, prRegInfo); prRegInfo->u4PowerMode = CFG_INIT_POWER_SAVE_PROF; if (wlanAdapterStart(prAdapter, prRegInfo, NULL, 0) != WLAN_STATUS_SUCCESS) { i4Status = -EIO; eFailReason = ADAPTER_START_FAIL; break; } #endif if (FALSE == prAdapter->fgEnable5GBand) prWdev->wiphy->bands[IEEE80211_BAND_5GHZ] = NULL; prGlueInfo->main_thread = kthread_run(tx_thread, prGlueInfo->prDevHandler, "tx_thread"); g_u4HaltFlag = 0; #if CFG_SUPPORT_ROAMING_ENC /* adjust roaming threshold */ { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; CMD_ROAMING_INFO_T rRoamingInfo; UINT_32 u4SetInfoLen = 0; prAdapter->fgIsRoamingEncEnabled = TRUE; /* suggestion from Tsaiyuan.Hsu */ kalMemZero(&rRoamingInfo, sizeof(CMD_ROAMING_INFO_T)); rRoamingInfo.fgIsFastRoamingApplied = TRUE; DBGLOG(INIT, TRACE, "Enable roaming enhance function\n"); rStatus = kalIoctl(prGlueInfo, wlanoidSetRoamingInfo, &rRoamingInfo, sizeof(rRoamingInfo), TRUE, TRUE, TRUE, FALSE, &u4SetInfoLen); if (rStatus != WLAN_STATUS_SUCCESS) DBGLOG(INIT, ERROR, "set roaming advance info fail 0x%x\n", rStatus); } #endif /* CFG_SUPPORT_ROAMING_ENC */ #if (CFG_SUPPORT_TXR_ENC == 1) /* adjust tx rate switch threshold */ rlmTxRateEnhanceConfig(prGlueInfo->prAdapter); #endif /* CFG_SUPPORT_TXR_ENC */ /* set MAC address */ { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; struct sockaddr MacAddr; UINT_32 u4SetInfoLen = 0; kalMemZero(MacAddr.sa_data, sizeof(MacAddr.sa_data)); rStatus = kalIoctl(prGlueInfo, wlanoidQueryCurrentAddr, &MacAddr.sa_data, PARAM_MAC_ADDR_LEN, TRUE, TRUE, TRUE, FALSE, &u4SetInfoLen); if (rStatus != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, WARN, "set MAC addr fail 0x%x\n", rStatus); prGlueInfo->u4ReadyFlag = 0; } else { ether_addr_copy(prGlueInfo->prDevHandler->dev_addr, (const u8 *)&(MacAddr.sa_data)); ether_addr_copy(prGlueInfo->prDevHandler->perm_addr, prGlueInfo->prDevHandler->dev_addr); /* card is ready */ prGlueInfo->u4ReadyFlag = 1; #if CFG_SHOW_MACADDR_SOURCE DBGLOG(INIT, INFO, "MAC address: %pM ", (&MacAddr.sa_data)); #endif } } #if CFG_TCP_IP_CHKSUM_OFFLOAD /* set HW checksum offload */ { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; UINT_32 u4CSUMFlags = CSUM_OFFLOAD_EN_ALL; UINT_32 u4SetInfoLen = 0; rStatus = kalIoctl(prGlueInfo, wlanoidSetCSUMOffload, (PVOID) &u4CSUMFlags, sizeof(UINT_32), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); if (rStatus != WLAN_STATUS_SUCCESS) DBGLOG(INIT, WARN, "set HW checksum offload fail 0x%x\n", rStatus); } #endif /* 4 <3> Register the card */ DBGLOG(INIT, TRACE, "wlanNetRegister...\n"); i4DevIdx = wlanNetRegister(prWdev); if (i4DevIdx < 0) { i4Status = -ENXIO; DBGLOG(INIT, ERROR, "wlanProbe: Cannot register the net_device context to the kernel\n"); eFailReason = NET_REGISTER_FAIL; break; } wlanRegisterNotifier(); /* 4 <6> Initialize /proc filesystem */ #ifdef WLAN_INCLUDE_PROC DBGLOG(INIT, TRACE, "init procfs...\n"); i4Status = procCreateFsEntry(prGlueInfo); if (i4Status < 0) { DBGLOG(INIT, ERROR, "wlanProbe: init procfs failed\n"); eFailReason = PROC_INIT_FAIL; break; } #endif /* WLAN_INCLUDE_PROC */ #if CFG_ENABLE_BT_OVER_WIFI prGlueInfo->rBowInfo.fgIsNetRegistered = FALSE; prGlueInfo->rBowInfo.fgIsRegistered = FALSE; glRegisterAmpc(prGlueInfo); #endif #if CFG_ENABLE_WIFI_DIRECT DBGLOG(INIT, TRACE, "wlanSubModInit...\n"); /* wlan is launched */ prGlueInfo->prAdapter->fgIsWlanLaunched = TRUE; /* if p2p module is inserted, notify tx_thread to init p2p network */ if (rSubModHandler[P2P_MODULE].subModInit) wlanSubModInit(prGlueInfo); /* register set_p2p_mode handler to mtk_wmt_wifi */ register_set_p2p_mode_handler(set_p2p_mode_handler); #endif #if CFG_SPM_WORKAROUND_FOR_HOTSPOT if (glIsChipNeedWakelock(prGlueInfo)) KAL_WAKE_LOCK_INIT(prGlueInfo->prAdapter, &prGlueInfo->prAdapter->rApWakeLock, "WLAN AP"); #endif } while (FALSE); if (i4Status != WLAN_STATUS_SUCCESS) { switch (eFailReason) { case PROC_INIT_FAIL: wlanNetUnregister(prWdev); set_bit(GLUE_FLAG_HALT_BIT, &prGlueInfo->ulFlag); /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); /* wait main thread stops */ wait_for_completion_interruptible(&prGlueInfo->rHaltComp); KAL_WAKE_LOCK_DESTROY(prAdapter, &prAdapter->rTxThreadWakeLock); wlanAdapterStop(prAdapter); glBusFreeIrq(prWdev->netdev, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev))); KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock); wlanNetDestroy(prWdev); break; case NET_REGISTER_FAIL: set_bit(GLUE_FLAG_HALT_BIT, &prGlueInfo->ulFlag); /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); /* wait main thread stops */ wait_for_completion_interruptible(&prGlueInfo->rHaltComp); KAL_WAKE_LOCK_DESTROY(prAdapter, &prAdapter->rTxThreadWakeLock); wlanAdapterStop(prAdapter); glBusFreeIrq(prWdev->netdev, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev))); KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock); wlanNetDestroy(prWdev); break; case ADAPTER_START_FAIL: glBusFreeIrq(prWdev->netdev, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev))); KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock); wlanNetDestroy(prWdev); break; case BUS_SET_IRQ_FAIL: KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock); wlanNetDestroy(prWdev); break; case NET_CREATE_FAIL: break; case BUS_INIT_FAIL: break; default: break; } } #if CFG_ENABLE_WIFI_DIRECT { GLUE_SPIN_LOCK_DECLARATION(); GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); g_u4P2PEnding = 0; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); } #endif #if CFG_SUPPORT_AGPS_ASSIST if (i4Status == WLAN_STATUS_SUCCESS) kalIndicateAgpsNotify(prAdapter, AGPS_EVENT_WLAN_ON, NULL, 0); #endif #if (CFG_SUPPORT_MET_PROFILING == 1) { int iMetInitRet = WLAN_STATUS_FAILURE; if (i4Status == WLAN_STATUS_SUCCESS) { DBGLOG(INIT, TRACE, "init MET procfs...\n"); iMetInitRet = kalMetInitProcfs(prGlueInfo); if (iMetInitRet < 0) DBGLOG(INIT, ERROR, "wlanProbe: init MET procfs failed\n"); } } #endif if (i4Status == WLAN_STATUS_SUCCESS) { /*Init performance monitor structure */ kalPerMonInit(prGlueInfo); /* probe ok */ DBGLOG(INIT, TRACE, "wlanProbe ok\n"); } else { /* we don't care the return value of mtk_wcn_set_connsys_power_off_flag, * because even this function returns * error, we can also call core dump but only core dump failed. */ if (g_IsNeedDoChipReset) mtk_wcn_set_connsys_power_off_flag(0); /* probe failed */ DBGLOG(INIT, ERROR, "wlanProbe failed\n"); } return i4Status; } /* end of wlanProbe() */ /*----------------------------------------------------------------------------*/ /*! * \brief A method to stop driver operation and release all resources. Following * this call, no frame should go up or down through this interface. * * \return (none) */ /*----------------------------------------------------------------------------*/ static VOID wlanRemove(VOID) { struct net_device *prDev = NULL; P_WLANDEV_INFO_T prWlandevInfo = NULL; P_GLUE_INFO_T prGlueInfo = NULL; P_ADAPTER_T prAdapter = NULL; DBGLOG(INIT, LOUD, "Remove wlan!\n"); /* 4 <0> Sanity check */ ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES); if (0 == u4WlanDevNum) { DBGLOG(INIT, ERROR, "0 == u4WlanDevNum\n"); return; } /* unregister set_p2p_mode handler to mtk_wmt_wifi */ register_set_p2p_mode_handler(NULL); prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; prWlandevInfo = &arWlanDevInfo[u4WlanDevNum - 1]; ASSERT(prDev); if (NULL == prDev) { DBGLOG(INIT, ERROR, "NULL == prDev\n"); return; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); if (NULL == prGlueInfo) { DBGLOG(INIT, ERROR, "NULL == prGlueInfo\n"); free_netdev(prDev); return; } kalPerMonDestroy(prGlueInfo); /* 4 <3> Remove /proc filesystem. */ #ifdef WLAN_INCLUDE_PROC procRemoveProcfs(); #endif /* WLAN_INCLUDE_PROC */ #if CFG_ENABLE_WIFI_DIRECT /* avoid remove & p2p off command simultaneously */ { BOOLEAN fgIsP2POnOffing; GLUE_SPIN_LOCK_DECLARATION(); GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); g_u4P2PEnding = 1; fgIsP2POnOffing = g_u4P2POnOffing; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); DBGLOG(INIT, TRACE, "waiting for fgIsP2POnOffing...\n"); /* History: cannot use down() here, sometimes we cannot come back here */ /* waiting for p2p off command finishes, we cannot skip the remove */ while (1) { if (fgIsP2POnOffing == 0) break; GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); fgIsP2POnOffing = g_u4P2POnOffing; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); } } #endif #if CFG_ENABLE_BT_OVER_WIFI if (prGlueInfo->rBowInfo.fgIsNetRegistered) { bowNotifyAllLinkDisconnected(prGlueInfo->prAdapter); /* wait 300ms for BoW module to send deauth */ kalMsleep(300); } #endif /* 4 <1> Stopping handling interrupt and free IRQ */ DBGLOG(INIT, TRACE, "free IRQ...\n"); glBusFreeIrq(prDev, *((P_GLUE_INFO_T *) netdev_priv(prDev))); kalMemSet(&(prGlueInfo->prAdapter->rWlanInfo), 0, sizeof(WLAN_INFO_T)); g_u4HaltFlag = 1; /* before flush_delayed_work() */ if (fgIsWorkMcStart == TRUE) { DBGLOG(INIT, TRACE, "flush_delayed_work...\n"); flush_delayed_work(&workq); /* flush_delayed_work_sync is deprecated */ } flush_delayed_work(&sched_workq); DBGLOG(INIT, INFO, "down g_halt_sem...\n"); down(&g_halt_sem); #if CFG_SPM_WORKAROUND_FOR_HOTSPOT if (glIsChipNeedWakelock(prGlueInfo)) KAL_WAKE_LOCK_DESTROY(prGlueInfo->prAdapter, &prGlueInfo->prAdapter->rApWakeLock); #endif /* flush_delayed_work_sync(&workq); */ /* flush_delayed_work(&workq); */ /* flush_delayed_work_sync is deprecated */ /* 4 <2> Mark HALT, notify main thread to stop, and clean up queued requests */ /* prGlueInfo->u4Flag |= GLUE_FLAG_HALT; */ set_bit(GLUE_FLAG_HALT_BIT, &prGlueInfo->ulFlag); DBGLOG(INIT, TRACE, "waiting for tx_thread stop...\n"); /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); DBGLOG(INIT, TRACE, "wait_for_completion_interruptible\n"); /* wait main thread stops */ wait_for_completion_interruptible(&prGlueInfo->rHaltComp); DBGLOG(INIT, TRACE, "mtk_sdiod stopped\n"); KAL_WAKE_LOCK_DESTROY(prGlueInfo->prAdapter, &prGlueInfo->prAdapter->rTxThreadWakeLock); KAL_WAKE_LOCK_DESTROY(prGlueInfo->prAdapter, &prGlueInfo->rAhbIsrWakeLock); /* prGlueInfo->rHifInfo.main_thread = NULL; */ prGlueInfo->main_thread = NULL; #if CFG_ENABLE_BT_OVER_WIFI if (prGlueInfo->rBowInfo.fgIsRegistered) glUnregisterAmpc(prGlueInfo); #endif #if (CFG_SUPPORT_MET_PROFILING == 1) kalMetRemoveProcfs(); #endif /* Force to do DMA reset */ DBGLOG(INIT, TRACE, "glResetHif\n"); glResetHif(prGlueInfo); /* 4 <4> wlanAdapterStop */ prAdapter = prGlueInfo->prAdapter; #if CFG_SUPPORT_AGPS_ASSIST kalIndicateAgpsNotify(prAdapter, AGPS_EVENT_WLAN_OFF, NULL, 0); #endif wlanAdapterStop(prAdapter); DBGLOG(INIT, TRACE, "Number of Stalled Packets = %d\n", prGlueInfo->i4TxPendingFrameNum); #if CFG_ENABLE_WIFI_DIRECT prGlueInfo->prAdapter->fgIsWlanLaunched = FALSE; if (prGlueInfo->prAdapter->fgIsP2PRegistered) { DBGLOG(INIT, TRACE, "p2pNetUnregister...\n"); #if !CFG_SUPPORT_PERSIST_NETDEV p2pNetUnregister(prGlueInfo, FALSE); #endif DBGLOG(INIT, INFO, "p2pRemove...\n"); p2pRemove(prGlueInfo); } #endif /* 4 <5> Release the Bus */ glBusRelease(prDev); up(&g_halt_sem); wlanDebugUninit(); /* 4 <6> Unregister the card */ wlanNetUnregister(prDev->ieee80211_ptr); /* 4 <7> Destroy the device */ wlanNetDestroy(prDev->ieee80211_ptr); prDev = NULL; DBGLOG(INIT, LOUD, "wlanUnregisterNotifier...\n"); wlanUnregisterNotifier(); DBGLOG(INIT, INFO, "wlanRemove ok\n"); } /* end of wlanRemove() */ /*----------------------------------------------------------------------------*/ /*! * \brief Driver entry point when the driver is configured as a Linux Module, and * is called once at module load time, by the user-level modutils * application: insmod or modprobe. * * \retval 0 Success */ /*----------------------------------------------------------------------------*/ /* 1 Module Entry Point */ static int initWlan(void) { int ret = 0, i; #if DBG for (i = 0; i < DBG_MODULE_NUM; i++) aucDebugModule[i] = DBG_CLASS_MASK; /* enable all */ #else /* Initial debug level is D1 */ for (i = 0; i < DBG_MODULE_NUM; i++) aucDebugModule[i] = DBG_CLASS_ERROR | DBG_CLASS_WARN | DBG_CLASS_INFO | DBG_CLASS_STATE; #endif /* DBG */ DBGLOG(INIT, INFO, "initWlan\n"); spin_lock_init(&g_p2p_lock); /* memory pre-allocation */ kalInitIOBuffer(); procInitFs(); createWirelessDevice(); if (gprWdev) glP2pCreateWirelessDevice((P_GLUE_INFO_T) wiphy_priv(gprWdev->wiphy)); ret = ((glRegisterBus(wlanProbe, wlanRemove) == WLAN_STATUS_SUCCESS) ? 0 : -EIO); if (ret == -EIO) { kalUninitIOBuffer(); return ret; } #if (CFG_CHIP_RESET_SUPPORT) glResetInit(); #endif /* register set_dbg_level handler to mtk_wmt_wifi */ register_set_dbg_level_handler(set_dbg_level_handler); /* Register framebuffer notifier client*/ kalFbNotifierReg((P_GLUE_INFO_T) wiphy_priv(gprWdev->wiphy)); /* Set the initial DEBUG CLASS of each module */ return ret; } /* end of initWlan() */ /*----------------------------------------------------------------------------*/ /*! * \brief Driver exit point when the driver as a Linux Module is removed. Called * at module unload time, by the user level modutils application: rmmod. * This is our last chance to clean up after ourselves. * * \return (none) */ /*----------------------------------------------------------------------------*/ /* 1 Module Leave Point */ static VOID exitWlan(void) { DBGLOG(INIT, INFO, "exitWlan\n"); /* Unregister framebuffer notifier client*/ kalFbNotifierUnReg(); /* unregister set_dbg_level handler to mtk_wmt_wifi */ register_set_dbg_level_handler(NULL); #if CFG_CHIP_RESET_SUPPORT glResetUninit(); #endif destroyWirelessDevice(); glP2pDestroyWirelessDevice(); glUnregisterBus(wlanRemove); /* free pre-allocated memory */ kalUninitIOBuffer(); DBGLOG(INIT, INFO, "exitWlan\n"); procUninitProcFs(); } /* end of exitWlan() */ #ifdef MTK_WCN_BUILT_IN_DRIVER int mtk_wcn_wlan_gen2_init(void) { return initWlan(); } EXPORT_SYMBOL(mtk_wcn_wlan_gen2_init); void mtk_wcn_wlan_gen2_exit(void) { return exitWlan(); } EXPORT_SYMBOL(mtk_wcn_wlan_gen2_exit); #else module_init(initWlan); module_exit(exitWlan); #endif
bq/aquaris-M4.5
drivers/misc/mediatek/connectivity/wlan/gen2/os/linux/gl_init.c
C
gpl-2.0
114,508