├── startcocci_linux.sh ├── startcocci_freebsd.sh ├── testdir └── truecases │ ├── test.h │ ├── mic_virtio.h │ ├── sclp_ctl.c │ ├── mic_common.h │ ├── cros_ec_dev.c │ ├── cros_ec_i2c.c │ ├── cros_ec_proto.c │ ├── mic_virtio.c │ ├── commctrl.c │ └── audit.c ├── copy_files.py ├── test.c ├── readme.txt ├── pattern_match_freebsd.cocci └── pattern_match_linux.cocci /startcocci_linux.sh: -------------------------------------------------------------------------------- 1 | resultfile='result.txt' 2 | testdir='testdir' 3 | outcome='outcome' 4 | 5 | if test -d ${outcome} 6 | then 7 | rm -rf ${outcome}/ 8 | mkdir ${outcome} 9 | echo Remove old outcome files... 10 | else 11 | mkdir ${outcome} 12 | echo Make outcome dir... 13 | fi 14 | 15 | if test -d ${testdir} 16 | then 17 | pass 18 | else 19 | mkdir ${testdir} 20 | echo Make testdir... 21 | fi 22 | 23 | if test -f ${resultfile} 24 | then 25 | rm ${resultfile} 26 | touch ${resultfile} 27 | echo Remove old results... 28 | else 29 | touch ${resultfile} 30 | echo Make results log file... 31 | fi 32 | 33 | echo Start analyzing... 34 | spatch -cocci_file pattern_match_linux.cocci -D count=0 -dir ${testdir} 35 | #--disable-worth-trying-opt 36 | echo Finished analyzing. 37 | python copy_files.py 38 | 39 | echo Result log: ${resultfile}. 40 | echo Source files copied to: ${outcome}\ 41 | -------------------------------------------------------------------------------- /startcocci_freebsd.sh: -------------------------------------------------------------------------------- 1 | resultfile='result.txt' 2 | testdir='testdir' 3 | outcome='outcome' 4 | 5 | if test -d ${outcome} 6 | then 7 | rm -rf ${outcome}/ 8 | mkdir ${outcome} 9 | echo Remove old outcome files... 10 | else 11 | mkdir ${outcome} 12 | echo Make outcome dir... 13 | fi 14 | 15 | if test -d ${testdir} 16 | then 17 | pass 18 | else 19 | mkdir ${testdir} 20 | echo Make testdir... 21 | fi 22 | 23 | if test -f ${resultfile} 24 | then 25 | rm ${resultfile} 26 | touch ${resultfile} 27 | echo Remove old results... 28 | else 29 | touch ${resultfile} 30 | echo Make results log file... 31 | fi 32 | 33 | echo Start analyzing... 34 | spatch -cocci_file pattern_match_freebsd.cocci -D count=0 -dir ${testdir} 35 | #--disable-worth-trying-opt 36 | echo Finished analyzing. 37 | python copy_files.py 38 | 39 | echo Result log: ${resultfile}. 40 | echo Source files copied to: ${outcome}\ 41 | -------------------------------------------------------------------------------- /testdir/truecases/test.h: -------------------------------------------------------------------------------- 1 | int case1(int p){ 2 | 3 | int x,y; 4 | q = (char*)p; 5 | x =x +1; 6 | 7 | get_user(x, q); 8 | 9 | 10 | y = y + 1; 11 | 12 | get_user(x, p); 13 | 14 | //get_user(x, (unsigned int *)e); 15 | } 16 | int case2(int p){ 17 | 18 | int x,y; 19 | q = p; 20 | x =x +1; 21 | 22 | get_user(x, p); 23 | 24 | y = y + 1; 25 | 26 | get_user(x, q); 27 | 28 | } 29 | int case3(int p){ 30 | 31 | int x,y; 32 | 33 | x =x +1; 34 | 35 | get_user(x, p); 36 | 37 | q = p; 38 | y = y + 1; 39 | 40 | get_user(x, q); 41 | 42 | } 43 | int case4(int p){ 44 | 45 | int x,y; 46 | 47 | x =x +1; 48 | 49 | get_user(x, &p); 50 | 51 | y = y + 1; 52 | 53 | get_user(x, &p); 54 | 55 | } 56 | int case5(int p){ 57 | 58 | int x,y; 59 | 60 | x =x +1; 61 | 62 | get_user(x, &p->size); 63 | 64 | y = y + 1; 65 | 66 | 67 | copy_from_user(buf, p, x); 68 | 69 | } 70 | -------------------------------------------------------------------------------- /copy_files.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path 3 | import shutil 4 | 5 | class Tool: 6 | def __init__(self ): 7 | if not os.path.exists("outcome/"): 8 | os.mkdir('outcome/') 9 | #os.path.isfile('test.txt') 10 | 11 | self.result_handler = open("result.txt","r") 12 | if not self.result_handler: 13 | print "open result failed!" 14 | 15 | self.buffer = "" 16 | 17 | self.counter = 0 18 | 19 | def get_dst(self, src): 20 | p = src.rfind('/') 21 | filename = src[p+1:] 22 | return 'outcome/'+str(self.counter)+"-"+filename 23 | 24 | def tailor(self, str): #delete '\n' 25 | s = len(str) 26 | return str[:s-1] 27 | 28 | def main(self): 29 | 30 | while True: 31 | src = self.result_handler.readline() 32 | if not src: 33 | print "Finished copying." 34 | break 35 | else: 36 | if src[0] != 'N' and src[0] != '-' : 37 | if src != self.buffer : 38 | self.counter = self.counter + 1 39 | dst = self.get_dst(src) 40 | s = self.tailor(src) 41 | d = self.tailor(dst) 42 | print "Copying from: ", s, "\tto: ", d 43 | shutil.copy(s,d) 44 | #shutil.move('d:/c.png','e:/') 45 | #shutil.rmtree('d:/dd') 46 | self.buffer = src 47 | 48 | 49 | def finish(self): 50 | self.result_handler.close() 51 | print self.counter, "file copied" 52 | 53 | ########################################### 54 | mytool = Tool() 55 | mytool.main() 56 | mytool.finish() -------------------------------------------------------------------------------- /test.c: -------------------------------------------------------------------------------- 1 | /* 2 | int rule1(int p){ 3 | 4 | 5 | a = a + 1; 6 | 7 | get_user(cmd, src); 8 | src += sizeof(uint32_t); 9 | get_user(target, src); 10 | } 11 | 12 | int rule2(int p){ 13 | 14 | 15 | a = a + 1; 16 | ptr = src; 17 | 18 | __get_user(cmd, ptr); 19 | //src += sizeof(uint32_t); 20 | 21 | 22 | __get_user(target, src); 23 | } 24 | 25 | int rule3(int p){ 26 | 27 | 28 | a = a + 1; 29 | ptr = src; 30 | 31 | copy_from_user(cmd, (uint32_t)src, c1); 32 | //ptr -= sizeof(uint32_t); 33 | 34 | 35 | copy_from_user(target, (uint32_t)ptr, c2); 36 | } 37 | 38 | int rule4(int p){ 39 | 40 | 41 | a = a + 1; 42 | 43 | 44 | __copy_from_user(cmd, src, c1); 45 | 46 | //src -= sizeof(uint32_t); 47 | ptr = (uint32_t)src; 48 | //ptr -= sizeof(uint32_t); 49 | 50 | 51 | __copy_from_user(target, ptr, c2); 52 | } 53 | 54 | int rule5(int p){ 55 | 56 | 57 | a = a + 1; 58 | 59 | 60 | __copy_from_user(cmd, (int)src->ele, c1); 61 | 62 | //src -= sizeof(uint32_t); 63 | 64 | 65 | __copy_from_user(target, src, c2); 66 | } 67 | 68 | 69 | int rule6(int p){ 70 | 71 | 72 | a = a + 1; 73 | 74 | __copy_from_user(cmd, src.ele, c1); 75 | 76 | //&src -= sizeof(uint32_t); 77 | 78 | 79 | __copy_from_user(target, (int)&src, c2); 80 | } 81 | 82 | void binder(){ 83 | if (copy_from_user(t->buffer->data, (const void __user *)(uintptr_t) 84 | tr->data.ptr.buffer, tr->data_size)) { 85 | binder_user_error("%d:%d got transaction with invalid data ptr\n", 86 | proc->pid, thread->pid); 87 | return_error = BR_FAILED_REPLY; 88 | goto err_copy_data_failed; 89 | } 90 | if (copy_from_user(offp, (const void __user *)(uintptr_t) 91 | tr->data.ptr.offsets, tr->offsets_size)) { 92 | binder_user_error("%d:%d got transaction with invalid offsets ptr\n", 93 | proc->pid, thread->pid); 94 | return_error = BR_FAILED_REPLY; 95 | goto err_copy_data_failed; 96 | } 97 | } 98 | */ 99 | void sysctl(){ 100 | 101 | while (left && isspace(c)){ 102 | __get_user(c, p) 103 | p++; 104 | } 105 | 106 | if (left > sizeof(tmpbuf) - 1) 107 | return -EINVAL; 108 | if (copy_from_user(tmpbuf, p, left)) 109 | return -EFAULT; 110 | } -------------------------------------------------------------------------------- /testdir/truecases/mic_virtio.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Intel MIC Platform Software Stack (MPSS) 3 | * 4 | * Copyright(c) 2013 Intel Corporation. 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License, version 2, as 8 | * published by the Free Software Foundation. 9 | * 10 | * This program is distributed in the hope that it will be useful, but 11 | * WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | * General Public License for more details. 14 | * 15 | * The full GNU General Public License is included in this distribution in 16 | * the file called "COPYING". 17 | * 18 | * Disclaimer: The codes contained in these modules may be specific to 19 | * the Intel Software Development Platform codenamed: Knights Ferry, and 20 | * the Intel product codenamed: Knights Corner, and are not backward 21 | * compatible with other Intel products. Additionally, Intel will NOT 22 | * support the codes or instruction set in future products. 23 | * 24 | * Intel MIC Card driver. 25 | * 26 | */ 27 | #ifndef __MIC_CARD_VIRTIO_H 28 | #define __MIC_CARD_VIRTIO_H 29 | 30 | #include 31 | #include "mic_device.h" 32 | 33 | /* 34 | * 64 bit I/O access 35 | */ 36 | #ifndef ioread64 37 | #define ioread64 readq 38 | #endif 39 | #ifndef iowrite64 40 | #define iowrite64 writeq 41 | #endif 42 | 43 | static inline unsigned mic_desc_size(struct mic_device_desc __iomem *desc) 44 | { 45 | return sizeof(*desc) 46 | + ioread8(&desc->num_vq) * sizeof(struct mic_vqconfig) 47 | + ioread8(&desc->feature_len) * 2 48 | + ioread8(&desc->config_len); 49 | } 50 | 51 | static inline struct mic_vqconfig __iomem * 52 | mic_vq_config(struct mic_device_desc __iomem *desc) 53 | { 54 | return (struct mic_vqconfig __iomem *)(desc + 1); 55 | } 56 | 57 | static inline __u8 __iomem * 58 | mic_vq_features(struct mic_device_desc __iomem *desc) 59 | { 60 | return (__u8 __iomem *)(mic_vq_config(desc) + ioread8(&desc->num_vq)); 61 | } 62 | 63 | static inline __u8 __iomem * 64 | mic_vq_configspace(struct mic_device_desc __iomem *desc) 65 | { 66 | return mic_vq_features(desc) + ioread8(&desc->feature_len) * 2; 67 | } 68 | static inline unsigned mic_total_desc_size(struct mic_device_desc __iomem *desc) 69 | { 70 | return mic_aligned_desc_size(desc) + sizeof(struct mic_device_ctrl); 71 | } 72 | 73 | int mic_devices_init(struct mic_driver *mdrv); 74 | void mic_devices_uninit(struct mic_driver *mdrv); 75 | 76 | #endif 77 | -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | 1. Introduction of the script files. 2 | 3 | In /cocci directory, there are six script files and two subdirectory that are important to know (ignore the rest): 4 | 5 | (1)/testdir: A directory that stors the files that are to parsed. Any file in this directoy or subdirectoy will be parsed. 6 | 7 | (2)startcocci_linux.sh: Shellscript to start the parsing. This script will clearn the files that are left from the last parsing and invoke the right cocci script(pattern_match_linux.cocci) to parse the source files. This one is specifc for Linux and Android source code. 8 | 9 | (3)startcocci_freebsd.sh: Shellscript of starting the parsing. This script will clearn the files that are left from the last parsing and invoke the right cocci script(pattern_match_fressbsd.cocci) to parse the source files. This one is specifc for FreeBSD source code. 10 | 11 | (4)pattern_match_linux.cocci: Coccinelle script file that stores the rules we added for the pattern matching. This one is specific for Linux and Android, because they use the same transfer functions. 12 | 13 | (5)pattern_match_FreeBSD.cocci: Coccinelle script file that stores the rules we added for the pattern matching. This one is specific for FreeBSD, because it uses different transfer functions. 14 | 15 | (6)copy_files.py: Python script that helps to copy the suspicious souce code files to a specifc subdirectory, so as to facilitate the manual analysis. 16 | 17 | (7)/outcome: This directory will be created after parsing, and suspicous source files will be copied here for manual analysis. 18 | 19 | (8)resut.txt: This file will be created after parsing, reports and statistical data will be stored in this file. 20 | 21 | (9)readme.txt: Instructions and decriptions. 22 | 23 | 2. Description of Coccinelle rules. 24 | 25 | There totally two Coccinelle rule files (pattern_match_linux.cocci, pattern_match_FreeBSD.cocci) in this method, which are basically the same except useing different transfer functions to match. These file consist of the following: 26 | 27 | (1) function print_and_log() prints and stores the results of the parsing to specific files and directory. 28 | 29 | (2) function post_match_process() filters out some coner cases after the coccinelle pattern matching, so as to reduce the false positives. 30 | 31 | (3)rule 1 ~ rule 6 are the coccinelle rules defined to match different double fetch situations. These rules will be matched one by one, and matching stops once a rule is matched. 32 | The "..." in the code stands for any statements in the source code; 33 | The "|" stands for a disjunction, each item is used to match until one is matched. 34 | Key workd "when != " after "..." represents the situations that shouldn't be included. 35 | 36 | 37 | 3. How to use. 38 | (1) Install Coccinelle on the machine. 39 | Mac OS: “brew install coccinelle” 40 | Ubuntu: “apt-get install coccinelle” 41 | 42 | (2) Copy the files that are to be parsed to /testdir 43 | 44 | (3) Run “./startcocci_linux.sh” for Linux or Android parsing 45 | Run “./startcocci_freebsd.sh” for FreeBSD parsing 46 | 47 | (4) Check the result from result.txt 48 | 49 | (5) See the corresponding source files from /outcome 50 | 51 | 52 | -------------------------------------------------------------------------------- /testdir/truecases/sclp_ctl.c: -------------------------------------------------------------------------------- 1 | /* 2 | * IOCTL interface for SCLP 3 | * 4 | * Copyright IBM Corp. 2012 5 | * 6 | * Author: Michael Holzheu 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | #include "sclp.h" 21 | 22 | /* 23 | * Supported command words 24 | */ 25 | static unsigned int sclp_ctl_sccb_wlist[] = { 26 | 0x00400002, 27 | 0x00410002, 28 | }; 29 | 30 | /* 31 | * Check if command word is supported 32 | */ 33 | static int sclp_ctl_cmdw_supported(unsigned int cmdw) 34 | { 35 | int i; 36 | 37 | for (i = 0; i < ARRAY_SIZE(sclp_ctl_sccb_wlist); i++) { 38 | if (cmdw == sclp_ctl_sccb_wlist[i]) 39 | return 1; 40 | } 41 | return 0; 42 | } 43 | 44 | static void __user *u64_to_uptr(u64 value) 45 | { 46 | if (is_compat_task()) 47 | return compat_ptr(value); 48 | else 49 | return (void __user *)(unsigned long)value; 50 | } 51 | 52 | /* 53 | * Start SCLP request 54 | */ 55 | static int sclp_ctl_ioctl_sccb(void __user *user_area) 56 | { 57 | struct sclp_ctl_sccb ctl_sccb; 58 | struct sccb_header *sccb; 59 | int rc; 60 | 61 | if (copy_from_user(&ctl_sccb, user_area, sizeof(ctl_sccb))) 62 | return -EFAULT; 63 | if (!sclp_ctl_cmdw_supported(ctl_sccb.cmdw)) 64 | return -EOPNOTSUPP; 65 | sccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA); 66 | if (!sccb) 67 | return -ENOMEM; 68 | if (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sizeof(*sccb))) { 69 | rc = -EFAULT; 70 | goto out_free; 71 | } 72 | if (sccb->length > PAGE_SIZE || sccb->length < 8) 73 | return -EINVAL; 74 | if (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sccb->length)) { 75 | rc = -EFAULT; 76 | goto out_free; 77 | } 78 | rc = sclp_sync_request(ctl_sccb.cmdw, sccb); 79 | if (rc) 80 | goto out_free; 81 | if (copy_to_user(u64_to_uptr(ctl_sccb.sccb), sccb, sccb->length)) 82 | rc = -EFAULT; 83 | out_free: 84 | free_page((unsigned long) sccb); 85 | return rc; 86 | } 87 | 88 | /* 89 | * SCLP SCCB ioctl function 90 | */ 91 | static long sclp_ctl_ioctl(struct file *filp, unsigned int cmd, 92 | unsigned long arg) 93 | { 94 | void __user *argp; 95 | 96 | if (is_compat_task()) 97 | argp = compat_ptr(arg); 98 | else 99 | argp = (void __user *) arg; 100 | switch (cmd) { 101 | case SCLP_CTL_SCCB: 102 | return sclp_ctl_ioctl_sccb(argp); 103 | default: /* unknown ioctl number */ 104 | return -ENOTTY; 105 | } 106 | } 107 | 108 | /* 109 | * File operations 110 | */ 111 | static const struct file_operations sclp_ctl_fops = { 112 | .owner = THIS_MODULE, 113 | .open = nonseekable_open, 114 | .unlocked_ioctl = sclp_ctl_ioctl, 115 | .compat_ioctl = sclp_ctl_ioctl, 116 | .llseek = no_llseek, 117 | }; 118 | 119 | /* 120 | * Misc device definition 121 | */ 122 | static struct miscdevice sclp_ctl_device = { 123 | .minor = MISC_DYNAMIC_MINOR, 124 | .name = "sclp", 125 | .fops = &sclp_ctl_fops, 126 | }; 127 | 128 | /* 129 | * Register sclp_ctl misc device 130 | */ 131 | static int __init sclp_ctl_init(void) 132 | { 133 | return misc_register(&sclp_ctl_device); 134 | } 135 | module_init(sclp_ctl_init); 136 | 137 | /* 138 | * Deregister sclp_ctl misc device 139 | */ 140 | static void __exit sclp_ctl_exit(void) 141 | { 142 | misc_deregister(&sclp_ctl_device); 143 | } 144 | module_exit(sclp_ctl_exit); 145 | -------------------------------------------------------------------------------- /testdir/truecases/mic_common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Intel MIC Platform Software Stack (MPSS) 3 | * 4 | * Copyright(c) 2013 Intel Corporation. 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License, version 2, as 8 | * published by the Free Software Foundation. 9 | * 10 | * This program is distributed in the hope that it will be useful, but 11 | * WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | * General Public License for more details. 14 | * 15 | * The full GNU General Public License is included in this distribution in 16 | * the file called "COPYING". 17 | * 18 | * Intel MIC driver. 19 | * 20 | */ 21 | #ifndef __MIC_COMMON_H_ 22 | #define __MIC_COMMON_H_ 23 | 24 | #include 25 | 26 | #define __mic_align(a, x) (((a) + (x) - 1) & ~((x) - 1)) 27 | 28 | /** 29 | * struct mic_device_desc: Virtio device information shared between the 30 | * virtio driver and userspace backend 31 | * 32 | * @type: Device type: console/network/disk etc. Type 0/-1 terminates. 33 | * @num_vq: Number of virtqueues. 34 | * @feature_len: Number of bytes of feature bits. Multiply by 2: one for 35 | host features and one for guest acknowledgements. 36 | * @config_len: Number of bytes of the config array after virtqueues. 37 | * @status: A status byte, written by the Guest. 38 | * @config: Start of the following variable length config. 39 | */ 40 | struct mic_device_desc { 41 | __s8 type; 42 | __u8 num_vq; 43 | __u8 feature_len; 44 | __u8 config_len; 45 | __u8 status; 46 | __le64 config[0]; 47 | } __attribute__ ((aligned(8))); 48 | 49 | /** 50 | * struct mic_device_ctrl: Per virtio device information in the device page 51 | * used internally by the host and card side drivers. 52 | * 53 | * @vdev: Used for storing MIC vdev information by the guest. 54 | * @config_change: Set to 1 by host when a config change is requested. 55 | * @vdev_reset: Set to 1 by guest to indicate virtio device has been reset. 56 | * @guest_ack: Set to 1 by guest to ack a command. 57 | * @host_ack: Set to 1 by host to ack a command. 58 | * @used_address_updated: Set to 1 by guest when the used address should be 59 | * updated. 60 | * @c2h_vdev_db: The doorbell number to be used by guest. Set by host. 61 | * @h2c_vdev_db: The doorbell number to be used by host. Set by guest. 62 | */ 63 | struct mic_device_ctrl { 64 | __le64 vdev; 65 | __u8 config_change; 66 | __u8 vdev_reset; 67 | __u8 guest_ack; 68 | __u8 host_ack; 69 | __u8 used_address_updated; 70 | __s8 c2h_vdev_db; 71 | __s8 h2c_vdev_db; 72 | } __attribute__ ((aligned(8))); 73 | 74 | /** 75 | * struct mic_bootparam: Virtio device independent information in device page 76 | * 77 | * @magic: A magic value used by the card to ensure it can see the host 78 | * @h2c_config_db: Host to Card Virtio config doorbell set by card 79 | * @node_id: Unique id of the node 80 | * @h2c_scif_db - Host to card SCIF doorbell set by card 81 | * @c2h_scif_db - Card to host SCIF doorbell set by host 82 | * @scif_host_dma_addr - SCIF host queue pair DMA address 83 | * @scif_card_dma_addr - SCIF card queue pair DMA address 84 | */ 85 | struct mic_bootparam { 86 | __le32 magic; 87 | __s8 h2c_config_db; 88 | __u8 node_id; 89 | __u8 h2c_scif_db; 90 | __u8 c2h_scif_db; 91 | __u64 scif_host_dma_addr; 92 | __u64 scif_card_dma_addr; 93 | } __attribute__ ((aligned(8))); 94 | 95 | /** 96 | * struct mic_device_page: High level representation of the device page 97 | * 98 | * @bootparam: The bootparam structure is used for sharing information and 99 | * status updates between MIC host and card drivers. 100 | * @desc: Array of MIC virtio device descriptors. 101 | */ 102 | struct mic_device_page { 103 | struct mic_bootparam bootparam; 104 | struct mic_device_desc desc[0]; 105 | }; 106 | /** 107 | * struct mic_vqconfig: This is how we expect the device configuration field 108 | * for a virtqueue to be laid out in config space. 109 | * 110 | * @address: Guest/MIC physical address of the virtio ring 111 | * (avail and desc rings) 112 | * @used_address: Guest/MIC physical address of the used ring 113 | * @num: The number of entries in the virtio_ring 114 | */ 115 | struct mic_vqconfig { 116 | __le64 address; 117 | __le64 used_address; 118 | __le16 num; 119 | } __attribute__ ((aligned(8))); 120 | 121 | /* 122 | * The alignment to use between consumer and producer parts of vring. 123 | * This is pagesize for historical reasons. 124 | */ 125 | #define MIC_VIRTIO_RING_ALIGN 4096 126 | 127 | #define MIC_MAX_VRINGS 4 128 | #define MIC_VRING_ENTRIES 128 129 | 130 | /* 131 | * Max vring entries (power of 2) to ensure desc and avail rings 132 | * fit in a single page 133 | */ 134 | #define MIC_MAX_VRING_ENTRIES 128 135 | 136 | /** 137 | * Max size of the desc block in bytes: includes: 138 | * - struct mic_device_desc 139 | * - struct mic_vqconfig (num_vq of these) 140 | * - host and guest features 141 | * - virtio device config space 142 | */ 143 | #define MIC_MAX_DESC_BLK_SIZE 256 144 | 145 | /** 146 | * struct _mic_vring_info - Host vring info exposed to userspace backend 147 | * for the avail index and magic for the card. 148 | * 149 | * @avail_idx: host avail idx 150 | * @magic: A magic debug cookie. 151 | */ 152 | struct _mic_vring_info { 153 | __u16 avail_idx; 154 | __le32 magic; 155 | }; 156 | 157 | /** 158 | * struct mic_vring - Vring information. 159 | * 160 | * @vr: The virtio ring. 161 | * @info: Host vring information exposed to the userspace backend for the 162 | * avail index and magic for the card. 163 | * @va: The va for the buffer allocated for vr and info. 164 | * @len: The length of the buffer required for allocating vr and info. 165 | */ 166 | struct mic_vring { 167 | struct vring vr; 168 | struct _mic_vring_info *info; 169 | void *va; 170 | int len; 171 | }; 172 | 173 | #define mic_aligned_desc_size(d) __mic_align(mic_desc_size(d), 8) 174 | 175 | #ifndef INTEL_MIC_CARD 176 | static inline unsigned mic_desc_size(const struct mic_device_desc *desc) 177 | { 178 | return sizeof(*desc) + desc->num_vq * sizeof(struct mic_vqconfig) 179 | + desc->feature_len * 2 + desc->config_len; 180 | } 181 | 182 | static inline struct mic_vqconfig * 183 | mic_vq_config(const struct mic_device_desc *desc) 184 | { 185 | return (struct mic_vqconfig *)(desc + 1); 186 | } 187 | 188 | static inline __u8 *mic_vq_features(const struct mic_device_desc *desc) 189 | { 190 | return (__u8 *)(mic_vq_config(desc) + desc->num_vq); 191 | } 192 | 193 | static inline __u8 *mic_vq_configspace(const struct mic_device_desc *desc) 194 | { 195 | return mic_vq_features(desc) + desc->feature_len * 2; 196 | } 197 | static inline unsigned mic_total_desc_size(struct mic_device_desc *desc) 198 | { 199 | return mic_aligned_desc_size(desc) + sizeof(struct mic_device_ctrl); 200 | } 201 | #endif 202 | 203 | /* Device page size */ 204 | #define MIC_DP_SIZE 4096 205 | 206 | #define MIC_MAGIC 0xc0ffee00 207 | 208 | /** 209 | * enum mic_states - MIC states. 210 | */ 211 | enum mic_states { 212 | MIC_READY = 0, 213 | MIC_BOOTING, 214 | MIC_ONLINE, 215 | MIC_SHUTTING_DOWN, 216 | MIC_RESETTING, 217 | MIC_RESET_FAILED, 218 | MIC_LAST 219 | }; 220 | 221 | /** 222 | * enum mic_status - MIC status reported by card after 223 | * a host or card initiated shutdown or a card crash. 224 | */ 225 | enum mic_status { 226 | MIC_NOP = 0, 227 | MIC_CRASHED, 228 | MIC_HALTED, 229 | MIC_POWER_OFF, 230 | MIC_RESTART, 231 | MIC_STATUS_LAST 232 | }; 233 | 234 | #endif 235 | -------------------------------------------------------------------------------- /testdir/truecases/cros_ec_dev.c: -------------------------------------------------------------------------------- 1 | /* 2 | * cros_ec_dev - expose the Chrome OS Embedded Controller to user-space 3 | * 4 | * Copyright (C) 2014 Google, Inc. 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "cros_ec_dev.h" 27 | 28 | /* Device variables */ 29 | #define CROS_MAX_DEV 128 30 | static int ec_major; 31 | 32 | static const struct attribute_group *cros_ec_groups[] = { 33 | &cros_ec_attr_group, 34 | &cros_ec_lightbar_attr_group, 35 | &cros_ec_vbc_attr_group, 36 | NULL, 37 | }; 38 | 39 | static struct class cros_class = { 40 | .owner = THIS_MODULE, 41 | .name = "chromeos", 42 | .dev_groups = cros_ec_groups, 43 | }; 44 | 45 | /* Basic communication */ 46 | static int ec_get_version(struct cros_ec_dev *ec, char *str, int maxlen) 47 | { 48 | struct ec_response_get_version *resp; 49 | static const char * const current_image_name[] = { 50 | "unknown", "read-only", "read-write", "invalid", 51 | }; 52 | struct cros_ec_command *msg; 53 | int ret; 54 | 55 | msg = kmalloc(sizeof(*msg) + sizeof(*resp), GFP_KERNEL); 56 | if (!msg) 57 | return -ENOMEM; 58 | 59 | msg->version = 0; 60 | msg->command = EC_CMD_GET_VERSION + ec->cmd_offset; 61 | msg->insize = sizeof(*resp); 62 | msg->outsize = 0; 63 | 64 | ret = cros_ec_cmd_xfer(ec->ec_dev, msg); 65 | if (ret < 0) 66 | goto exit; 67 | 68 | if (msg->result != EC_RES_SUCCESS) { 69 | snprintf(str, maxlen, 70 | "%s\nUnknown EC version: EC returned %d\n", 71 | CROS_EC_DEV_VERSION, msg->result); 72 | ret = -EINVAL; 73 | goto exit; 74 | } 75 | 76 | resp = (struct ec_response_get_version *)msg->data; 77 | if (resp->current_image >= ARRAY_SIZE(current_image_name)) 78 | resp->current_image = 3; /* invalid */ 79 | 80 | snprintf(str, maxlen, "%s\n%s\n%s\n%s\n", CROS_EC_DEV_VERSION, 81 | resp->version_string_ro, resp->version_string_rw, 82 | current_image_name[resp->current_image]); 83 | 84 | ret = 0; 85 | exit: 86 | kfree(msg); 87 | return ret; 88 | } 89 | 90 | /* Device file ops */ 91 | static int ec_device_open(struct inode *inode, struct file *filp) 92 | { 93 | struct cros_ec_dev *ec = container_of(inode->i_cdev, 94 | struct cros_ec_dev, cdev); 95 | filp->private_data = ec; 96 | nonseekable_open(inode, filp); 97 | return 0; 98 | } 99 | 100 | static int ec_device_release(struct inode *inode, struct file *filp) 101 | { 102 | return 0; 103 | } 104 | 105 | static ssize_t ec_device_read(struct file *filp, char __user *buffer, 106 | size_t length, loff_t *offset) 107 | { 108 | struct cros_ec_dev *ec = filp->private_data; 109 | char msg[sizeof(struct ec_response_get_version) + 110 | sizeof(CROS_EC_DEV_VERSION)]; 111 | size_t count; 112 | int ret; 113 | 114 | if (*offset != 0) 115 | return 0; 116 | 117 | ret = ec_get_version(ec, msg, sizeof(msg)); 118 | if (ret) 119 | return ret; 120 | 121 | count = min(length, strlen(msg)); 122 | 123 | if (copy_to_user(buffer, msg, count)) 124 | return -EFAULT; 125 | 126 | *offset = count; 127 | return count; 128 | } 129 | 130 | /* Ioctls */ 131 | static long ec_device_ioctl_xcmd(struct cros_ec_dev *ec, void __user *arg) 132 | { 133 | long ret; 134 | struct cros_ec_command u_cmd; 135 | struct cros_ec_command *s_cmd; 136 | 137 | if (copy_from_user(&u_cmd, arg, sizeof(u_cmd))) 138 | return -EFAULT; 139 | 140 | s_cmd = kmalloc(sizeof(*s_cmd) + max(u_cmd.outsize, u_cmd.insize), 141 | GFP_KERNEL); 142 | if (!s_cmd) 143 | return -ENOMEM; 144 | 145 | if (copy_from_user(s_cmd, arg, sizeof(*s_cmd) + u_cmd.outsize)) { 146 | ret = -EFAULT; 147 | goto exit; 148 | } 149 | 150 | s_cmd->command += ec->cmd_offset; 151 | ret = cros_ec_cmd_xfer(ec->ec_dev, s_cmd); 152 | /* Only copy data to userland if data was received. */ 153 | if (ret < 0) 154 | goto exit; 155 | 156 | if (copy_to_user(arg, s_cmd, sizeof(*s_cmd) + u_cmd.insize)) 157 | ret = -EFAULT; 158 | exit: 159 | kfree(s_cmd); 160 | return ret; 161 | } 162 | 163 | static long ec_device_ioctl_readmem(struct cros_ec_dev *ec, void __user *arg) 164 | { 165 | struct cros_ec_device *ec_dev = ec->ec_dev; 166 | struct cros_ec_readmem s_mem = { }; 167 | long num; 168 | 169 | /* Not every platform supports direct reads */ 170 | if (!ec_dev->cmd_readmem) 171 | return -ENOTTY; 172 | 173 | if (copy_from_user(&s_mem, arg, sizeof(s_mem))) 174 | return -EFAULT; 175 | 176 | num = ec_dev->cmd_readmem(ec_dev, s_mem.offset, s_mem.bytes, 177 | s_mem.buffer); 178 | if (num <= 0) 179 | return num; 180 | 181 | if (copy_to_user((void __user *)arg, &s_mem, sizeof(s_mem))) 182 | return -EFAULT; 183 | 184 | return 0; 185 | } 186 | 187 | static long ec_device_ioctl(struct file *filp, unsigned int cmd, 188 | unsigned long arg) 189 | { 190 | struct cros_ec_dev *ec = filp->private_data; 191 | 192 | if (_IOC_TYPE(cmd) != CROS_EC_DEV_IOC) 193 | return -ENOTTY; 194 | 195 | switch (cmd) { 196 | case CROS_EC_DEV_IOCXCMD: 197 | return ec_device_ioctl_xcmd(ec, (void __user *)arg); 198 | case CROS_EC_DEV_IOCRDMEM: 199 | return ec_device_ioctl_readmem(ec, (void __user *)arg); 200 | } 201 | 202 | return -ENOTTY; 203 | } 204 | 205 | /* Module initialization */ 206 | static const struct file_operations fops = { 207 | .open = ec_device_open, 208 | .release = ec_device_release, 209 | .read = ec_device_read, 210 | .unlocked_ioctl = ec_device_ioctl, 211 | }; 212 | 213 | static void __remove(struct device *dev) 214 | { 215 | struct cros_ec_dev *ec = container_of(dev, struct cros_ec_dev, 216 | class_dev); 217 | kfree(ec); 218 | } 219 | 220 | static int ec_device_probe(struct platform_device *pdev) 221 | { 222 | int retval = -ENOMEM; 223 | struct device *dev = &pdev->dev; 224 | struct cros_ec_platform *ec_platform = dev_get_platdata(dev); 225 | dev_t devno = MKDEV(ec_major, pdev->id); 226 | struct cros_ec_dev *ec = kzalloc(sizeof(*ec), GFP_KERNEL); 227 | 228 | if (!ec) 229 | return retval; 230 | 231 | dev_set_drvdata(dev, ec); 232 | ec->ec_dev = dev_get_drvdata(dev->parent); 233 | ec->dev = dev; 234 | ec->cmd_offset = ec_platform->cmd_offset; 235 | device_initialize(&ec->class_dev); 236 | cdev_init(&ec->cdev, &fops); 237 | 238 | /* 239 | * Add the character device 240 | * Link cdev to the class device to be sure device is not used 241 | * before unbinding it. 242 | */ 243 | ec->cdev.kobj.parent = &ec->class_dev.kobj; 244 | retval = cdev_add(&ec->cdev, devno, 1); 245 | if (retval) { 246 | dev_err(dev, ": failed to add character device\n"); 247 | goto cdev_add_failed; 248 | } 249 | 250 | /* 251 | * Add the class device 252 | * Link to the character device for creating the /dev entry 253 | * in devtmpfs. 254 | */ 255 | ec->class_dev.devt = ec->cdev.dev; 256 | ec->class_dev.class = &cros_class; 257 | ec->class_dev.parent = dev; 258 | ec->class_dev.release = __remove; 259 | 260 | retval = dev_set_name(&ec->class_dev, "%s", ec_platform->ec_name); 261 | if (retval) { 262 | dev_err(dev, "dev_set_name failed => %d\n", retval); 263 | goto set_named_failed; 264 | } 265 | 266 | retval = device_add(&ec->class_dev); 267 | if (retval) { 268 | dev_err(dev, "device_register failed => %d\n", retval); 269 | goto dev_reg_failed; 270 | } 271 | 272 | return 0; 273 | 274 | dev_reg_failed: 275 | set_named_failed: 276 | dev_set_drvdata(dev, NULL); 277 | cdev_del(&ec->cdev); 278 | cdev_add_failed: 279 | kfree(ec); 280 | return retval; 281 | } 282 | 283 | static int ec_device_remove(struct platform_device *pdev) 284 | { 285 | struct cros_ec_dev *ec = dev_get_drvdata(&pdev->dev); 286 | cdev_del(&ec->cdev); 287 | device_unregister(&ec->class_dev); 288 | return 0; 289 | } 290 | 291 | static const struct platform_device_id cros_ec_id[] = { 292 | { "cros-ec-ctl", 0 }, 293 | { /* sentinel */ }, 294 | }; 295 | MODULE_DEVICE_TABLE(platform, cros_ec_id); 296 | 297 | static struct platform_driver cros_ec_dev_driver = { 298 | .driver = { 299 | .name = "cros-ec-ctl", 300 | }, 301 | .probe = ec_device_probe, 302 | .remove = ec_device_remove, 303 | }; 304 | 305 | static int __init cros_ec_dev_init(void) 306 | { 307 | int ret; 308 | dev_t dev = 0; 309 | 310 | ret = class_register(&cros_class); 311 | if (ret) { 312 | pr_err(CROS_EC_DEV_NAME ": failed to register device class\n"); 313 | return ret; 314 | } 315 | 316 | /* Get a range of minor numbers (starting with 0) to work with */ 317 | ret = alloc_chrdev_region(&dev, 0, CROS_MAX_DEV, CROS_EC_DEV_NAME); 318 | if (ret < 0) { 319 | pr_err(CROS_EC_DEV_NAME ": alloc_chrdev_region() failed\n"); 320 | goto failed_chrdevreg; 321 | } 322 | ec_major = MAJOR(dev); 323 | 324 | /* Register the driver */ 325 | ret = platform_driver_register(&cros_ec_dev_driver); 326 | if (ret < 0) { 327 | pr_warn(CROS_EC_DEV_NAME ": can't register driver: %d\n", ret); 328 | goto failed_devreg; 329 | } 330 | return 0; 331 | 332 | failed_devreg: 333 | unregister_chrdev_region(MKDEV(ec_major, 0), CROS_MAX_DEV); 334 | failed_chrdevreg: 335 | class_unregister(&cros_class); 336 | return ret; 337 | } 338 | 339 | static void __exit cros_ec_dev_exit(void) 340 | { 341 | platform_driver_unregister(&cros_ec_dev_driver); 342 | unregister_chrdev(ec_major, CROS_EC_DEV_NAME); 343 | class_unregister(&cros_class); 344 | } 345 | 346 | module_init(cros_ec_dev_init); 347 | module_exit(cros_ec_dev_exit); 348 | 349 | MODULE_AUTHOR("Bill Richardson "); 350 | MODULE_DESCRIPTION("Userspace interface to the Chrome OS Embedded Controller"); 351 | MODULE_VERSION("1.0"); 352 | MODULE_LICENSE("GPL"); 353 | -------------------------------------------------------------------------------- /testdir/truecases/cros_ec_i2c.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ChromeOS EC multi-function device (I2C) 3 | * 4 | * Copyright (C) 2012 Google, Inc 5 | * 6 | * This software is licensed under the terms of the GNU General Public 7 | * License version 2, as published by the Free Software Foundation, and 8 | * may be copied, distributed, and modified under those terms. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | */ 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | /** 27 | * Request format for protocol v3 28 | * byte 0 0xda (EC_COMMAND_PROTOCOL_3) 29 | * byte 1-8 struct ec_host_request 30 | * byte 10- response data 31 | */ 32 | struct ec_host_request_i2c { 33 | /* Always 0xda to backward compatible with v2 struct */ 34 | uint8_t command_protocol; 35 | struct ec_host_request ec_request; 36 | } __packed; 37 | 38 | 39 | /* 40 | * Response format for protocol v3 41 | * byte 0 result code 42 | * byte 1 packet_length 43 | * byte 2-9 struct ec_host_response 44 | * byte 10- response data 45 | */ 46 | struct ec_host_response_i2c { 47 | uint8_t result; 48 | uint8_t packet_length; 49 | struct ec_host_response ec_response; 50 | } __packed; 51 | 52 | static inline struct cros_ec_device *to_ec_dev(struct device *dev) 53 | { 54 | struct i2c_client *client = to_i2c_client(dev); 55 | 56 | return i2c_get_clientdata(client); 57 | } 58 | 59 | static int cros_ec_pkt_xfer_i2c(struct cros_ec_device *ec_dev, 60 | struct cros_ec_command *msg) 61 | { 62 | struct i2c_client *client = ec_dev->priv; 63 | int ret = -ENOMEM; 64 | int i; 65 | int packet_len; 66 | u8 *out_buf = NULL; 67 | u8 *in_buf = NULL; 68 | u8 sum; 69 | struct i2c_msg i2c_msg[2]; 70 | struct ec_host_response *ec_response; 71 | struct ec_host_request_i2c *ec_request_i2c; 72 | struct ec_host_response_i2c *ec_response_i2c; 73 | int request_header_size = sizeof(struct ec_host_request_i2c); 74 | int response_header_size = sizeof(struct ec_host_response_i2c); 75 | 76 | i2c_msg[0].addr = client->addr; 77 | i2c_msg[0].flags = 0; 78 | i2c_msg[1].addr = client->addr; 79 | i2c_msg[1].flags = I2C_M_RD; 80 | 81 | packet_len = msg->insize + response_header_size; 82 | BUG_ON(packet_len > ec_dev->din_size); 83 | in_buf = ec_dev->din; 84 | i2c_msg[1].len = packet_len; 85 | i2c_msg[1].buf = (char *) in_buf; 86 | 87 | packet_len = msg->outsize + request_header_size; 88 | BUG_ON(packet_len > ec_dev->dout_size); 89 | out_buf = ec_dev->dout; 90 | i2c_msg[0].len = packet_len; 91 | i2c_msg[0].buf = (char *) out_buf; 92 | 93 | /* create request data */ 94 | ec_request_i2c = (struct ec_host_request_i2c *) out_buf; 95 | ec_request_i2c->command_protocol = EC_COMMAND_PROTOCOL_3; 96 | 97 | ec_dev->dout++; 98 | ret = cros_ec_prepare_tx(ec_dev, msg); 99 | ec_dev->dout--; 100 | 101 | /* send command to EC and read answer */ 102 | ret = i2c_transfer(client->adapter, i2c_msg, 2); 103 | if (ret < 0) { 104 | dev_dbg(ec_dev->dev, "i2c transfer failed: %d\n", ret); 105 | goto done; 106 | } else if (ret != 2) { 107 | dev_err(ec_dev->dev, "failed to get response: %d\n", ret); 108 | ret = -EIO; 109 | goto done; 110 | } 111 | 112 | ec_response_i2c = (struct ec_host_response_i2c *) in_buf; 113 | msg->result = ec_response_i2c->result; 114 | ec_response = &ec_response_i2c->ec_response; 115 | 116 | switch (msg->result) { 117 | case EC_RES_SUCCESS: 118 | break; 119 | case EC_RES_IN_PROGRESS: 120 | ret = -EAGAIN; 121 | dev_dbg(ec_dev->dev, "command 0x%02x in progress\n", 122 | msg->command); 123 | goto done; 124 | 125 | default: 126 | dev_dbg(ec_dev->dev, "command 0x%02x returned %d\n", 127 | msg->command, msg->result); 128 | /* 129 | * When we send v3 request to v2 ec, ec won't recognize the 130 | * 0xda (EC_COMMAND_PROTOCOL_3) and will return with status 131 | * EC_RES_INVALID_COMMAND with zero data length. 132 | * 133 | * In case of invalid command for v3 protocol the data length 134 | * will be at least sizeof(struct ec_host_response) 135 | */ 136 | if (ec_response_i2c->result == EC_RES_INVALID_COMMAND && 137 | ec_response_i2c->packet_length == 0) { 138 | ret = -EPROTONOSUPPORT; 139 | goto done; 140 | } 141 | } 142 | 143 | if (ec_response_i2c->packet_length < sizeof(struct ec_host_response)) { 144 | dev_err(ec_dev->dev, 145 | "response of %u bytes too short; not a full header\n", 146 | ec_response_i2c->packet_length); 147 | ret = -EBADMSG; 148 | goto done; 149 | } 150 | 151 | if (msg->insize < ec_response->data_len) { 152 | dev_err(ec_dev->dev, 153 | "response data size is too large: expected %u, got %u\n", 154 | msg->insize, 155 | ec_response->data_len); 156 | ret = -EMSGSIZE; 157 | goto done; 158 | } 159 | 160 | /* copy response packet payload and compute checksum */ 161 | sum = 0; 162 | for (i = 0; i < sizeof(struct ec_host_response); i++) 163 | sum += ((u8 *)ec_response)[i]; 164 | 165 | memcpy(msg->data, 166 | in_buf + response_header_size, 167 | ec_response->data_len); 168 | for (i = 0; i < ec_response->data_len; i++) 169 | sum += msg->data[i]; 170 | 171 | /* All bytes should sum to zero */ 172 | if (sum) { 173 | dev_err(ec_dev->dev, "bad packet checksum\n"); 174 | ret = -EBADMSG; 175 | goto done; 176 | } 177 | 178 | ret = ec_response->data_len; 179 | 180 | done: 181 | if (msg->command == EC_CMD_REBOOT_EC) 182 | msleep(EC_REBOOT_DELAY_MS); 183 | 184 | return ret; 185 | } 186 | 187 | static int cros_ec_cmd_xfer_i2c(struct cros_ec_device *ec_dev, 188 | struct cros_ec_command *msg) 189 | { 190 | struct i2c_client *client = ec_dev->priv; 191 | int ret = -ENOMEM; 192 | int i; 193 | int len; 194 | int packet_len; 195 | u8 *out_buf = NULL; 196 | u8 *in_buf = NULL; 197 | u8 sum; 198 | struct i2c_msg i2c_msg[2]; 199 | 200 | i2c_msg[0].addr = client->addr; 201 | i2c_msg[0].flags = 0; 202 | i2c_msg[1].addr = client->addr; 203 | i2c_msg[1].flags = I2C_M_RD; 204 | 205 | /* 206 | * allocate larger packet (one byte for checksum, one byte for 207 | * length, and one for result code) 208 | */ 209 | packet_len = msg->insize + 3; 210 | in_buf = kzalloc(packet_len, GFP_KERNEL); 211 | if (!in_buf) 212 | goto done; 213 | i2c_msg[1].len = packet_len; 214 | i2c_msg[1].buf = (char *)in_buf; 215 | 216 | /* 217 | * allocate larger packet (one byte for checksum, one for 218 | * command code, one for length, and one for command version) 219 | */ 220 | packet_len = msg->outsize + 4; 221 | out_buf = kzalloc(packet_len, GFP_KERNEL); 222 | if (!out_buf) 223 | goto done; 224 | i2c_msg[0].len = packet_len; 225 | i2c_msg[0].buf = (char *)out_buf; 226 | 227 | out_buf[0] = EC_CMD_VERSION0 + msg->version; 228 | out_buf[1] = msg->command; 229 | out_buf[2] = msg->outsize; 230 | 231 | /* copy message payload and compute checksum */ 232 | sum = out_buf[0] + out_buf[1] + out_buf[2]; 233 | for (i = 0; i < msg->outsize; i++) { 234 | out_buf[3 + i] = msg->data[i]; 235 | sum += out_buf[3 + i]; 236 | } 237 | out_buf[3 + msg->outsize] = sum; 238 | 239 | /* send command to EC and read answer */ 240 | ret = i2c_transfer(client->adapter, i2c_msg, 2); 241 | if (ret < 0) { 242 | dev_err(ec_dev->dev, "i2c transfer failed: %d\n", ret); 243 | goto done; 244 | } else if (ret != 2) { 245 | dev_err(ec_dev->dev, "failed to get response: %d\n", ret); 246 | ret = -EIO; 247 | goto done; 248 | } 249 | 250 | /* check response error code */ 251 | msg->result = i2c_msg[1].buf[0]; 252 | ret = cros_ec_check_result(ec_dev, msg); 253 | if (ret) 254 | goto done; 255 | 256 | len = in_buf[1]; 257 | if (len > msg->insize) { 258 | dev_err(ec_dev->dev, "packet too long (%d bytes, expected %d)", 259 | len, msg->insize); 260 | ret = -ENOSPC; 261 | goto done; 262 | } 263 | 264 | /* copy response packet payload and compute checksum */ 265 | sum = in_buf[0] + in_buf[1]; 266 | for (i = 0; i < len; i++) { 267 | msg->data[i] = in_buf[2 + i]; 268 | sum += in_buf[2 + i]; 269 | } 270 | dev_dbg(ec_dev->dev, "packet: %*ph, sum = %02x\n", 271 | i2c_msg[1].len, in_buf, sum); 272 | if (sum != in_buf[2 + len]) { 273 | dev_err(ec_dev->dev, "bad packet checksum\n"); 274 | ret = -EBADMSG; 275 | goto done; 276 | } 277 | 278 | ret = len; 279 | done: 280 | kfree(in_buf); 281 | kfree(out_buf); 282 | if (msg->command == EC_CMD_REBOOT_EC) 283 | msleep(EC_REBOOT_DELAY_MS); 284 | 285 | return ret; 286 | } 287 | 288 | static int cros_ec_i2c_probe(struct i2c_client *client, 289 | const struct i2c_device_id *dev_id) 290 | { 291 | struct device *dev = &client->dev; 292 | struct cros_ec_device *ec_dev = NULL; 293 | int err; 294 | 295 | ec_dev = devm_kzalloc(dev, sizeof(*ec_dev), GFP_KERNEL); 296 | if (!ec_dev) 297 | return -ENOMEM; 298 | 299 | i2c_set_clientdata(client, ec_dev); 300 | ec_dev->dev = dev; 301 | ec_dev->priv = client; 302 | ec_dev->irq = client->irq; 303 | ec_dev->cmd_xfer = cros_ec_cmd_xfer_i2c; 304 | ec_dev->pkt_xfer = cros_ec_pkt_xfer_i2c; 305 | ec_dev->phys_name = client->adapter->name; 306 | ec_dev->din_size = sizeof(struct ec_host_response_i2c) + 307 | sizeof(struct ec_response_get_protocol_info); 308 | ec_dev->dout_size = sizeof(struct ec_host_request_i2c); 309 | 310 | err = cros_ec_register(ec_dev); 311 | if (err) { 312 | dev_err(dev, "cannot register EC\n"); 313 | return err; 314 | } 315 | 316 | return 0; 317 | } 318 | 319 | static int cros_ec_i2c_remove(struct i2c_client *client) 320 | { 321 | struct cros_ec_device *ec_dev = i2c_get_clientdata(client); 322 | 323 | cros_ec_remove(ec_dev); 324 | 325 | return 0; 326 | } 327 | 328 | #ifdef CONFIG_PM_SLEEP 329 | static int cros_ec_i2c_suspend(struct device *dev) 330 | { 331 | struct cros_ec_device *ec_dev = to_ec_dev(dev); 332 | 333 | return cros_ec_suspend(ec_dev); 334 | } 335 | 336 | static int cros_ec_i2c_resume(struct device *dev) 337 | { 338 | struct cros_ec_device *ec_dev = to_ec_dev(dev); 339 | 340 | return cros_ec_resume(ec_dev); 341 | } 342 | #endif 343 | 344 | static SIMPLE_DEV_PM_OPS(cros_ec_i2c_pm_ops, cros_ec_i2c_suspend, 345 | cros_ec_i2c_resume); 346 | 347 | static const struct of_device_id cros_ec_i2c_of_match[] = { 348 | { .compatible = "google,cros-ec-i2c", }, 349 | { /* sentinel */ }, 350 | }; 351 | MODULE_DEVICE_TABLE(of, cros_ec_i2c_of_match); 352 | 353 | static const struct i2c_device_id cros_ec_i2c_id[] = { 354 | { "cros-ec-i2c", 0 }, 355 | { } 356 | }; 357 | MODULE_DEVICE_TABLE(i2c, cros_ec_i2c_id); 358 | 359 | static struct i2c_driver cros_ec_driver = { 360 | .driver = { 361 | .name = "cros-ec-i2c", 362 | .of_match_table = of_match_ptr(cros_ec_i2c_of_match), 363 | .pm = &cros_ec_i2c_pm_ops, 364 | }, 365 | .probe = cros_ec_i2c_probe, 366 | .remove = cros_ec_i2c_remove, 367 | .id_table = cros_ec_i2c_id, 368 | }; 369 | 370 | module_i2c_driver(cros_ec_driver); 371 | 372 | MODULE_LICENSE("GPL"); 373 | MODULE_DESCRIPTION("ChromeOS EC multi function device"); 374 | -------------------------------------------------------------------------------- /testdir/truecases/cros_ec_proto.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ChromeOS EC communication protocol helper functions 3 | * 4 | * Copyright (C) 2015 Google, Inc 5 | * 6 | * This software is licensed under the terms of the GNU General Public 7 | * License version 2, as published by the Free Software Foundation, and 8 | * may be copied, distributed, and modified under those terms. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | #define EC_COMMAND_RETRIES 50 24 | 25 | static int prepare_packet(struct cros_ec_device *ec_dev, 26 | struct cros_ec_command *msg) 27 | { 28 | struct ec_host_request *request; 29 | u8 *out; 30 | int i; 31 | u8 csum = 0; 32 | 33 | BUG_ON(ec_dev->proto_version != EC_HOST_REQUEST_VERSION); 34 | BUG_ON(msg->outsize + sizeof(*request) > ec_dev->dout_size); 35 | 36 | out = ec_dev->dout; 37 | request = (struct ec_host_request *)out; 38 | request->struct_version = EC_HOST_REQUEST_VERSION; 39 | request->checksum = 0; 40 | request->command = msg->command; 41 | request->command_version = msg->version; 42 | request->reserved = 0; 43 | request->data_len = msg->outsize; 44 | 45 | for (i = 0; i < sizeof(*request); i++) 46 | csum += out[i]; 47 | 48 | /* Copy data and update checksum */ 49 | memcpy(out + sizeof(*request), msg->data, msg->outsize); 50 | for (i = 0; i < msg->outsize; i++) 51 | csum += msg->data[i]; 52 | 53 | request->checksum = -csum; 54 | 55 | return sizeof(*request) + msg->outsize; 56 | } 57 | 58 | static int send_command(struct cros_ec_device *ec_dev, 59 | struct cros_ec_command *msg) 60 | { 61 | int ret; 62 | 63 | if (ec_dev->proto_version > 2) 64 | ret = ec_dev->pkt_xfer(ec_dev, msg); 65 | else 66 | ret = ec_dev->cmd_xfer(ec_dev, msg); 67 | 68 | if (msg->result == EC_RES_IN_PROGRESS) { 69 | int i; 70 | struct cros_ec_command *status_msg; 71 | struct ec_response_get_comms_status *status; 72 | 73 | status_msg = kmalloc(sizeof(*status_msg) + sizeof(*status), 74 | GFP_KERNEL); 75 | if (!status_msg) 76 | return -ENOMEM; 77 | 78 | status_msg->version = 0; 79 | status_msg->command = EC_CMD_GET_COMMS_STATUS; 80 | status_msg->insize = sizeof(*status); 81 | status_msg->outsize = 0; 82 | 83 | /* 84 | * Query the EC's status until it's no longer busy or 85 | * we encounter an error. 86 | */ 87 | for (i = 0; i < EC_COMMAND_RETRIES; i++) { 88 | usleep_range(10000, 11000); 89 | 90 | ret = ec_dev->cmd_xfer(ec_dev, status_msg); 91 | if (ret < 0) 92 | break; 93 | 94 | msg->result = status_msg->result; 95 | if (status_msg->result != EC_RES_SUCCESS) 96 | break; 97 | 98 | status = (struct ec_response_get_comms_status *) 99 | status_msg->data; 100 | if (!(status->flags & EC_COMMS_STATUS_PROCESSING)) 101 | break; 102 | } 103 | 104 | kfree(status_msg); 105 | } 106 | 107 | return ret; 108 | } 109 | 110 | int cros_ec_prepare_tx(struct cros_ec_device *ec_dev, 111 | struct cros_ec_command *msg) 112 | { 113 | u8 *out; 114 | u8 csum; 115 | int i; 116 | 117 | if (ec_dev->proto_version > 2) 118 | return prepare_packet(ec_dev, msg); 119 | 120 | BUG_ON(msg->outsize > EC_PROTO2_MAX_PARAM_SIZE); 121 | out = ec_dev->dout; 122 | out[0] = EC_CMD_VERSION0 + msg->version; 123 | out[1] = msg->command; 124 | out[2] = msg->outsize; 125 | csum = out[0] + out[1] + out[2]; 126 | for (i = 0; i < msg->outsize; i++) 127 | csum += out[EC_MSG_TX_HEADER_BYTES + i] = msg->data[i]; 128 | out[EC_MSG_TX_HEADER_BYTES + msg->outsize] = csum; 129 | 130 | return EC_MSG_TX_PROTO_BYTES + msg->outsize; 131 | } 132 | EXPORT_SYMBOL(cros_ec_prepare_tx); 133 | 134 | int cros_ec_check_result(struct cros_ec_device *ec_dev, 135 | struct cros_ec_command *msg) 136 | { 137 | switch (msg->result) { 138 | case EC_RES_SUCCESS: 139 | return 0; 140 | case EC_RES_IN_PROGRESS: 141 | dev_dbg(ec_dev->dev, "command 0x%02x in progress\n", 142 | msg->command); 143 | return -EAGAIN; 144 | default: 145 | dev_dbg(ec_dev->dev, "command 0x%02x returned %d\n", 146 | msg->command, msg->result); 147 | return 0; 148 | } 149 | } 150 | EXPORT_SYMBOL(cros_ec_check_result); 151 | 152 | static int cros_ec_host_command_proto_query(struct cros_ec_device *ec_dev, 153 | int devidx, 154 | struct cros_ec_command *msg) 155 | { 156 | /* 157 | * Try using v3+ to query for supported protocols. If this 158 | * command fails, fall back to v2. Returns the highest protocol 159 | * supported by the EC. 160 | * Also sets the max request/response/passthru size. 161 | */ 162 | int ret; 163 | 164 | if (!ec_dev->pkt_xfer) 165 | return -EPROTONOSUPPORT; 166 | 167 | memset(msg, 0, sizeof(*msg)); 168 | msg->command = EC_CMD_PASSTHRU_OFFSET(devidx) | EC_CMD_GET_PROTOCOL_INFO; 169 | msg->insize = sizeof(struct ec_response_get_protocol_info); 170 | 171 | ret = send_command(ec_dev, msg); 172 | 173 | if (ret < 0) { 174 | dev_dbg(ec_dev->dev, 175 | "failed to check for EC[%d] protocol version: %d\n", 176 | devidx, ret); 177 | return ret; 178 | } 179 | 180 | if (devidx > 0 && msg->result == EC_RES_INVALID_COMMAND) 181 | return -ENODEV; 182 | else if (msg->result != EC_RES_SUCCESS) 183 | return msg->result; 184 | 185 | return 0; 186 | } 187 | 188 | static int cros_ec_host_command_proto_query_v2(struct cros_ec_device *ec_dev) 189 | { 190 | struct cros_ec_command *msg; 191 | struct ec_params_hello *hello_params; 192 | struct ec_response_hello *hello_response; 193 | int ret; 194 | int len = max(sizeof(*hello_params), sizeof(*hello_response)); 195 | 196 | msg = kmalloc(sizeof(*msg) + len, GFP_KERNEL); 197 | if (!msg) 198 | return -ENOMEM; 199 | 200 | msg->version = 0; 201 | msg->command = EC_CMD_HELLO; 202 | hello_params = (struct ec_params_hello *)msg->data; 203 | msg->outsize = sizeof(*hello_params); 204 | hello_response = (struct ec_response_hello *)msg->data; 205 | msg->insize = sizeof(*hello_response); 206 | 207 | hello_params->in_data = 0xa0b0c0d0; 208 | 209 | ret = send_command(ec_dev, msg); 210 | 211 | if (ret < 0) { 212 | dev_dbg(ec_dev->dev, 213 | "EC failed to respond to v2 hello: %d\n", 214 | ret); 215 | goto exit; 216 | } else if (msg->result != EC_RES_SUCCESS) { 217 | dev_err(ec_dev->dev, 218 | "EC responded to v2 hello with error: %d\n", 219 | msg->result); 220 | ret = msg->result; 221 | goto exit; 222 | } else if (hello_response->out_data != 0xa1b2c3d4) { 223 | dev_err(ec_dev->dev, 224 | "EC responded to v2 hello with bad result: %u\n", 225 | hello_response->out_data); 226 | ret = -EBADMSG; 227 | goto exit; 228 | } 229 | 230 | ret = 0; 231 | 232 | exit: 233 | kfree(msg); 234 | return ret; 235 | } 236 | 237 | int cros_ec_query_all(struct cros_ec_device *ec_dev) 238 | { 239 | struct device *dev = ec_dev->dev; 240 | struct cros_ec_command *proto_msg; 241 | struct ec_response_get_protocol_info *proto_info; 242 | int ret; 243 | 244 | proto_msg = kzalloc(sizeof(*proto_msg) + sizeof(*proto_info), 245 | GFP_KERNEL); 246 | if (!proto_msg) 247 | return -ENOMEM; 248 | 249 | /* First try sending with proto v3. */ 250 | ec_dev->proto_version = 3; 251 | ret = cros_ec_host_command_proto_query(ec_dev, 0, proto_msg); 252 | 253 | if (ret == 0) { 254 | proto_info = (struct ec_response_get_protocol_info *) 255 | proto_msg->data; 256 | ec_dev->max_request = proto_info->max_request_packet_size - 257 | sizeof(struct ec_host_request); 258 | ec_dev->max_response = proto_info->max_response_packet_size - 259 | sizeof(struct ec_host_response); 260 | ec_dev->proto_version = 261 | min(EC_HOST_REQUEST_VERSION, 262 | fls(proto_info->protocol_versions) - 1); 263 | dev_dbg(ec_dev->dev, 264 | "using proto v%u\n", 265 | ec_dev->proto_version); 266 | 267 | ec_dev->din_size = ec_dev->max_response + 268 | sizeof(struct ec_host_response) + 269 | EC_MAX_RESPONSE_OVERHEAD; 270 | ec_dev->dout_size = ec_dev->max_request + 271 | sizeof(struct ec_host_request) + 272 | EC_MAX_REQUEST_OVERHEAD; 273 | 274 | /* 275 | * Check for PD 276 | */ 277 | ret = cros_ec_host_command_proto_query(ec_dev, 1, proto_msg); 278 | 279 | if (ret) { 280 | dev_dbg(ec_dev->dev, "no PD chip found: %d\n", ret); 281 | ec_dev->max_passthru = 0; 282 | } else { 283 | dev_dbg(ec_dev->dev, "found PD chip\n"); 284 | ec_dev->max_passthru = 285 | proto_info->max_request_packet_size - 286 | sizeof(struct ec_host_request); 287 | } 288 | } else { 289 | /* Try querying with a v2 hello message. */ 290 | ec_dev->proto_version = 2; 291 | ret = cros_ec_host_command_proto_query_v2(ec_dev); 292 | 293 | if (ret == 0) { 294 | /* V2 hello succeeded. */ 295 | dev_dbg(ec_dev->dev, "falling back to proto v2\n"); 296 | 297 | ec_dev->max_request = EC_PROTO2_MAX_PARAM_SIZE; 298 | ec_dev->max_response = EC_PROTO2_MAX_PARAM_SIZE; 299 | ec_dev->max_passthru = 0; 300 | ec_dev->pkt_xfer = NULL; 301 | ec_dev->din_size = EC_MSG_BYTES; 302 | ec_dev->dout_size = EC_MSG_BYTES; 303 | } else { 304 | /* 305 | * It's possible for a test to occur too early when 306 | * the EC isn't listening. If this happens, we'll 307 | * test later when the first command is run. 308 | */ 309 | ec_dev->proto_version = EC_PROTO_VERSION_UNKNOWN; 310 | dev_dbg(ec_dev->dev, "EC query failed: %d\n", ret); 311 | goto exit; 312 | } 313 | } 314 | 315 | devm_kfree(dev, ec_dev->din); 316 | devm_kfree(dev, ec_dev->dout); 317 | 318 | ec_dev->din = devm_kzalloc(dev, ec_dev->din_size, GFP_KERNEL); 319 | if (!ec_dev->din) { 320 | ret = -ENOMEM; 321 | goto exit; 322 | } 323 | 324 | ec_dev->dout = devm_kzalloc(dev, ec_dev->dout_size, GFP_KERNEL); 325 | if (!ec_dev->dout) { 326 | devm_kfree(dev, ec_dev->din); 327 | ret = -ENOMEM; 328 | goto exit; 329 | } 330 | 331 | exit: 332 | kfree(proto_msg); 333 | return ret; 334 | } 335 | EXPORT_SYMBOL(cros_ec_query_all); 336 | 337 | int cros_ec_cmd_xfer(struct cros_ec_device *ec_dev, 338 | struct cros_ec_command *msg) 339 | { 340 | int ret; 341 | 342 | mutex_lock(&ec_dev->lock); 343 | if (ec_dev->proto_version == EC_PROTO_VERSION_UNKNOWN) { 344 | ret = cros_ec_query_all(ec_dev); 345 | if (ret) { 346 | dev_err(ec_dev->dev, 347 | "EC version unknown and query failed; aborting command\n"); 348 | mutex_unlock(&ec_dev->lock); 349 | return ret; 350 | } 351 | } 352 | 353 | if (msg->insize > ec_dev->max_response) { 354 | dev_dbg(ec_dev->dev, "clamping message receive buffer\n"); 355 | msg->insize = ec_dev->max_response; 356 | } 357 | 358 | if (msg->command < EC_CMD_PASSTHRU_OFFSET(1)) { 359 | if (msg->outsize > ec_dev->max_request) { 360 | dev_err(ec_dev->dev, 361 | "request of size %u is too big (max: %u)\n", 362 | msg->outsize, 363 | ec_dev->max_request); 364 | mutex_unlock(&ec_dev->lock); 365 | return -EMSGSIZE; 366 | } 367 | } else { 368 | if (msg->outsize > ec_dev->max_passthru) { 369 | dev_err(ec_dev->dev, 370 | "passthru rq of size %u is too big (max: %u)\n", 371 | msg->outsize, 372 | ec_dev->max_passthru); 373 | mutex_unlock(&ec_dev->lock); 374 | return -EMSGSIZE; 375 | } 376 | } 377 | ret = send_command(ec_dev, msg); 378 | mutex_unlock(&ec_dev->lock); 379 | 380 | return ret; 381 | } 382 | EXPORT_SYMBOL(cros_ec_cmd_xfer); 383 | -------------------------------------------------------------------------------- /pattern_match_freebsd.cocci: -------------------------------------------------------------------------------- 1 | //define global variable 2 | @initialize:python@ 3 | count << virtual.count; 4 | @@ 5 | #-----------------------------Post Matching Process------------------------------ 6 | def print_and_log(filename,first,second,count): 7 | 8 | 9 | print "No. ", count, " file: ", filename 10 | print "--first fetch: line ",first 11 | print "--second fetch: line ",second 12 | print "------------------------------------\n" 13 | 14 | logfile = open('result.txt','a') 15 | logfile.write("No." + count + " File: \n" + str(filename) + "\n") 16 | logfile.write("--first fetch: line " + str(first) + "\n") 17 | logfile.write("--second fetch: line " + str(second) + "\n") 18 | logfile.write("-------------------------------\n") 19 | 20 | logfile.close() 21 | 22 | def post_match_process(p1,p2,src,ptr,count): 23 | 24 | filename = p1[0].file 25 | first = p1[0].line 26 | second = p2[0].line 27 | 28 | src_str = str(src) 29 | ptr_str = str(ptr) 30 | #print "src1:", src_str 31 | #print "src2:", ptr_str 32 | #print "first:", first 33 | #print "second:", second 34 | 35 | # remove loop case, first and second fetch are not supposed to be in the same line. 36 | if first == second: 37 | return 38 | # remove reverse loop case, where first fetch behand second fetch but in last loop . 39 | if int(first) > int(second): 40 | return 41 | # remove case of get_user(a, src++) or get_user(a, src + 4) 42 | if src_str.find("+") != -1 or ptr_str.find("+") != -1: 43 | return 44 | # remove case of get_user(a, src[i]) 45 | if src_str.find("[") != -1 or ptr_str.find("[") != -1: 46 | return 47 | # remove case of get_user(a, src--) or get_user(a, src - 4) 48 | if src_str.find("-") != -1 and src_str.find("->") == -1: 49 | return 50 | if ptr_str.find("-") != -1 and ptr_str.find("->") == -1: 51 | return 52 | # remove false matching of src ===> (int*)src , but leave function call like u64_to_uptr(ctl_sccb.sccb) 53 | if src_str.find("(") == 0 or ptr_str.find("(") == 0: 54 | return 55 | 56 | if count: 57 | count = str(int(count) + 1) 58 | else: 59 | count = "1" 60 | 61 | print_and_log(filename, first, second, count) 62 | 63 | return count 64 | 65 | 66 | //---------------------Pattern Matching Rules----------------------------------- 67 | //----------------------------------- case 1: normal case without src assignment 68 | @ rule1 disable drop_cast exists @ 69 | expression addr,exp1,exp2,src,size1,size2,offset; 70 | position p1,p2; 71 | identifier func; 72 | type T1,T2; 73 | @@ 74 | func(...){ 75 | ... 76 | ( 77 | get_user(exp1, (T1)src)@p1 78 | | 79 | get_user(exp1, src)@p1 80 | | 81 | __get_user(exp1, (T1)src)@p1 82 | | 83 | __get_user(exp1, src)@p1 84 | | 85 | copyin_nofault((T1)src, exp1, size1)@p1 86 | | 87 | copyin_nofault(src, exp1, size1)@p1 88 | | 89 | copyin((T1)src, exp1, size1)@p1 90 | | 91 | copyin(src, exp1, size1)@p1 92 | 93 | ) 94 | ... when any 95 | when != src += offset 96 | when != src = src + offset 97 | when != src++ 98 | when != src -=offset 99 | when != src = src - offset 100 | when != src-- 101 | when != src = addr 102 | 103 | ( 104 | get_user(exp2, (T2)src)@p2 105 | | 106 | get_user(exp2, src)@p2 107 | | 108 | __get_user(exp2,(T2)src)@p2 109 | | 110 | __get_user(exp2, src)@p2 111 | | 112 | copyin((T2)src, exp2,size2)@p2 113 | | 114 | copyin(src, exp2, size2)@p2 115 | | 116 | copyin_nofault((T2)src, exp2, size2)@p2 117 | | 118 | copyin_nofault(src, exp2, size2)@p2 119 | ) 120 | ... 121 | } 122 | 123 | @script:python@ 124 | p11 << rule1.p1; 125 | p12 << rule1.p2; 126 | s1 << rule1.src; 127 | @@ 128 | 129 | print "src1:", str(s1) 130 | if p11 and p12: 131 | coccilib.report.print_report(p11[0],"rule1 First fetch") 132 | coccilib.report.print_report(p12[0],"rule1 Second fetch") 133 | 134 | ret = post_match_process(p11, p12, s1, s1, count) 135 | if ret: 136 | count = ret 137 | 138 | 139 | 140 | //--------------------------------------- case 2: ptr = src at beginning, ptr first 141 | @ rule2 disable drop_cast exists @ 142 | identifier func; 143 | expression addr,exp1,exp2,src,ptr,size1,size2,offset; 144 | position p0,p1,p2; 145 | type T0,T1,T2; 146 | @@ 147 | 148 | 149 | func(...){ 150 | ... 151 | ( 152 | ptr = (T0)src@p0 // potential assignment case 153 | | 154 | ptr = src@p0 155 | ) 156 | ... 157 | ( 158 | get_user(exp1, (T1)ptr)@p1 159 | | 160 | get_user(exp1, ptr)@p1 161 | | 162 | __get_user(exp1, (T1)ptr)@p1 163 | | 164 | __get_user(exp1, ptr)@p1 165 | | 166 | copyin_nofault((T1)ptr, exp1, size1)@p1 167 | | 168 | copyin_nofault(ptr, exp1, size1)@p1 169 | | 170 | copyin((T1)ptr, exp1, size1)@p1 171 | | 172 | copyin(ptr, exp1, size1)@p1 173 | ) 174 | ... 175 | when != src += offset 176 | when != src = src + offset 177 | when != src++ 178 | when != src -=offset 179 | when != src = src - offset 180 | when != src-- 181 | when != src = addr 182 | ( 183 | get_user(exp2, (T2)src)@p2 184 | | 185 | get_user(exp2, src)@p2 186 | | 187 | __get_user(exp2,(T2)src)@p2 188 | | 189 | __get_user(exp2, src)@p2 190 | | 191 | copyin((T2)src, exp2, size2)@p2 192 | | 193 | copyin(src, exp2, size2)@p2 194 | | 195 | copyin_nofault((T2)src, exp2, size2)@p2 196 | | 197 | copyin_nofault(src, exp2, size2)@p2 198 | ) 199 | ... 200 | } 201 | 202 | @script:python@ 203 | p21 << rule2.p1; 204 | p22 << rule2.p2; 205 | p2 << rule2.ptr; 206 | s2 << rule2.src; 207 | @@ 208 | print "src2:", str(s2) 209 | print "ptr2:", str(p2) 210 | if p21 and p22: 211 | coccilib.report.print_report(p21[0],"rule2 First fetch") 212 | coccilib.report.print_report(p22[0],"rule2 Second fetch") 213 | ret = post_match_process(p21, p22, s2, p2, count) 214 | if ret: 215 | count = ret 216 | 217 | //--------------------------------------- case 3: ptr = src at beginning, src first 218 | @ rule3 disable drop_cast exists @ 219 | identifier func; 220 | expression addr,exp1,exp2,src,ptr,size1,size2,offset; 221 | position p0,p1,p2; 222 | type T0,T1,T2; 223 | @@ 224 | 225 | 226 | func(...){ 227 | ... 228 | ( 229 | ptr = (T0)src@p0 // potential assignment case 230 | | 231 | ptr = src@p0 232 | ) 233 | ... 234 | ( 235 | get_user(exp1, (T1)src)@p1 236 | | 237 | get_user(exp1, src)@p1 238 | | 239 | __get_user(exp1, (T1)src)@p1 240 | | 241 | __get_user(exp1, src)@p1 242 | | 243 | copyin_nofault((T1)src, exp1, size1)@p1 244 | | 245 | copyin_nofault(src, exp1, size1)@p1 246 | | 247 | copyin((T1)src, exp1, size1)@p1 248 | | 249 | copyin(src, exp1, size1)@p1 250 | ) 251 | ... 252 | when != ptr += offset 253 | when != ptr = ptr + offset 254 | when != ptr++ 255 | when != ptr -=offset 256 | when != ptr = ptr - offset 257 | when != ptr-- 258 | when != ptr = addr 259 | ( 260 | get_user(exp2, (T2)ptr)@p2 261 | | 262 | get_user(exp2, ptr)@p2 263 | | 264 | __get_user(exp2,(T2)ptr)@p2 265 | | 266 | __get_user(exp2, ptr)@p2 267 | | 268 | copyin((T2)ptr, exp2, size2)@p2 269 | | 270 | copyin( ptr, exp2, size2)@p2 271 | | 272 | copyin_nofault((T2)ptr, exp2, size2)@p2 273 | | 274 | copyin_nofault(ptr, exp2, size2)@p2 275 | ) 276 | ... 277 | } 278 | 279 | @script:python@ 280 | p31 << rule3.p1; 281 | p32 << rule3.p2; 282 | p3 << rule3.ptr; 283 | s3 << rule3.src; 284 | @@ 285 | print "src3:", str(s3) 286 | print "ptr3:", str(p3) 287 | if p31 and p32: 288 | coccilib.report.print_report(p31[0],"rule3 First fetch") 289 | coccilib.report.print_report(p32[0],"rule3 Second fetch") 290 | ret = post_match_process(p31, p32, s3, p3, count) 291 | if ret: 292 | count = ret 293 | 294 | //----------------------------------- case 4: ptr = src at middle 295 | 296 | @ rule4 disable drop_cast exists @ 297 | identifier func; 298 | expression addr,exp1,exp2,src,ptr,size1,size2,offset; 299 | position p0,p1,p2; 300 | type T0,T1,T2; 301 | @@ 302 | 303 | 304 | func(...){ 305 | ... 306 | ( 307 | get_user(exp1, (T1)src)@p1 308 | | 309 | get_user(exp1, src)@p1 310 | | 311 | __get_user(exp1, (T1)src)@p1 312 | | 313 | __get_user(exp1, src)@p1 314 | | 315 | copyin_nofault((T1)src, exp1, size1)@p1 316 | | 317 | copyin_nofault(src, exp1, size1)@p1 318 | | 319 | copyin((T1)src, exp1, size1)@p1 320 | | 321 | copyin(src, exp1, size1)@p1 322 | ) 323 | ... 324 | when != src += offset 325 | when != src = src + offset 326 | when != src++ 327 | when != src -=offset 328 | when != src = src - offset 329 | when != src-- 330 | when != src = addr 331 | 332 | ( 333 | ptr = (T0)src@p0 // potential assignment case 334 | | 335 | ptr = src@p0 336 | ) 337 | ... 338 | when != ptr += offset 339 | when != ptr = ptr + offset 340 | when != ptr++ 341 | when != ptr -=offset 342 | when != ptr = ptr - offset 343 | when != ptr-- 344 | when != ptr = addr 345 | 346 | ( 347 | get_user(exp2, (T2)ptr)@p2 348 | | 349 | get_user(exp2, ptr)@p2 350 | | 351 | __get_user(exp2,(T2)ptr)@p2 352 | | 353 | __get_user(exp2, ptr)@p2 354 | | 355 | copyin((T2)ptr, exp2,size2)@p2 356 | | 357 | copyin(ptr, exp2, size2)@p2 358 | | 359 | copyin_nofault((T2)ptr, exp2, size2)@p2 360 | | 361 | copyin_nofault(ptr, exp2, size2)@p2 362 | ) 363 | ... 364 | } 365 | 366 | @script:python@ 367 | p41 << rule4.p1; 368 | p42 << rule4.p2; 369 | p4 << rule4.ptr; 370 | s4 << rule4.src; 371 | @@ 372 | print "src4:", str(s4) 373 | print "ptr4:", str(p4) 374 | if p41 and p42: 375 | coccilib.report.print_report(p41[0],"rule4 First fetch") 376 | coccilib.report.print_report(p42[0],"rule4 Second fetch") 377 | ret = post_match_process(p41, p42, s4, p4, count) 378 | if ret: 379 | count = ret 380 | 381 | //----------------------------------- case 5: first element, then ptr, copy from structure 382 | @ rule5 disable drop_cast exists @ 383 | identifier func, e1; 384 | expression addr,exp1,exp2,src,size1,size2,offset; 385 | position p1,p2; 386 | type T1,T2; 387 | @@ 388 | 389 | 390 | func(...){ 391 | ... 392 | ( 393 | get_user(exp1, (T1)src->e1)@p1 394 | | 395 | get_user(exp1, src->e1)@p1 396 | | 397 | get_user(exp1, &(src->e1))@p1 398 | | 399 | __get_user(exp1, (T1)src->e1)@p1 400 | | 401 | __get_user(exp1, src->e1)@p1 402 | | 403 | __get_user(exp1, &(src->e1))@p1 404 | | 405 | copyin_nofault((T1)src->e1, exp1, size1)@p1 406 | | 407 | copyin_nofault(src->e1, exp1, size1)@p1 408 | | 409 | copyin_nofault(&(src->e1), exp1, size1)@p1 410 | | 411 | copyin((T1)src->e1, exp1, size1)@p1 412 | | 413 | copyin(src->e1, exp1, size1)@p1 414 | | 415 | copyin(&(src->e1), exp1, size1)@p1 416 | ) 417 | ... 418 | when != src += offset 419 | when != src = src + offset 420 | when != src++ 421 | when != src -=offset 422 | when != src = src - offset 423 | when != src-- 424 | when != src = addr 425 | ( 426 | get_user(exp2,(T2)src)@p2 427 | | 428 | get_user(exp2,src)@p2 429 | | 430 | __get_user(exp2,(T2)src)@p2 431 | | 432 | __get_user(exp2,src)@p2 433 | | 434 | copyin((T2)src, exp2, size2)@p2 435 | | 436 | copyin(src, exp2, size2)@p2 437 | | 438 | copyin_nofault((T2)src, exp2, size2)@p2 439 | | 440 | copyin_nofault(src, exp2, size2)@p2 441 | ) 442 | ... 443 | } 444 | 445 | @script:python@ 446 | p51 << rule5.p1; 447 | p52 << rule5.p2; 448 | s5 << rule5.src; 449 | e5 << rule5.e1; 450 | @@ 451 | print "src5:", str(s5) 452 | print "e5:", str(e5) 453 | if p51 and p52: 454 | coccilib.report.print_report(p51[0],"rule5 First fetch") 455 | coccilib.report.print_report(p52[0],"rule5 Second fetch") 456 | ret = post_match_process(p51, p52, s5, e5, count) 457 | if ret: 458 | count = ret 459 | 460 | 461 | //----------------------------------- case 6: first element, then ptr, copy from pointer 462 | @ rule6 disable drop_cast exists @ 463 | identifier func, e1; 464 | expression addr,exp1,exp2,src,size1,size2,offset; 465 | position p1,p2; 466 | type T1,T2; 467 | @@ 468 | func(...){ 469 | ... 470 | ( 471 | get_user(exp1, (T1)src.e1)@p1 472 | | 473 | get_user(exp1, src.e1)@p1 474 | | 475 | get_user(exp1, &(src.e1))@p1 476 | | 477 | __get_user(exp1, (T1)src.e1)@p1 478 | | 479 | __get_user(exp1, src.e1)@p1 480 | | 481 | __get_user(exp1, &(src.e1))@p1 482 | | 483 | copyin_nofault((T1)src.e1, exp1, size1)@p1 484 | | 485 | copyin_nofault(src.e1, exp1, size1)@p1 486 | | 487 | copyin_nofault(&(src.e1), exp1, size1)@p1 488 | | 489 | copyin((T1)src.e1, exp1, size1)@p1 490 | | 491 | copyin(src.e1, exp1, size1)@p1 492 | | 493 | copyin(&(src.e1), exp1, size1)@p1 494 | ) 495 | ... 496 | when != &src += offset 497 | when != &src = &src + offset 498 | when != &src++ 499 | when != &src -=offset 500 | when != &src = &src - offset 501 | when != &src-- 502 | when != &src = &addr 503 | ( 504 | get_user(exp2,(T2)&src)@p2 505 | | 506 | get_user(exp2,&src)@p2 507 | | 508 | __get_user(exp2,(T2)&src)@p2 509 | | 510 | __get_user(exp2,&src)@p2 511 | | 512 | copyin((T2)&src, exp2, size2)@p2 513 | | 514 | copyin(&src, exp2, size2)@p2 515 | | 516 | copyin_nofault((T2)&src, exp2, size2)@p2 517 | | 518 | copyin_nofault(&src, exp2, size2)@p2 519 | ) 520 | ... 521 | } 522 | 523 | @script:python@ 524 | p61 << rule6.p1; 525 | p62 << rule6.p2; 526 | s6 << rule6.src; 527 | e6 << rule6.e1; 528 | @@ 529 | print "src6:", str(s6) 530 | print "e6:", str(e6) 531 | if p61 and p62: 532 | coccilib.report.print_report(p61[0],"rule6 First fetch") 533 | coccilib.report.print_report(p62[0],"rule6 Second fetch") 534 | ret = post_match_process(p61, p62, s6, e6, count) 535 | if ret: 536 | count = ret 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | -------------------------------------------------------------------------------- /pattern_match_linux.cocci: -------------------------------------------------------------------------------- 1 | //define global variable 2 | @initialize:python@ 3 | count << virtual.count; 4 | @@ 5 | #-----------------------------Post Matching Process------------------------------ 6 | def print_and_log(filename,first,second,count): 7 | 8 | 9 | print "No. ", count, " file: ", filename 10 | print "--first fetch: line ",first 11 | print "--second fetch: line ",second 12 | print "------------------------------------\n" 13 | 14 | logfile = open('result.txt','a') 15 | logfile.write("No." + count + " File: \n" + str(filename) + "\n") 16 | logfile.write("--first fetch: line " + str(first) + "\n") 17 | logfile.write("--second fetch: line " + str(second) + "\n") 18 | logfile.write("-------------------------------\n") 19 | 20 | logfile.close() 21 | 22 | def post_match_process(p1,p2,src,ptr,count): 23 | filename = p1[0].file 24 | first = p1[0].line 25 | second = p2[0].line 26 | 27 | src_str = str(src) 28 | ptr_str = str(ptr) 29 | #print "src1:", src_str 30 | #print "src2:", ptr_str 31 | #print "first:", first 32 | #print "second:", second 33 | 34 | # remove loop case, first and second fetch are not supposed to be in the same line. 35 | if first == second: 36 | return 37 | # remove reverse loop case, where first fetch behand second fetch but in last loop . 38 | if int(first) > int(second): 39 | return 40 | # remove case of get_user(a, src++) or get_user(a, src + 4) 41 | if src_str.find("+") != -1 or ptr_str.find("+") != -1: 42 | return 43 | # remove case of get_user(a, src[i]) 44 | if src_str.find("[") != -1 or ptr_str.find("[") != -1: 45 | return 46 | # remove case of get_user(a, src--) or get_user(a, src - 4) 47 | if src_str.find("-") != -1 and src_str.find("->") == -1: 48 | return 49 | if ptr_str.find("-") != -1 and ptr_str.find("->") == -1: 50 | return 51 | # remove false matching of src ===> (int*)src , but leave function call like u64_to_uptr(ctl_sccb.sccb) 52 | if src_str.find("(") == 0 or ptr_str.find("(") == 0: 53 | return 54 | 55 | if count: 56 | count = str(int(count) + 1) 57 | else: 58 | count = "1" 59 | 60 | print_and_log(filename, first, second, count) 61 | 62 | return count 63 | 64 | 65 | 66 | //---------------------Pattern Matching Rules----------------------------------- 67 | //----------------------------------- case 1: normal case without src assignment 68 | @ rule1 disable drop_cast exists @ 69 | expression addr,exp1,exp2,src,size1,size2,offset; 70 | position p1,p2; 71 | identifier func; 72 | type T1,T2; 73 | @@ 74 | func(...){ 75 | ... 76 | ( 77 | get_user(exp1, (T1)src)@p1 78 | | 79 | get_user(exp1, src)@p1 80 | | 81 | __get_user(exp1, (T1)src)@p1 82 | | 83 | __get_user(exp1, src)@p1 84 | | 85 | copy_from_user(exp1, (T1)src, size1)@p1 86 | | 87 | copy_from_user(exp1, src, size1)@p1 88 | | 89 | __copy_from_user(exp1, (T1)src, size1)@p1 90 | | 91 | __copy_from_user(exp1, src, size1)@p1 92 | 93 | ) 94 | ... when any 95 | when != src += offset 96 | when != src = src + offset 97 | when != src++ 98 | when != src -=offset 99 | when != src = src - offset 100 | when != src-- 101 | when != src = addr 102 | 103 | ( 104 | get_user(exp2, (T2)src)@p2 105 | | 106 | get_user(exp2, src)@p2 107 | | 108 | __get_user(exp2,(T2)src)@p2 109 | | 110 | __get_user(exp2, src)@p2 111 | | 112 | __copy_from_user(exp2,(T2)src,size2)@p2 113 | | 114 | __copy_from_user(exp2, src,size2)@p2 115 | | 116 | copy_from_user(exp2,(T2)src,size2)@p2 117 | | 118 | copy_from_user(exp2, src,size2)@p2 119 | ) 120 | ... 121 | } 122 | 123 | @script:python@ 124 | p11 << rule1.p1; 125 | p12 << rule1.p2; 126 | s1 << rule1.src; 127 | @@ 128 | 129 | print "src1:", str(s1) 130 | if p11 and p12: 131 | coccilib.report.print_report(p11[0],"rule1 First fetch") 132 | coccilib.report.print_report(p12[0],"rule1 Second fetch") 133 | 134 | ret = post_match_process(p11, p12, s1, s1, count) 135 | if ret: 136 | count = ret 137 | 138 | //--------------------------------------- case 2: ptr = src at beginning, ptr first 139 | @ rule2 disable drop_cast exists @ 140 | identifier func; 141 | expression addr,exp1,exp2,src,ptr,size1,size2,offset; 142 | position p0,p1,p2; 143 | type T0,T1,T2; 144 | @@ 145 | 146 | 147 | func(...){ 148 | ... 149 | ( 150 | ptr = (T0)src@p0 // potential assignment case 151 | | 152 | ptr = src@p0 153 | ) 154 | ... 155 | ( 156 | get_user(exp1, (T1)ptr)@p1 157 | | 158 | get_user(exp1, ptr)@p1 159 | | 160 | __get_user(exp1, (T1)ptr)@p1 161 | | 162 | __get_user(exp1, ptr)@p1 163 | | 164 | copy_from_user(exp1, (T1)ptr,size1)@p1 165 | | 166 | copy_from_user(exp1, ptr,size1)@p1 167 | | 168 | __copy_from_user(exp1, (T1)ptr,size1)@p1 169 | | 170 | __copy_from_user(exp1, ptr,size1)@p1 171 | ) 172 | ... 173 | when != src += offset 174 | when != src = src + offset 175 | when != src++ 176 | when != src -=offset 177 | when != src = src - offset 178 | when != src-- 179 | when != src = addr 180 | ( 181 | get_user(exp2, (T2)src)@p2 182 | | 183 | get_user(exp2, src)@p2 184 | | 185 | __get_user(exp2,(T2)src)@p2 186 | | 187 | __get_user(exp2, src)@p2 188 | | 189 | __copy_from_user(exp2,(T2)src,size2)@p2 190 | | 191 | __copy_from_user(exp2, src,size2)@p2 192 | | 193 | copy_from_user(exp2,(T2)src,size2)@p2 194 | | 195 | copy_from_user(exp2, src,size2)@p2 196 | ) 197 | ... 198 | } 199 | 200 | @script:python@ 201 | p21 << rule2.p1; 202 | p22 << rule2.p2; 203 | p2 << rule2.ptr; 204 | s2 << rule2.src; 205 | @@ 206 | print "src2:", str(s2) 207 | print "ptr2:", str(p2) 208 | if p21 and p22: 209 | coccilib.report.print_report(p21[0],"rule2 First fetch") 210 | coccilib.report.print_report(p22[0],"rule2 Second fetch") 211 | ret = post_match_process(p21, p22, s2, p2, count) 212 | if ret: 213 | count = ret 214 | //--------------------------------------- case 3: ptr = src at beginning, src first 215 | @ rule3 disable drop_cast exists @ 216 | identifier func; 217 | expression addr,exp1,exp2,src,ptr,size1,size2,offset; 218 | position p0,p1,p2; 219 | type T0,T1,T2; 220 | @@ 221 | 222 | 223 | func(...){ 224 | ... 225 | ( 226 | ptr = (T0)src@p0 // potential assignment case 227 | | 228 | ptr = src@p0 229 | ) 230 | ... 231 | ( 232 | get_user(exp1, (T1)src)@p1 233 | | 234 | get_user(exp1, src)@p1 235 | | 236 | __get_user(exp1, (T1)src)@p1 237 | | 238 | __get_user(exp1, src)@p1 239 | | 240 | copy_from_user(exp1, (T1)src,size1)@p1 241 | | 242 | copy_from_user(exp1, src,size1)@p1 243 | | 244 | __copy_from_user(exp1, (T1)src,size1)@p1 245 | | 246 | __copy_from_user(exp1, src,size1)@p1 247 | ) 248 | ... 249 | when != ptr += offset 250 | when != ptr = ptr + offset 251 | when != ptr++ 252 | when != ptr -=offset 253 | when != ptr = ptr - offset 254 | when != ptr-- 255 | when != ptr = addr 256 | ( 257 | get_user(exp2, (T2)ptr)@p2 258 | | 259 | get_user(exp2, ptr)@p2 260 | | 261 | __get_user(exp2,(T2)ptr)@p2 262 | | 263 | __get_user(exp2, ptr)@p2 264 | | 265 | __copy_from_user(exp2,(T2)ptr,size2)@p2 266 | | 267 | __copy_from_user(exp2, ptr,size2)@p2 268 | | 269 | copy_from_user(exp2,(T2)ptr,size2)@p2 270 | | 271 | copy_from_user(exp2, ptr,size2)@p2 272 | ) 273 | ... 274 | } 275 | 276 | @script:python@ 277 | p31 << rule3.p1; 278 | p32 << rule3.p2; 279 | p3 << rule3.ptr; 280 | s3 << rule3.src; 281 | @@ 282 | print "src3:", str(s3) 283 | print "ptr3:", str(p3) 284 | if p31 and p32: 285 | coccilib.report.print_report(p31[0],"rule3 First fetch") 286 | coccilib.report.print_report(p32[0],"rule3 Second fetch") 287 | ret = post_match_process(p31, p32, s3, p3, count) 288 | if ret: 289 | count = ret 290 | //----------------------------------- case 4: ptr = src at middle 291 | 292 | @ rule4 disable drop_cast exists @ 293 | identifier func; 294 | expression addr,exp1,exp2,src,ptr,size1,size2,offset; 295 | position p0,p1,p2; 296 | type T0,T1,T2; 297 | @@ 298 | 299 | 300 | func(...){ 301 | ... 302 | ( 303 | get_user(exp1, (T1)src)@p1 304 | | 305 | get_user(exp1, src)@p1 306 | | 307 | __get_user(exp1, (T1)src)@p1 308 | | 309 | __get_user(exp1, src)@p1 310 | | 311 | copy_from_user(exp1, (T1)src,size1)@p1 312 | | 313 | copy_from_user(exp1, src,size1)@p1 314 | | 315 | __copy_from_user(exp1, (T1)src,size1)@p1 316 | | 317 | __copy_from_user(exp1, src,size1)@p1 318 | ) 319 | ... 320 | when != src += offset 321 | when != src = src + offset 322 | when != src++ 323 | when != src -=offset 324 | when != src = src - offset 325 | when != src-- 326 | when != src = addr 327 | 328 | ( 329 | ptr = (T0)src@p0 // potential assignment case 330 | | 331 | ptr = src@p0 332 | ) 333 | ... 334 | when != ptr += offset 335 | when != ptr = ptr + offset 336 | when != ptr++ 337 | when != ptr -=offset 338 | when != ptr = ptr - offset 339 | when != ptr-- 340 | when != ptr = addr 341 | 342 | ( 343 | get_user(exp2, (T2)ptr)@p2 344 | | 345 | get_user(exp2, ptr)@p2 346 | | 347 | __get_user(exp2,(T2)ptr)@p2 348 | | 349 | __get_user(exp2, ptr)@p2 350 | | 351 | __copy_from_user(exp2,(T2)ptr,size2)@p2 352 | | 353 | __copy_from_user(exp2, ptr,size2)@p2 354 | | 355 | copy_from_user(exp2,(T2)ptr,size2)@p2 356 | | 357 | copy_from_user(exp2, ptr,size2)@p2 358 | ) 359 | ... 360 | } 361 | 362 | @script:python@ 363 | p41 << rule4.p1; 364 | p42 << rule4.p2; 365 | p4 << rule4.ptr; 366 | s4 << rule4.src; 367 | @@ 368 | print "src4:", str(s4) 369 | print "ptr4:", str(p4) 370 | if p41 and p42: 371 | coccilib.report.print_report(p41[0],"rule4 First fetch") 372 | coccilib.report.print_report(p42[0],"rule4 Second fetch") 373 | ret = post_match_process(p41, p42, s4, p4, count) 374 | if ret: 375 | count = ret 376 | //----------------------------------- case 5: first element, then ptr, copy from structure 377 | @ rule5 disable drop_cast exists @ 378 | identifier func, e1; 379 | expression addr,exp1,exp2,src,size1,size2,offset; 380 | position p1,p2; 381 | type T1,T2; 382 | @@ 383 | 384 | 385 | func(...){ 386 | ... 387 | ( 388 | get_user(exp1, (T1)src->e1)@p1 389 | | 390 | get_user(exp1, src->e1)@p1 391 | | 392 | get_user(exp1, &(src->e1))@p1 393 | | 394 | __get_user(exp1, (T1)src->e1)@p1 395 | | 396 | __get_user(exp1, src->e1)@p1 397 | | 398 | __get_user(exp1, &(src->e1))@p1 399 | | 400 | copy_from_user(exp1, (T1)src->e1,size1)@p1 401 | | 402 | copy_from_user(exp1, src->e1,size1)@p1 403 | | 404 | copy_from_user(exp1, &(src->e1),size1)@p1 405 | | 406 | __copy_from_user(exp1, (T1)src->e1,size1)@p1 407 | | 408 | __copy_from_user(exp1, src->e1,size1)@p1 409 | | 410 | __copy_from_user(exp1, &(src->e1),size1)@p1 411 | ) 412 | ... 413 | when != src += offset 414 | when != src = src + offset 415 | when != src++ 416 | when != src -=offset 417 | when != src = src - offset 418 | when != src-- 419 | when != src = addr 420 | ( 421 | get_user(exp2,(T2)src)@p2 422 | | 423 | get_user(exp2,src)@p2 424 | | 425 | __get_user(exp2,(T2)src)@p2 426 | | 427 | __get_user(exp2,src)@p2 428 | | 429 | __copy_from_user(exp2,(T2)src,size2)@p2 430 | | 431 | __copy_from_user(exp2,src,size2)@p2 432 | | 433 | copy_from_user(exp2,(T2)src,size2)@p2 434 | | 435 | copy_from_user(exp2,src,size2)@p2 436 | ) 437 | ... 438 | } 439 | 440 | @script:python@ 441 | p51 << rule5.p1; 442 | p52 << rule5.p2; 443 | s5 << rule5.src; 444 | e5 << rule5.e1; 445 | @@ 446 | print "src5:", str(s5) 447 | print "e5:", str(e5) 448 | if p51 and p52: 449 | coccilib.report.print_report(p51[0],"rule5 First fetch") 450 | coccilib.report.print_report(p52[0],"rule5 Second fetch") 451 | ret = post_match_process(p51, p52, s5, e5, count) 452 | if ret: 453 | count = ret 454 | 455 | 456 | //----------------------------------- case 6: first element, then ptr, copy from pointer 457 | @ rule6 disable drop_cast exists @ 458 | identifier func, e1; 459 | expression addr,exp1,exp2,src,size1,size2,offset; 460 | position p1,p2; 461 | type T1,T2; 462 | @@ 463 | func(...){ 464 | ... 465 | ( 466 | get_user(exp1, (T1)src.e1)@p1 467 | | 468 | get_user(exp1, src.e1)@p1 469 | | 470 | get_user(exp1, &(src.e1))@p1 471 | | 472 | __get_user(exp1, (T1)src.e1)@p1 473 | | 474 | __get_user(exp1, src.e1)@p1 475 | | 476 | __get_user(exp1, &(src.e1))@p1 477 | | 478 | copy_from_user(exp1, (T1)src.e1, size1)@p1 479 | | 480 | copy_from_user(exp1, src.e1, size1)@p1 481 | | 482 | copy_from_user(exp1, &(src.e1), size1)@p1 483 | | 484 | __copy_from_user(exp1, (T1)src.e1, size1)@p1 485 | | 486 | __copy_from_user(exp1, src.e1, size1)@p1 487 | | 488 | __copy_from_user(exp1, &(src.e1), size1)@p1 489 | ) 490 | ... 491 | when != &src += offset 492 | when != &src = &src + offset 493 | when != &src++ 494 | when != &src -=offset 495 | when != &src = &src - offset 496 | when != &src-- 497 | when != &src = &addr 498 | ( 499 | get_user(exp2,(T2)&src)@p2 500 | | 501 | get_user(exp2,&src)@p2 502 | | 503 | __get_user(exp2,(T2)&src)@p2 504 | | 505 | __get_user(exp2,&src)@p2 506 | | 507 | __copy_from_user(exp2,(T2)&src,size2)@p2 508 | | 509 | __copy_from_user(exp2,&src,size2)@p2 510 | | 511 | copy_from_user(exp2,(T2)&src,size2)@p2 512 | | 513 | copy_from_user(exp2,&src,size2)@p2 514 | ) 515 | ... 516 | } 517 | 518 | @script:python@ 519 | p61 << rule6.p1; 520 | p62 << rule6.p2; 521 | s6 << rule6.src; 522 | e6 << rule6.e1; 523 | @@ 524 | print "src6:", str(s6) 525 | print "e6:", str(e6) 526 | if p61 and p62: 527 | coccilib.report.print_report(p61[0],"rule6 First fetch") 528 | coccilib.report.print_report(p62[0],"rule6 Second fetch") 529 | ret = post_match_process(p61, p62, s6, e6, count) 530 | if ret: 531 | count = ret 532 | 533 | 534 | 535 | -------------------------------------------------------------------------------- /testdir/truecases/mic_virtio.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Intel MIC Platform Software Stack (MPSS) 3 | * 4 | * Copyright(c) 2013 Intel Corporation. 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License, version 2, as 8 | * published by the Free Software Foundation. 9 | * 10 | * This program is distributed in the hope that it will be useful, but 11 | * WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | * General Public License for more details. 14 | * 15 | * The full GNU General Public License is included in this distribution in 16 | * the file called "COPYING". 17 | * 18 | * Intel MIC Host driver. 19 | * 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include "../common/mic_dev.h" 27 | #include "mic_device.h" 28 | #include "mic_smpt.h" 29 | #include "mic_virtio.h" 30 | 31 | /* 32 | * Size of the internal buffer used during DMA's as an intermediate buffer 33 | * for copy to/from user. 34 | */ 35 | #define MIC_INT_DMA_BUF_SIZE PAGE_ALIGN(64 * 1024ULL) 36 | 37 | static int mic_sync_dma(struct mic_device *mdev, dma_addr_t dst, 38 | dma_addr_t src, size_t len) 39 | { 40 | int err = 0; 41 | struct dma_async_tx_descriptor *tx; 42 | struct dma_chan *mic_ch = mdev->dma_ch[0]; 43 | 44 | if (!mic_ch) { 45 | err = -EBUSY; 46 | goto error; 47 | } 48 | 49 | tx = mic_ch->device->device_prep_dma_memcpy(mic_ch, dst, src, len, 50 | DMA_PREP_FENCE); 51 | if (!tx) { 52 | err = -ENOMEM; 53 | goto error; 54 | } else { 55 | dma_cookie_t cookie = tx->tx_submit(tx); 56 | 57 | err = dma_submit_error(cookie); 58 | if (err) 59 | goto error; 60 | err = dma_sync_wait(mic_ch, cookie); 61 | } 62 | error: 63 | if (err) 64 | dev_err(&mdev->pdev->dev, "%s %d err %d\n", 65 | __func__, __LINE__, err); 66 | return err; 67 | } 68 | 69 | /* 70 | * Initiates the copies across the PCIe bus from card memory to a user 71 | * space buffer. When transfers are done using DMA, source/destination 72 | * addresses and transfer length must follow the alignment requirements of 73 | * the MIC DMA engine. 74 | */ 75 | static int mic_virtio_copy_to_user(struct mic_vdev *mvdev, void __user *ubuf, 76 | size_t len, u64 daddr, size_t dlen, 77 | int vr_idx) 78 | { 79 | struct mic_device *mdev = mvdev->mdev; 80 | void __iomem *dbuf = mdev->aper.va + daddr; 81 | struct mic_vringh *mvr = &mvdev->mvr[vr_idx]; 82 | size_t dma_alignment = 1 << mdev->dma_ch[0]->device->copy_align; 83 | size_t dma_offset; 84 | size_t partlen; 85 | int err; 86 | 87 | dma_offset = daddr - round_down(daddr, dma_alignment); 88 | daddr -= dma_offset; 89 | len += dma_offset; 90 | 91 | while (len) { 92 | partlen = min_t(size_t, len, MIC_INT_DMA_BUF_SIZE); 93 | 94 | err = mic_sync_dma(mdev, mvr->buf_da, daddr, 95 | ALIGN(partlen, dma_alignment)); 96 | if (err) 97 | goto err; 98 | 99 | if (copy_to_user(ubuf, mvr->buf + dma_offset, 100 | partlen - dma_offset)) { 101 | err = -EFAULT; 102 | goto err; 103 | } 104 | daddr += partlen; 105 | ubuf += partlen; 106 | dbuf += partlen; 107 | mvdev->in_bytes_dma += partlen; 108 | mvdev->in_bytes += partlen; 109 | len -= partlen; 110 | dma_offset = 0; 111 | } 112 | return 0; 113 | err: 114 | dev_err(mic_dev(mvdev), "%s %d err %d\n", __func__, __LINE__, err); 115 | return err; 116 | } 117 | 118 | /* 119 | * Initiates copies across the PCIe bus from a user space buffer to card 120 | * memory. When transfers are done using DMA, source/destination addresses 121 | * and transfer length must follow the alignment requirements of the MIC 122 | * DMA engine. 123 | */ 124 | static int mic_virtio_copy_from_user(struct mic_vdev *mvdev, void __user *ubuf, 125 | size_t len, u64 daddr, size_t dlen, 126 | int vr_idx) 127 | { 128 | struct mic_device *mdev = mvdev->mdev; 129 | void __iomem *dbuf = mdev->aper.va + daddr; 130 | struct mic_vringh *mvr = &mvdev->mvr[vr_idx]; 131 | size_t dma_alignment = 1 << mdev->dma_ch[0]->device->copy_align; 132 | size_t partlen; 133 | int err; 134 | 135 | if (daddr & (dma_alignment - 1)) { 136 | mvdev->tx_dst_unaligned += len; 137 | goto memcpy; 138 | } else if (ALIGN(len, dma_alignment) > dlen) { 139 | mvdev->tx_len_unaligned += len; 140 | goto memcpy; 141 | } 142 | 143 | while (len) { 144 | partlen = min_t(size_t, len, MIC_INT_DMA_BUF_SIZE); 145 | 146 | if (copy_from_user(mvr->buf, ubuf, partlen)) { 147 | err = -EFAULT; 148 | goto err; 149 | } 150 | err = mic_sync_dma(mdev, daddr, mvr->buf_da, 151 | ALIGN(partlen, dma_alignment)); 152 | if (err) 153 | goto err; 154 | daddr += partlen; 155 | ubuf += partlen; 156 | dbuf += partlen; 157 | mvdev->out_bytes_dma += partlen; 158 | mvdev->out_bytes += partlen; 159 | len -= partlen; 160 | } 161 | memcpy: 162 | /* 163 | * We are copying to IO below and should ideally use something 164 | * like copy_from_user_toio(..) if it existed. 165 | */ 166 | if (copy_from_user((void __force *)dbuf, ubuf, len)) { 167 | err = -EFAULT; 168 | goto err; 169 | } 170 | mvdev->out_bytes += len; 171 | return 0; 172 | err: 173 | dev_err(mic_dev(mvdev), "%s %d err %d\n", __func__, __LINE__, err); 174 | return err; 175 | } 176 | 177 | #define MIC_VRINGH_READ true 178 | 179 | /* The function to call to notify the card about added buffers */ 180 | static void mic_notify(struct vringh *vrh) 181 | { 182 | struct mic_vringh *mvrh = container_of(vrh, struct mic_vringh, vrh); 183 | struct mic_vdev *mvdev = mvrh->mvdev; 184 | s8 db = mvdev->dc->h2c_vdev_db; 185 | 186 | if (db != -1) 187 | mvdev->mdev->ops->send_intr(mvdev->mdev, db); 188 | } 189 | 190 | /* Determine the total number of bytes consumed in a VRINGH KIOV */ 191 | static inline u32 mic_vringh_iov_consumed(struct vringh_kiov *iov) 192 | { 193 | int i; 194 | u32 total = iov->consumed; 195 | 196 | for (i = 0; i < iov->i; i++) 197 | total += iov->iov[i].iov_len; 198 | return total; 199 | } 200 | 201 | /* 202 | * Traverse the VRINGH KIOV and issue the APIs to trigger the copies. 203 | * This API is heavily based on the vringh_iov_xfer(..) implementation 204 | * in vringh.c. The reason we cannot reuse vringh_iov_pull_kern(..) 205 | * and vringh_iov_push_kern(..) directly is because there is no 206 | * way to override the VRINGH xfer(..) routines as of v3.10. 207 | */ 208 | static int mic_vringh_copy(struct mic_vdev *mvdev, struct vringh_kiov *iov, 209 | void __user *ubuf, size_t len, bool read, int vr_idx, 210 | size_t *out_len) 211 | { 212 | int ret = 0; 213 | size_t partlen, tot_len = 0; 214 | 215 | while (len && iov->i < iov->used) { 216 | partlen = min(iov->iov[iov->i].iov_len, len); 217 | if (read) 218 | ret = mic_virtio_copy_to_user(mvdev, ubuf, partlen, 219 | (u64)iov->iov[iov->i].iov_base, 220 | iov->iov[iov->i].iov_len, 221 | vr_idx); 222 | else 223 | ret = mic_virtio_copy_from_user(mvdev, ubuf, partlen, 224 | (u64)iov->iov[iov->i].iov_base, 225 | iov->iov[iov->i].iov_len, 226 | vr_idx); 227 | if (ret) { 228 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 229 | __func__, __LINE__, ret); 230 | break; 231 | } 232 | len -= partlen; 233 | ubuf += partlen; 234 | tot_len += partlen; 235 | iov->consumed += partlen; 236 | iov->iov[iov->i].iov_len -= partlen; 237 | iov->iov[iov->i].iov_base += partlen; 238 | if (!iov->iov[iov->i].iov_len) { 239 | /* Fix up old iov element then increment. */ 240 | iov->iov[iov->i].iov_len = iov->consumed; 241 | iov->iov[iov->i].iov_base -= iov->consumed; 242 | 243 | iov->consumed = 0; 244 | iov->i++; 245 | } 246 | } 247 | *out_len = tot_len; 248 | return ret; 249 | } 250 | 251 | /* 252 | * Use the standard VRINGH infrastructure in the kernel to fetch new 253 | * descriptors, initiate the copies and update the used ring. 254 | */ 255 | static int _mic_virtio_copy(struct mic_vdev *mvdev, 256 | struct mic_copy_desc *copy) 257 | { 258 | int ret = 0; 259 | u32 iovcnt = copy->iovcnt; 260 | struct iovec iov; 261 | struct iovec __user *u_iov = copy->iov; 262 | void __user *ubuf = NULL; 263 | struct mic_vringh *mvr = &mvdev->mvr[copy->vr_idx]; 264 | struct vringh_kiov *riov = &mvr->riov; 265 | struct vringh_kiov *wiov = &mvr->wiov; 266 | struct vringh *vrh = &mvr->vrh; 267 | u16 *head = &mvr->head; 268 | struct mic_vring *vr = &mvr->vring; 269 | size_t len = 0, out_len; 270 | 271 | copy->out_len = 0; 272 | /* Fetch a new IOVEC if all previous elements have been processed */ 273 | if (riov->i == riov->used && wiov->i == wiov->used) { 274 | ret = vringh_getdesc_kern(vrh, riov, wiov, 275 | head, GFP_KERNEL); 276 | /* Check if there are available descriptors */ 277 | if (ret <= 0) 278 | return ret; 279 | } 280 | while (iovcnt) { 281 | if (!len) { 282 | /* Copy over a new iovec from user space. */ 283 | ret = copy_from_user(&iov, u_iov, sizeof(*u_iov)); 284 | if (ret) { 285 | ret = -EINVAL; 286 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 287 | __func__, __LINE__, ret); 288 | break; 289 | } 290 | len = iov.iov_len; 291 | ubuf = iov.iov_base; 292 | } 293 | /* Issue all the read descriptors first */ 294 | ret = mic_vringh_copy(mvdev, riov, ubuf, len, MIC_VRINGH_READ, 295 | copy->vr_idx, &out_len); 296 | if (ret) { 297 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 298 | __func__, __LINE__, ret); 299 | break; 300 | } 301 | len -= out_len; 302 | ubuf += out_len; 303 | copy->out_len += out_len; 304 | /* Issue the write descriptors next */ 305 | ret = mic_vringh_copy(mvdev, wiov, ubuf, len, !MIC_VRINGH_READ, 306 | copy->vr_idx, &out_len); 307 | if (ret) { 308 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 309 | __func__, __LINE__, ret); 310 | break; 311 | } 312 | len -= out_len; 313 | ubuf += out_len; 314 | copy->out_len += out_len; 315 | if (!len) { 316 | /* One user space iovec is now completed */ 317 | iovcnt--; 318 | u_iov++; 319 | } 320 | /* Exit loop if all elements in KIOVs have been processed. */ 321 | if (riov->i == riov->used && wiov->i == wiov->used) 322 | break; 323 | } 324 | /* 325 | * Update the used ring if a descriptor was available and some data was 326 | * copied in/out and the user asked for a used ring update. 327 | */ 328 | if (*head != USHRT_MAX && copy->out_len && copy->update_used) { 329 | u32 total = 0; 330 | 331 | /* Determine the total data consumed */ 332 | total += mic_vringh_iov_consumed(riov); 333 | total += mic_vringh_iov_consumed(wiov); 334 | vringh_complete_kern(vrh, *head, total); 335 | *head = USHRT_MAX; 336 | if (vringh_need_notify_kern(vrh) > 0) 337 | vringh_notify(vrh); 338 | vringh_kiov_cleanup(riov); 339 | vringh_kiov_cleanup(wiov); 340 | /* Update avail idx for user space */ 341 | vr->info->avail_idx = vrh->last_avail_idx; 342 | } 343 | return ret; 344 | } 345 | 346 | static inline int mic_verify_copy_args(struct mic_vdev *mvdev, 347 | struct mic_copy_desc *copy) 348 | { 349 | if (copy->vr_idx >= mvdev->dd->num_vq) { 350 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 351 | __func__, __LINE__, -EINVAL); 352 | return -EINVAL; 353 | } 354 | return 0; 355 | } 356 | 357 | /* Copy a specified number of virtio descriptors in a chain */ 358 | int mic_virtio_copy_desc(struct mic_vdev *mvdev, 359 | struct mic_copy_desc *copy) 360 | { 361 | int err; 362 | struct mic_vringh *mvr = &mvdev->mvr[copy->vr_idx]; 363 | 364 | err = mic_verify_copy_args(mvdev, copy); 365 | if (err) 366 | return err; 367 | 368 | mutex_lock(&mvr->vr_mutex); 369 | if (!mic_vdevup(mvdev)) { 370 | err = -ENODEV; 371 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 372 | __func__, __LINE__, err); 373 | goto err; 374 | } 375 | err = _mic_virtio_copy(mvdev, copy); 376 | if (err) { 377 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 378 | __func__, __LINE__, err); 379 | } 380 | err: 381 | mutex_unlock(&mvr->vr_mutex); 382 | return err; 383 | } 384 | 385 | static void mic_virtio_init_post(struct mic_vdev *mvdev) 386 | { 387 | struct mic_vqconfig *vqconfig = mic_vq_config(mvdev->dd); 388 | int i; 389 | 390 | for (i = 0; i < mvdev->dd->num_vq; i++) { 391 | if (!le64_to_cpu(vqconfig[i].used_address)) { 392 | dev_warn(mic_dev(mvdev), "used_address zero??\n"); 393 | continue; 394 | } 395 | mvdev->mvr[i].vrh.vring.used = 396 | (void __force *)mvdev->mdev->aper.va + 397 | le64_to_cpu(vqconfig[i].used_address); 398 | } 399 | 400 | mvdev->dc->used_address_updated = 0; 401 | 402 | dev_dbg(mic_dev(mvdev), "%s: device type %d LINKUP\n", 403 | __func__, mvdev->virtio_id); 404 | } 405 | 406 | static inline void mic_virtio_device_reset(struct mic_vdev *mvdev) 407 | { 408 | int i; 409 | 410 | dev_dbg(mic_dev(mvdev), "%s: status %d device type %d RESET\n", 411 | __func__, mvdev->dd->status, mvdev->virtio_id); 412 | 413 | for (i = 0; i < mvdev->dd->num_vq; i++) 414 | /* 415 | * Avoid lockdep false positive. The + 1 is for the mic 416 | * mutex which is held in the reset devices code path. 417 | */ 418 | mutex_lock_nested(&mvdev->mvr[i].vr_mutex, i + 1); 419 | 420 | /* 0 status means "reset" */ 421 | mvdev->dd->status = 0; 422 | mvdev->dc->vdev_reset = 0; 423 | mvdev->dc->host_ack = 1; 424 | 425 | for (i = 0; i < mvdev->dd->num_vq; i++) { 426 | struct vringh *vrh = &mvdev->mvr[i].vrh; 427 | mvdev->mvr[i].vring.info->avail_idx = 0; 428 | vrh->completed = 0; 429 | vrh->last_avail_idx = 0; 430 | vrh->last_used_idx = 0; 431 | } 432 | 433 | for (i = 0; i < mvdev->dd->num_vq; i++) 434 | mutex_unlock(&mvdev->mvr[i].vr_mutex); 435 | } 436 | 437 | void mic_virtio_reset_devices(struct mic_device *mdev) 438 | { 439 | struct list_head *pos, *tmp; 440 | struct mic_vdev *mvdev; 441 | 442 | dev_dbg(&mdev->pdev->dev, "%s\n", __func__); 443 | 444 | list_for_each_safe(pos, tmp, &mdev->vdev_list) { 445 | mvdev = list_entry(pos, struct mic_vdev, list); 446 | mic_virtio_device_reset(mvdev); 447 | mvdev->poll_wake = 1; 448 | wake_up(&mvdev->waitq); 449 | } 450 | } 451 | 452 | void mic_bh_handler(struct work_struct *work) 453 | { 454 | struct mic_vdev *mvdev = container_of(work, struct mic_vdev, 455 | virtio_bh_work); 456 | 457 | if (mvdev->dc->used_address_updated) 458 | mic_virtio_init_post(mvdev); 459 | 460 | if (mvdev->dc->vdev_reset) 461 | mic_virtio_device_reset(mvdev); 462 | 463 | mvdev->poll_wake = 1; 464 | wake_up(&mvdev->waitq); 465 | } 466 | 467 | static irqreturn_t mic_virtio_intr_handler(int irq, void *data) 468 | { 469 | struct mic_vdev *mvdev = data; 470 | struct mic_device *mdev = mvdev->mdev; 471 | 472 | mdev->ops->intr_workarounds(mdev); 473 | schedule_work(&mvdev->virtio_bh_work); 474 | return IRQ_HANDLED; 475 | } 476 | 477 | int mic_virtio_config_change(struct mic_vdev *mvdev, 478 | void __user *argp) 479 | { 480 | DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wake); 481 | int ret = 0, retry, i; 482 | struct mic_bootparam *bootparam = mvdev->mdev->dp; 483 | s8 db = bootparam->h2c_config_db; 484 | 485 | mutex_lock(&mvdev->mdev->mic_mutex); 486 | for (i = 0; i < mvdev->dd->num_vq; i++) 487 | mutex_lock_nested(&mvdev->mvr[i].vr_mutex, i + 1); 488 | 489 | if (db == -1 || mvdev->dd->type == -1) { 490 | ret = -EIO; 491 | goto exit; 492 | } 493 | 494 | if (copy_from_user(mic_vq_configspace(mvdev->dd), 495 | argp, mvdev->dd->config_len)) { 496 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 497 | __func__, __LINE__, -EFAULT); 498 | ret = -EFAULT; 499 | goto exit; 500 | } 501 | mvdev->dc->config_change = MIC_VIRTIO_PARAM_CONFIG_CHANGED; 502 | mvdev->mdev->ops->send_intr(mvdev->mdev, db); 503 | 504 | for (retry = 100; retry--;) { 505 | ret = wait_event_timeout(wake, 506 | mvdev->dc->guest_ack, msecs_to_jiffies(100)); 507 | if (ret) 508 | break; 509 | } 510 | 511 | dev_dbg(mic_dev(mvdev), 512 | "%s %d retry: %d\n", __func__, __LINE__, retry); 513 | mvdev->dc->config_change = 0; 514 | mvdev->dc->guest_ack = 0; 515 | exit: 516 | for (i = 0; i < mvdev->dd->num_vq; i++) 517 | mutex_unlock(&mvdev->mvr[i].vr_mutex); 518 | mutex_unlock(&mvdev->mdev->mic_mutex); 519 | return ret; 520 | } 521 | 522 | static int mic_copy_dp_entry(struct mic_vdev *mvdev, 523 | void __user *argp, 524 | __u8 *type, 525 | struct mic_device_desc **devpage) 526 | { 527 | struct mic_device *mdev = mvdev->mdev; 528 | struct mic_device_desc dd, *dd_config, *devp; 529 | struct mic_vqconfig *vqconfig; 530 | int ret = 0, i; 531 | bool slot_found = false; 532 | 533 | if (copy_from_user(&dd, argp, sizeof(dd))) { 534 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 535 | __func__, __LINE__, -EFAULT); 536 | return -EFAULT; 537 | } 538 | 539 | if (mic_aligned_desc_size(&dd) > MIC_MAX_DESC_BLK_SIZE || 540 | dd.num_vq > MIC_MAX_VRINGS) { 541 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 542 | __func__, __LINE__, -EINVAL); 543 | return -EINVAL; 544 | } 545 | 546 | dd_config = kmalloc(mic_desc_size(&dd), GFP_KERNEL); 547 | if (dd_config == NULL) { 548 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 549 | __func__, __LINE__, -ENOMEM); 550 | return -ENOMEM; 551 | } 552 | if (copy_from_user(dd_config, argp, mic_desc_size(&dd))) { 553 | ret = -EFAULT; 554 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 555 | __func__, __LINE__, ret); 556 | goto exit; 557 | } 558 | 559 | vqconfig = mic_vq_config(dd_config); 560 | for (i = 0; i < dd.num_vq; i++) { 561 | if (le16_to_cpu(vqconfig[i].num) > MIC_MAX_VRING_ENTRIES) { 562 | ret = -EINVAL; 563 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 564 | __func__, __LINE__, ret); 565 | goto exit; 566 | } 567 | } 568 | 569 | /* Find the first free device page entry */ 570 | for (i = sizeof(struct mic_bootparam); 571 | i < MIC_DP_SIZE - mic_total_desc_size(dd_config); 572 | i += mic_total_desc_size(devp)) { 573 | devp = mdev->dp + i; 574 | if (devp->type == 0 || devp->type == -1) { 575 | slot_found = true; 576 | break; 577 | } 578 | } 579 | if (!slot_found) { 580 | ret = -EINVAL; 581 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 582 | __func__, __LINE__, ret); 583 | goto exit; 584 | } 585 | /* 586 | * Save off the type before doing the memcpy. Type will be set in the 587 | * end after completing all initialization for the new device. 588 | */ 589 | *type = dd_config->type; 590 | dd_config->type = 0; 591 | memcpy(devp, dd_config, mic_desc_size(dd_config)); 592 | 593 | *devpage = devp; 594 | exit: 595 | kfree(dd_config); 596 | return ret; 597 | } 598 | 599 | static void mic_init_device_ctrl(struct mic_vdev *mvdev, 600 | struct mic_device_desc *devpage) 601 | { 602 | struct mic_device_ctrl *dc; 603 | 604 | dc = (void *)devpage + mic_aligned_desc_size(devpage); 605 | 606 | dc->config_change = 0; 607 | dc->guest_ack = 0; 608 | dc->vdev_reset = 0; 609 | dc->host_ack = 0; 610 | dc->used_address_updated = 0; 611 | dc->c2h_vdev_db = -1; 612 | dc->h2c_vdev_db = -1; 613 | mvdev->dc = dc; 614 | } 615 | 616 | int mic_virtio_add_device(struct mic_vdev *mvdev, 617 | void __user *argp) 618 | { 619 | struct mic_device *mdev = mvdev->mdev; 620 | struct mic_device_desc *dd = NULL; 621 | struct mic_vqconfig *vqconfig; 622 | int vr_size, i, j, ret; 623 | u8 type = 0; 624 | s8 db; 625 | char irqname[10]; 626 | struct mic_bootparam *bootparam = mdev->dp; 627 | u16 num; 628 | dma_addr_t vr_addr; 629 | 630 | mutex_lock(&mdev->mic_mutex); 631 | 632 | ret = mic_copy_dp_entry(mvdev, argp, &type, &dd); 633 | if (ret) { 634 | mutex_unlock(&mdev->mic_mutex); 635 | return ret; 636 | } 637 | 638 | mic_init_device_ctrl(mvdev, dd); 639 | 640 | mvdev->dd = dd; 641 | mvdev->virtio_id = type; 642 | vqconfig = mic_vq_config(dd); 643 | INIT_WORK(&mvdev->virtio_bh_work, mic_bh_handler); 644 | 645 | for (i = 0; i < dd->num_vq; i++) { 646 | struct mic_vringh *mvr = &mvdev->mvr[i]; 647 | struct mic_vring *vr = &mvdev->mvr[i].vring; 648 | num = le16_to_cpu(vqconfig[i].num); 649 | mutex_init(&mvr->vr_mutex); 650 | vr_size = PAGE_ALIGN(vring_size(num, MIC_VIRTIO_RING_ALIGN) + 651 | sizeof(struct _mic_vring_info)); 652 | vr->va = (void *) 653 | __get_free_pages(GFP_KERNEL | __GFP_ZERO, 654 | get_order(vr_size)); 655 | if (!vr->va) { 656 | ret = -ENOMEM; 657 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 658 | __func__, __LINE__, ret); 659 | goto err; 660 | } 661 | vr->len = vr_size; 662 | vr->info = vr->va + vring_size(num, MIC_VIRTIO_RING_ALIGN); 663 | vr->info->magic = cpu_to_le32(MIC_MAGIC + mvdev->virtio_id + i); 664 | vr_addr = mic_map_single(mdev, vr->va, vr_size); 665 | if (mic_map_error(vr_addr)) { 666 | free_pages((unsigned long)vr->va, get_order(vr_size)); 667 | ret = -ENOMEM; 668 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 669 | __func__, __LINE__, ret); 670 | goto err; 671 | } 672 | vqconfig[i].address = cpu_to_le64(vr_addr); 673 | 674 | vring_init(&vr->vr, num, vr->va, MIC_VIRTIO_RING_ALIGN); 675 | ret = vringh_init_kern(&mvr->vrh, 676 | *(u32 *)mic_vq_features(mvdev->dd), num, false, 677 | vr->vr.desc, vr->vr.avail, vr->vr.used); 678 | if (ret) { 679 | dev_err(mic_dev(mvdev), "%s %d err %d\n", 680 | __func__, __LINE__, ret); 681 | goto err; 682 | } 683 | vringh_kiov_init(&mvr->riov, NULL, 0); 684 | vringh_kiov_init(&mvr->wiov, NULL, 0); 685 | mvr->head = USHRT_MAX; 686 | mvr->mvdev = mvdev; 687 | mvr->vrh.notify = mic_notify; 688 | dev_dbg(&mdev->pdev->dev, 689 | "%s %d index %d va %p info %p vr_size 0x%x\n", 690 | __func__, __LINE__, i, vr->va, vr->info, vr_size); 691 | mvr->buf = (void *)__get_free_pages(GFP_KERNEL, 692 | get_order(MIC_INT_DMA_BUF_SIZE)); 693 | mvr->buf_da = mic_map_single(mvdev->mdev, mvr->buf, 694 | MIC_INT_DMA_BUF_SIZE); 695 | } 696 | 697 | snprintf(irqname, sizeof(irqname), "mic%dvirtio%d", mdev->id, 698 | mvdev->virtio_id); 699 | mvdev->virtio_db = mic_next_db(mdev); 700 | mvdev->virtio_cookie = mic_request_threaded_irq(mdev, 701 | mic_virtio_intr_handler, 702 | NULL, irqname, mvdev, 703 | mvdev->virtio_db, MIC_INTR_DB); 704 | if (IS_ERR(mvdev->virtio_cookie)) { 705 | ret = PTR_ERR(mvdev->virtio_cookie); 706 | dev_dbg(&mdev->pdev->dev, "request irq failed\n"); 707 | goto err; 708 | } 709 | 710 | mvdev->dc->c2h_vdev_db = mvdev->virtio_db; 711 | 712 | list_add_tail(&mvdev->list, &mdev->vdev_list); 713 | /* 714 | * Order the type update with previous stores. This write barrier 715 | * is paired with the corresponding read barrier before the uncached 716 | * system memory read of the type, on the card while scanning the 717 | * device page. 718 | */ 719 | smp_wmb(); 720 | dd->type = type; 721 | 722 | dev_dbg(&mdev->pdev->dev, "Added virtio device id %d\n", dd->type); 723 | 724 | db = bootparam->h2c_config_db; 725 | if (db != -1) 726 | mdev->ops->send_intr(mdev, db); 727 | mutex_unlock(&mdev->mic_mutex); 728 | return 0; 729 | err: 730 | vqconfig = mic_vq_config(dd); 731 | for (j = 0; j < i; j++) { 732 | struct mic_vringh *mvr = &mvdev->mvr[j]; 733 | mic_unmap_single(mdev, le64_to_cpu(vqconfig[j].address), 734 | mvr->vring.len); 735 | free_pages((unsigned long)mvr->vring.va, 736 | get_order(mvr->vring.len)); 737 | } 738 | mutex_unlock(&mdev->mic_mutex); 739 | return ret; 740 | } 741 | 742 | void mic_virtio_del_device(struct mic_vdev *mvdev) 743 | { 744 | struct list_head *pos, *tmp; 745 | struct mic_vdev *tmp_mvdev; 746 | struct mic_device *mdev = mvdev->mdev; 747 | DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wake); 748 | int i, ret, retry; 749 | struct mic_vqconfig *vqconfig; 750 | struct mic_bootparam *bootparam = mdev->dp; 751 | s8 db; 752 | 753 | mutex_lock(&mdev->mic_mutex); 754 | db = bootparam->h2c_config_db; 755 | if (db == -1) 756 | goto skip_hot_remove; 757 | dev_dbg(&mdev->pdev->dev, 758 | "Requesting hot remove id %d\n", mvdev->virtio_id); 759 | mvdev->dc->config_change = MIC_VIRTIO_PARAM_DEV_REMOVE; 760 | mdev->ops->send_intr(mdev, db); 761 | for (retry = 100; retry--;) { 762 | ret = wait_event_timeout(wake, 763 | mvdev->dc->guest_ack, msecs_to_jiffies(100)); 764 | if (ret) 765 | break; 766 | } 767 | dev_dbg(&mdev->pdev->dev, 768 | "Device id %d config_change %d guest_ack %d retry %d\n", 769 | mvdev->virtio_id, mvdev->dc->config_change, 770 | mvdev->dc->guest_ack, retry); 771 | mvdev->dc->config_change = 0; 772 | mvdev->dc->guest_ack = 0; 773 | skip_hot_remove: 774 | mic_free_irq(mdev, mvdev->virtio_cookie, mvdev); 775 | flush_work(&mvdev->virtio_bh_work); 776 | vqconfig = mic_vq_config(mvdev->dd); 777 | for (i = 0; i < mvdev->dd->num_vq; i++) { 778 | struct mic_vringh *mvr = &mvdev->mvr[i]; 779 | 780 | mic_unmap_single(mvdev->mdev, mvr->buf_da, 781 | MIC_INT_DMA_BUF_SIZE); 782 | free_pages((unsigned long)mvr->buf, 783 | get_order(MIC_INT_DMA_BUF_SIZE)); 784 | vringh_kiov_cleanup(&mvr->riov); 785 | vringh_kiov_cleanup(&mvr->wiov); 786 | mic_unmap_single(mdev, le64_to_cpu(vqconfig[i].address), 787 | mvr->vring.len); 788 | free_pages((unsigned long)mvr->vring.va, 789 | get_order(mvr->vring.len)); 790 | } 791 | 792 | list_for_each_safe(pos, tmp, &mdev->vdev_list) { 793 | tmp_mvdev = list_entry(pos, struct mic_vdev, list); 794 | if (tmp_mvdev == mvdev) { 795 | list_del(pos); 796 | dev_dbg(&mdev->pdev->dev, 797 | "Removing virtio device id %d\n", 798 | mvdev->virtio_id); 799 | break; 800 | } 801 | } 802 | /* 803 | * Order the type update with previous stores. This write barrier 804 | * is paired with the corresponding read barrier before the uncached 805 | * system memory read of the type, on the card while scanning the 806 | * device page. 807 | */ 808 | smp_wmb(); 809 | mvdev->dd->type = -1; 810 | mutex_unlock(&mdev->mic_mutex); 811 | } 812 | -------------------------------------------------------------------------------- /testdir/truecases/commctrl.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Adaptec AAC series RAID controller driver 3 | * (c) Copyright 2001 Red Hat Inc. 4 | * 5 | * based on the old aacraid driver that is.. 6 | * Adaptec aacraid device driver for Linux. 7 | * 8 | * Copyright (c) 2000-2010 Adaptec, Inc. 9 | * 2010 PMC-Sierra, Inc. (aacraid@pmc-sierra.com) 10 | * 11 | * This program is free software; you can redistribute it and/or modify 12 | * it under the terms of the GNU General Public License as published by 13 | * the Free Software Foundation; either version 2, or (at your option) 14 | * any later version. 15 | * 16 | * This program is distributed in the hope that it will be useful, 17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | * GNU General Public License for more details. 20 | * 21 | * You should have received a copy of the GNU General Public License 22 | * along with this program; see the file COPYING. If not, write to 23 | * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 24 | * 25 | * Module Name: 26 | * commctrl.c 27 | * 28 | * Abstract: Contains all routines for control of the AFA comm layer 29 | * 30 | */ 31 | 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include /* ssleep prototype */ 42 | #include 43 | #include 44 | #include 45 | #include 46 | 47 | #include "aacraid.h" 48 | 49 | /** 50 | * ioctl_send_fib - send a FIB from userspace 51 | * @dev: adapter is being processed 52 | * @arg: arguments to the ioctl call 53 | * 54 | * This routine sends a fib to the adapter on behalf of a user level 55 | * program. 56 | */ 57 | # define AAC_DEBUG_PREAMBLE KERN_INFO 58 | # define AAC_DEBUG_POSTAMBLE 59 | 60 | static int ioctl_send_fib(struct aac_dev * dev, void __user *arg) 61 | { 62 | struct hw_fib * kfib; 63 | struct fib *fibptr; 64 | struct hw_fib * hw_fib = (struct hw_fib *)0; 65 | dma_addr_t hw_fib_pa = (dma_addr_t)0LL; 66 | unsigned size; 67 | int retval; 68 | 69 | if (dev->in_reset) { 70 | return -EBUSY; 71 | } 72 | fibptr = aac_fib_alloc(dev); 73 | if(fibptr == NULL) { 74 | return -ENOMEM; 75 | } 76 | 77 | kfib = fibptr->hw_fib_va; 78 | /* 79 | * First copy in the header so that we can check the size field. 80 | */ 81 | if (copy_from_user((void *)kfib, arg, sizeof(struct aac_fibhdr))) { 82 | aac_fib_free(fibptr); 83 | return -EFAULT; 84 | } 85 | /* 86 | * Since we copy based on the fib header size, make sure that we 87 | * will not overrun the buffer when we copy the memory. Return 88 | * an error if we would. 89 | */ 90 | size = le16_to_cpu(kfib->header.Size) + sizeof(struct aac_fibhdr); 91 | if (size < le16_to_cpu(kfib->header.SenderSize)) 92 | size = le16_to_cpu(kfib->header.SenderSize); 93 | if (size > dev->max_fib_size) { 94 | dma_addr_t daddr; 95 | 96 | if (size > 2048) { 97 | retval = -EINVAL; 98 | goto cleanup; 99 | } 100 | 101 | kfib = pci_alloc_consistent(dev->pdev, size, &daddr); 102 | if (!kfib) { 103 | retval = -ENOMEM; 104 | goto cleanup; 105 | } 106 | 107 | /* Highjack the hw_fib */ 108 | hw_fib = fibptr->hw_fib_va; 109 | hw_fib_pa = fibptr->hw_fib_pa; 110 | fibptr->hw_fib_va = kfib; 111 | fibptr->hw_fib_pa = daddr; 112 | memset(((char *)kfib) + dev->max_fib_size, 0, size - dev->max_fib_size); 113 | memcpy(kfib, hw_fib, dev->max_fib_size); 114 | } 115 | 116 | if (copy_from_user(kfib, arg, size)) { 117 | retval = -EFAULT; 118 | goto cleanup; 119 | } 120 | 121 | if (kfib->header.Command == cpu_to_le16(TakeABreakPt)) { 122 | aac_adapter_interrupt(dev); 123 | /* 124 | * Since we didn't really send a fib, zero out the state to allow 125 | * cleanup code not to assert. 126 | */ 127 | kfib->header.XferState = 0; 128 | } else { 129 | retval = aac_fib_send(le16_to_cpu(kfib->header.Command), fibptr, 130 | le16_to_cpu(kfib->header.Ssize) , FsaNormal, 131 | 1, 1, NULL, NULL); 132 | if (retval) { 133 | goto cleanup; 134 | } 135 | if (aac_fib_complete(fibptr) != 0) { 136 | retval = -EINVAL; 137 | goto cleanup; 138 | } 139 | } 140 | /* 141 | * Make sure that the size returned by the adapter (which includes 142 | * the header) is less than or equal to the size of a fib, so we 143 | * don't corrupt application data. Then copy that size to the user 144 | * buffer. (Don't try to add the header information again, since it 145 | * was already included by the adapter.) 146 | */ 147 | 148 | retval = 0; 149 | if (copy_to_user(arg, (void *)kfib, size)) 150 | retval = -EFAULT; 151 | cleanup: 152 | if (hw_fib) { 153 | pci_free_consistent(dev->pdev, size, kfib, fibptr->hw_fib_pa); 154 | fibptr->hw_fib_pa = hw_fib_pa; 155 | fibptr->hw_fib_va = hw_fib; 156 | } 157 | if (retval != -ERESTARTSYS) 158 | aac_fib_free(fibptr); 159 | return retval; 160 | } 161 | 162 | /** 163 | * open_getadapter_fib - Get the next fib 164 | * 165 | * This routine will get the next Fib, if available, from the AdapterFibContext 166 | * passed in from the user. 167 | */ 168 | 169 | static int open_getadapter_fib(struct aac_dev * dev, void __user *arg) 170 | { 171 | struct aac_fib_context * fibctx; 172 | int status; 173 | 174 | fibctx = kmalloc(sizeof(struct aac_fib_context), GFP_KERNEL); 175 | if (fibctx == NULL) { 176 | status = -ENOMEM; 177 | } else { 178 | unsigned long flags; 179 | struct list_head * entry; 180 | struct aac_fib_context * context; 181 | 182 | fibctx->type = FSAFS_NTC_GET_ADAPTER_FIB_CONTEXT; 183 | fibctx->size = sizeof(struct aac_fib_context); 184 | /* 185 | * Yes yes, I know this could be an index, but we have a 186 | * better guarantee of uniqueness for the locked loop below. 187 | * Without the aid of a persistent history, this also helps 188 | * reduce the chance that the opaque context would be reused. 189 | */ 190 | fibctx->unique = (u32)((ulong)fibctx & 0xFFFFFFFF); 191 | /* 192 | * Initialize the mutex used to wait for the next AIF. 193 | */ 194 | sema_init(&fibctx->wait_sem, 0); 195 | fibctx->wait = 0; 196 | /* 197 | * Initialize the fibs and set the count of fibs on 198 | * the list to 0. 199 | */ 200 | fibctx->count = 0; 201 | INIT_LIST_HEAD(&fibctx->fib_list); 202 | fibctx->jiffies = jiffies/HZ; 203 | /* 204 | * Now add this context onto the adapter's 205 | * AdapterFibContext list. 206 | */ 207 | spin_lock_irqsave(&dev->fib_lock, flags); 208 | /* Ensure that we have a unique identifier */ 209 | entry = dev->fib_list.next; 210 | while (entry != &dev->fib_list) { 211 | context = list_entry(entry, struct aac_fib_context, next); 212 | if (context->unique == fibctx->unique) { 213 | /* Not unique (32 bits) */ 214 | fibctx->unique++; 215 | entry = dev->fib_list.next; 216 | } else { 217 | entry = entry->next; 218 | } 219 | } 220 | list_add_tail(&fibctx->next, &dev->fib_list); 221 | spin_unlock_irqrestore(&dev->fib_lock, flags); 222 | if (copy_to_user(arg, &fibctx->unique, 223 | sizeof(fibctx->unique))) { 224 | status = -EFAULT; 225 | } else { 226 | status = 0; 227 | } 228 | } 229 | return status; 230 | } 231 | 232 | /** 233 | * next_getadapter_fib - get the next fib 234 | * @dev: adapter to use 235 | * @arg: ioctl argument 236 | * 237 | * This routine will get the next Fib, if available, from the AdapterFibContext 238 | * passed in from the user. 239 | */ 240 | 241 | static int next_getadapter_fib(struct aac_dev * dev, void __user *arg) 242 | { 243 | struct fib_ioctl f; 244 | struct fib *fib; 245 | struct aac_fib_context *fibctx; 246 | int status; 247 | struct list_head * entry; 248 | unsigned long flags; 249 | 250 | if(copy_from_user((void *)&f, arg, sizeof(struct fib_ioctl))) 251 | return -EFAULT; 252 | /* 253 | * Verify that the HANDLE passed in was a valid AdapterFibContext 254 | * 255 | * Search the list of AdapterFibContext addresses on the adapter 256 | * to be sure this is a valid address 257 | */ 258 | spin_lock_irqsave(&dev->fib_lock, flags); 259 | entry = dev->fib_list.next; 260 | fibctx = NULL; 261 | 262 | while (entry != &dev->fib_list) { 263 | fibctx = list_entry(entry, struct aac_fib_context, next); 264 | /* 265 | * Extract the AdapterFibContext from the Input parameters. 266 | */ 267 | if (fibctx->unique == f.fibctx) { /* We found a winner */ 268 | break; 269 | } 270 | entry = entry->next; 271 | fibctx = NULL; 272 | } 273 | if (!fibctx) { 274 | spin_unlock_irqrestore(&dev->fib_lock, flags); 275 | dprintk ((KERN_INFO "Fib Context not found\n")); 276 | return -EINVAL; 277 | } 278 | 279 | if((fibctx->type != FSAFS_NTC_GET_ADAPTER_FIB_CONTEXT) || 280 | (fibctx->size != sizeof(struct aac_fib_context))) { 281 | spin_unlock_irqrestore(&dev->fib_lock, flags); 282 | dprintk ((KERN_INFO "Fib Context corrupt?\n")); 283 | return -EINVAL; 284 | } 285 | status = 0; 286 | /* 287 | * If there are no fibs to send back, then either wait or return 288 | * -EAGAIN 289 | */ 290 | return_fib: 291 | if (!list_empty(&fibctx->fib_list)) { 292 | /* 293 | * Pull the next fib from the fibs 294 | */ 295 | entry = fibctx->fib_list.next; 296 | list_del(entry); 297 | 298 | fib = list_entry(entry, struct fib, fiblink); 299 | fibctx->count--; 300 | spin_unlock_irqrestore(&dev->fib_lock, flags); 301 | if (copy_to_user(f.fib, fib->hw_fib_va, sizeof(struct hw_fib))) { 302 | kfree(fib->hw_fib_va); 303 | kfree(fib); 304 | return -EFAULT; 305 | } 306 | /* 307 | * Free the space occupied by this copy of the fib. 308 | */ 309 | kfree(fib->hw_fib_va); 310 | kfree(fib); 311 | status = 0; 312 | } else { 313 | spin_unlock_irqrestore(&dev->fib_lock, flags); 314 | /* If someone killed the AIF aacraid thread, restart it */ 315 | status = !dev->aif_thread; 316 | if (status && !dev->in_reset && dev->queues && dev->fsa_dev) { 317 | /* Be paranoid, be very paranoid! */ 318 | kthread_stop(dev->thread); 319 | ssleep(1); 320 | dev->aif_thread = 0; 321 | dev->thread = kthread_run(aac_command_thread, dev, 322 | "%s", dev->name); 323 | ssleep(1); 324 | } 325 | if (f.wait) { 326 | if(down_interruptible(&fibctx->wait_sem) < 0) { 327 | status = -ERESTARTSYS; 328 | } else { 329 | /* Lock again and retry */ 330 | spin_lock_irqsave(&dev->fib_lock, flags); 331 | goto return_fib; 332 | } 333 | } else { 334 | status = -EAGAIN; 335 | } 336 | } 337 | fibctx->jiffies = jiffies/HZ; 338 | return status; 339 | } 340 | 341 | int aac_close_fib_context(struct aac_dev * dev, struct aac_fib_context * fibctx) 342 | { 343 | struct fib *fib; 344 | 345 | /* 346 | * First free any FIBs that have not been consumed. 347 | */ 348 | while (!list_empty(&fibctx->fib_list)) { 349 | struct list_head * entry; 350 | /* 351 | * Pull the next fib from the fibs 352 | */ 353 | entry = fibctx->fib_list.next; 354 | list_del(entry); 355 | fib = list_entry(entry, struct fib, fiblink); 356 | fibctx->count--; 357 | /* 358 | * Free the space occupied by this copy of the fib. 359 | */ 360 | kfree(fib->hw_fib_va); 361 | kfree(fib); 362 | } 363 | /* 364 | * Remove the Context from the AdapterFibContext List 365 | */ 366 | list_del(&fibctx->next); 367 | /* 368 | * Invalidate context 369 | */ 370 | fibctx->type = 0; 371 | /* 372 | * Free the space occupied by the Context 373 | */ 374 | kfree(fibctx); 375 | return 0; 376 | } 377 | 378 | /** 379 | * close_getadapter_fib - close down user fib context 380 | * @dev: adapter 381 | * @arg: ioctl arguments 382 | * 383 | * This routine will close down the fibctx passed in from the user. 384 | */ 385 | 386 | static int close_getadapter_fib(struct aac_dev * dev, void __user *arg) 387 | { 388 | struct aac_fib_context *fibctx; 389 | int status; 390 | unsigned long flags; 391 | struct list_head * entry; 392 | 393 | /* 394 | * Verify that the HANDLE passed in was a valid AdapterFibContext 395 | * 396 | * Search the list of AdapterFibContext addresses on the adapter 397 | * to be sure this is a valid address 398 | */ 399 | 400 | entry = dev->fib_list.next; 401 | fibctx = NULL; 402 | 403 | while(entry != &dev->fib_list) { 404 | fibctx = list_entry(entry, struct aac_fib_context, next); 405 | /* 406 | * Extract the fibctx from the input parameters 407 | */ 408 | if (fibctx->unique == (u32)(uintptr_t)arg) /* We found a winner */ 409 | break; 410 | entry = entry->next; 411 | fibctx = NULL; 412 | } 413 | 414 | if (!fibctx) 415 | return 0; /* Already gone */ 416 | 417 | if((fibctx->type != FSAFS_NTC_GET_ADAPTER_FIB_CONTEXT) || 418 | (fibctx->size != sizeof(struct aac_fib_context))) 419 | return -EINVAL; 420 | spin_lock_irqsave(&dev->fib_lock, flags); 421 | status = aac_close_fib_context(dev, fibctx); 422 | spin_unlock_irqrestore(&dev->fib_lock, flags); 423 | return status; 424 | } 425 | 426 | /** 427 | * check_revision - close down user fib context 428 | * @dev: adapter 429 | * @arg: ioctl arguments 430 | * 431 | * This routine returns the driver version. 432 | * Under Linux, there have been no version incompatibilities, so this is 433 | * simple! 434 | */ 435 | 436 | static int check_revision(struct aac_dev *dev, void __user *arg) 437 | { 438 | struct revision response; 439 | char *driver_version = aac_driver_version; 440 | u32 version; 441 | 442 | response.compat = 1; 443 | version = (simple_strtol(driver_version, 444 | &driver_version, 10) << 24) | 0x00000400; 445 | version += simple_strtol(driver_version + 1, &driver_version, 10) << 16; 446 | version += simple_strtol(driver_version + 1, NULL, 10); 447 | response.version = cpu_to_le32(version); 448 | # ifdef AAC_DRIVER_BUILD 449 | response.build = cpu_to_le32(AAC_DRIVER_BUILD); 450 | # else 451 | response.build = cpu_to_le32(9999); 452 | # endif 453 | 454 | if (copy_to_user(arg, &response, sizeof(response))) 455 | return -EFAULT; 456 | return 0; 457 | } 458 | 459 | 460 | /** 461 | * 462 | * aac_send_raw_scb 463 | * 464 | */ 465 | 466 | static int aac_send_raw_srb(struct aac_dev* dev, void __user * arg) 467 | { 468 | struct fib* srbfib; 469 | int status; 470 | struct aac_srb *srbcmd = NULL; 471 | struct user_aac_srb *user_srbcmd = NULL; 472 | struct user_aac_srb __user *user_srb = arg; 473 | struct aac_srb_reply __user *user_reply; 474 | struct aac_srb_reply* reply; 475 | u32 fibsize = 0; 476 | u32 flags = 0; 477 | s32 rcode = 0; 478 | u32 data_dir; 479 | void __user *sg_user[32]; 480 | void *sg_list[32]; 481 | u32 sg_indx = 0; 482 | u32 byte_count = 0; 483 | u32 actual_fibsize64, actual_fibsize = 0; 484 | int i; 485 | 486 | 487 | if (dev->in_reset) { 488 | dprintk((KERN_DEBUG"aacraid: send raw srb -EBUSY\n")); 489 | return -EBUSY; 490 | } 491 | if (!capable(CAP_SYS_ADMIN)){ 492 | dprintk((KERN_DEBUG"aacraid: No permission to send raw srb\n")); 493 | return -EPERM; 494 | } 495 | /* 496 | * Allocate and initialize a Fib then setup a SRB command 497 | */ 498 | if (!(srbfib = aac_fib_alloc(dev))) { 499 | return -ENOMEM; 500 | } 501 | aac_fib_init(srbfib); 502 | /* raw_srb FIB is not FastResponseCapable */ 503 | srbfib->hw_fib_va->header.XferState &= ~cpu_to_le32(FastResponseCapable); 504 | 505 | srbcmd = (struct aac_srb*) fib_data(srbfib); 506 | 507 | memset(sg_list, 0, sizeof(sg_list)); /* cleanup may take issue */ 508 | if(copy_from_user(&fibsize, &user_srb->count,sizeof(u32))){ 509 | dprintk((KERN_DEBUG"aacraid: Could not copy data size from user\n")); 510 | rcode = -EFAULT; 511 | goto cleanup; 512 | } 513 | 514 | if ((fibsize < (sizeof(struct user_aac_srb) - sizeof(struct user_sgentry))) || 515 | (fibsize > (dev->max_fib_size - sizeof(struct aac_fibhdr)))) { 516 | rcode = -EINVAL; 517 | goto cleanup; 518 | } 519 | 520 | user_srbcmd = kmalloc(fibsize, GFP_KERNEL); 521 | if (!user_srbcmd) { 522 | dprintk((KERN_DEBUG"aacraid: Could not make a copy of the srb\n")); 523 | rcode = -ENOMEM; 524 | goto cleanup; 525 | } 526 | if(copy_from_user(user_srbcmd, user_srb,fibsize)){ 527 | dprintk((KERN_DEBUG"aacraid: Could not copy srb from user\n")); 528 | rcode = -EFAULT; 529 | goto cleanup; 530 | } 531 | 532 | user_reply = arg+fibsize; 533 | 534 | flags = user_srbcmd->flags; /* from user in cpu order */ 535 | // Fix up srb for endian and force some values 536 | 537 | srbcmd->function = cpu_to_le32(SRBF_ExecuteScsi); // Force this 538 | srbcmd->channel = cpu_to_le32(user_srbcmd->channel); 539 | srbcmd->id = cpu_to_le32(user_srbcmd->id); 540 | srbcmd->lun = cpu_to_le32(user_srbcmd->lun); 541 | srbcmd->timeout = cpu_to_le32(user_srbcmd->timeout); 542 | srbcmd->flags = cpu_to_le32(flags); 543 | srbcmd->retry_limit = 0; // Obsolete parameter 544 | srbcmd->cdb_size = cpu_to_le32(user_srbcmd->cdb_size); 545 | memcpy(srbcmd->cdb, user_srbcmd->cdb, sizeof(srbcmd->cdb)); 546 | 547 | switch (flags & (SRB_DataIn | SRB_DataOut)) { 548 | case SRB_DataOut: 549 | data_dir = DMA_TO_DEVICE; 550 | break; 551 | case (SRB_DataIn | SRB_DataOut): 552 | data_dir = DMA_BIDIRECTIONAL; 553 | break; 554 | case SRB_DataIn: 555 | data_dir = DMA_FROM_DEVICE; 556 | break; 557 | default: 558 | data_dir = DMA_NONE; 559 | } 560 | if (user_srbcmd->sg.count > ARRAY_SIZE(sg_list)) { 561 | dprintk((KERN_DEBUG"aacraid: too many sg entries %d\n", 562 | le32_to_cpu(srbcmd->sg.count))); 563 | rcode = -EINVAL; 564 | goto cleanup; 565 | } 566 | actual_fibsize = sizeof(struct aac_srb) - sizeof(struct sgentry) + 567 | ((user_srbcmd->sg.count & 0xff) * sizeof(struct sgentry)); 568 | actual_fibsize64 = actual_fibsize + (user_srbcmd->sg.count & 0xff) * 569 | (sizeof(struct sgentry64) - sizeof(struct sgentry)); 570 | /* User made a mistake - should not continue */ 571 | if ((actual_fibsize != fibsize) && (actual_fibsize64 != fibsize)) { 572 | dprintk((KERN_DEBUG"aacraid: Bad Size specified in " 573 | "Raw SRB command calculated fibsize=%lu;%lu " 574 | "user_srbcmd->sg.count=%d aac_srb=%lu sgentry=%lu;%lu " 575 | "issued fibsize=%d\n", 576 | actual_fibsize, actual_fibsize64, user_srbcmd->sg.count, 577 | sizeof(struct aac_srb), sizeof(struct sgentry), 578 | sizeof(struct sgentry64), fibsize)); 579 | rcode = -EINVAL; 580 | goto cleanup; 581 | } 582 | if ((data_dir == DMA_NONE) && user_srbcmd->sg.count) { 583 | dprintk((KERN_DEBUG"aacraid: SG with no direction specified in Raw SRB command\n")); 584 | rcode = -EINVAL; 585 | goto cleanup; 586 | } 587 | byte_count = 0; 588 | if (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) { 589 | struct user_sgmap64* upsg = (struct user_sgmap64*)&user_srbcmd->sg; 590 | struct sgmap64* psg = (struct sgmap64*)&srbcmd->sg; 591 | 592 | /* 593 | * This should also catch if user used the 32 bit sgmap 594 | */ 595 | if (actual_fibsize64 == fibsize) { 596 | actual_fibsize = actual_fibsize64; 597 | for (i = 0; i < upsg->count; i++) { 598 | u64 addr; 599 | void* p; 600 | if (upsg->sg[i].count > 601 | ((dev->adapter_info.options & 602 | AAC_OPT_NEW_COMM) ? 603 | (dev->scsi_host_ptr->max_sectors << 9) : 604 | 65536)) { 605 | rcode = -EINVAL; 606 | goto cleanup; 607 | } 608 | /* Does this really need to be GFP_DMA? */ 609 | p = kmalloc(upsg->sg[i].count,GFP_KERNEL|__GFP_DMA); 610 | if(!p) { 611 | dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", 612 | upsg->sg[i].count,i,upsg->count)); 613 | rcode = -ENOMEM; 614 | goto cleanup; 615 | } 616 | addr = (u64)upsg->sg[i].addr[0]; 617 | addr += ((u64)upsg->sg[i].addr[1]) << 32; 618 | sg_user[i] = (void __user *)(uintptr_t)addr; 619 | sg_list[i] = p; // save so we can clean up later 620 | sg_indx = i; 621 | 622 | if (flags & SRB_DataOut) { 623 | if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){ 624 | dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); 625 | rcode = -EFAULT; 626 | goto cleanup; 627 | } 628 | } 629 | addr = pci_map_single(dev->pdev, p, upsg->sg[i].count, data_dir); 630 | 631 | psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff); 632 | psg->sg[i].addr[1] = cpu_to_le32(addr>>32); 633 | byte_count += upsg->sg[i].count; 634 | psg->sg[i].count = cpu_to_le32(upsg->sg[i].count); 635 | } 636 | } else { 637 | struct user_sgmap* usg; 638 | usg = kmalloc(actual_fibsize - sizeof(struct aac_srb) 639 | + sizeof(struct sgmap), GFP_KERNEL); 640 | if (!usg) { 641 | dprintk((KERN_DEBUG"aacraid: Allocation error in Raw SRB command\n")); 642 | rcode = -ENOMEM; 643 | goto cleanup; 644 | } 645 | memcpy (usg, upsg, actual_fibsize - sizeof(struct aac_srb) 646 | + sizeof(struct sgmap)); 647 | actual_fibsize = actual_fibsize64; 648 | 649 | for (i = 0; i < usg->count; i++) { 650 | u64 addr; 651 | void* p; 652 | if (usg->sg[i].count > 653 | ((dev->adapter_info.options & 654 | AAC_OPT_NEW_COMM) ? 655 | (dev->scsi_host_ptr->max_sectors << 9) : 656 | 65536)) { 657 | kfree(usg); 658 | rcode = -EINVAL; 659 | goto cleanup; 660 | } 661 | /* Does this really need to be GFP_DMA? */ 662 | p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA); 663 | if(!p) { 664 | dprintk((KERN_DEBUG "aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", 665 | usg->sg[i].count,i,usg->count)); 666 | kfree(usg); 667 | rcode = -ENOMEM; 668 | goto cleanup; 669 | } 670 | sg_user[i] = (void __user *)(uintptr_t)usg->sg[i].addr; 671 | sg_list[i] = p; // save so we can clean up later 672 | sg_indx = i; 673 | 674 | if (flags & SRB_DataOut) { 675 | if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){ 676 | kfree (usg); 677 | dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); 678 | rcode = -EFAULT; 679 | goto cleanup; 680 | } 681 | } 682 | addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir); 683 | 684 | psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff); 685 | psg->sg[i].addr[1] = cpu_to_le32(addr>>32); 686 | byte_count += usg->sg[i].count; 687 | psg->sg[i].count = cpu_to_le32(usg->sg[i].count); 688 | } 689 | kfree (usg); 690 | } 691 | srbcmd->count = cpu_to_le32(byte_count); 692 | if (user_srbcmd->sg.count) 693 | psg->count = cpu_to_le32(sg_indx+1); 694 | else 695 | psg->count = 0; 696 | status = aac_fib_send(ScsiPortCommand64, srbfib, actual_fibsize, FsaNormal, 1, 1,NULL,NULL); 697 | } else { 698 | struct user_sgmap* upsg = &user_srbcmd->sg; 699 | struct sgmap* psg = &srbcmd->sg; 700 | 701 | if (actual_fibsize64 == fibsize) { 702 | struct user_sgmap64* usg = (struct user_sgmap64 *)upsg; 703 | for (i = 0; i < upsg->count; i++) { 704 | uintptr_t addr; 705 | void* p; 706 | if (usg->sg[i].count > 707 | ((dev->adapter_info.options & 708 | AAC_OPT_NEW_COMM) ? 709 | (dev->scsi_host_ptr->max_sectors << 9) : 710 | 65536)) { 711 | rcode = -EINVAL; 712 | goto cleanup; 713 | } 714 | /* Does this really need to be GFP_DMA? */ 715 | p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA); 716 | if(!p) { 717 | dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", 718 | usg->sg[i].count,i,usg->count)); 719 | rcode = -ENOMEM; 720 | goto cleanup; 721 | } 722 | addr = (u64)usg->sg[i].addr[0]; 723 | addr += ((u64)usg->sg[i].addr[1]) << 32; 724 | sg_user[i] = (void __user *)addr; 725 | sg_list[i] = p; // save so we can clean up later 726 | sg_indx = i; 727 | 728 | if (flags & SRB_DataOut) { 729 | if(copy_from_user(p,sg_user[i],usg->sg[i].count)){ 730 | dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); 731 | rcode = -EFAULT; 732 | goto cleanup; 733 | } 734 | } 735 | addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir); 736 | 737 | psg->sg[i].addr = cpu_to_le32(addr & 0xffffffff); 738 | byte_count += usg->sg[i].count; 739 | psg->sg[i].count = cpu_to_le32(usg->sg[i].count); 740 | } 741 | } else { 742 | for (i = 0; i < upsg->count; i++) { 743 | dma_addr_t addr; 744 | void* p; 745 | if (upsg->sg[i].count > 746 | ((dev->adapter_info.options & 747 | AAC_OPT_NEW_COMM) ? 748 | (dev->scsi_host_ptr->max_sectors << 9) : 749 | 65536)) { 750 | rcode = -EINVAL; 751 | goto cleanup; 752 | } 753 | p = kmalloc(upsg->sg[i].count, GFP_KERNEL); 754 | if (!p) { 755 | dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n", 756 | upsg->sg[i].count, i, upsg->count)); 757 | rcode = -ENOMEM; 758 | goto cleanup; 759 | } 760 | sg_user[i] = (void __user *)(uintptr_t)upsg->sg[i].addr; 761 | sg_list[i] = p; // save so we can clean up later 762 | sg_indx = i; 763 | 764 | if (flags & SRB_DataOut) { 765 | if(copy_from_user(p, sg_user[i], 766 | upsg->sg[i].count)) { 767 | dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n")); 768 | rcode = -EFAULT; 769 | goto cleanup; 770 | } 771 | } 772 | addr = pci_map_single(dev->pdev, p, 773 | upsg->sg[i].count, data_dir); 774 | 775 | psg->sg[i].addr = cpu_to_le32(addr); 776 | byte_count += upsg->sg[i].count; 777 | psg->sg[i].count = cpu_to_le32(upsg->sg[i].count); 778 | } 779 | } 780 | srbcmd->count = cpu_to_le32(byte_count); 781 | if (user_srbcmd->sg.count) 782 | psg->count = cpu_to_le32(sg_indx+1); 783 | else 784 | psg->count = 0; 785 | status = aac_fib_send(ScsiPortCommand, srbfib, actual_fibsize, FsaNormal, 1, 1, NULL, NULL); 786 | } 787 | if (status == -ERESTARTSYS) { 788 | rcode = -ERESTARTSYS; 789 | goto cleanup; 790 | } 791 | 792 | if (status != 0){ 793 | dprintk((KERN_DEBUG"aacraid: Could not send raw srb fib to hba\n")); 794 | rcode = -ENXIO; 795 | goto cleanup; 796 | } 797 | 798 | if (flags & SRB_DataIn) { 799 | for(i = 0 ; i <= sg_indx; i++){ 800 | byte_count = le32_to_cpu( 801 | (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) 802 | ? ((struct sgmap64*)&srbcmd->sg)->sg[i].count 803 | : srbcmd->sg.sg[i].count); 804 | if(copy_to_user(sg_user[i], sg_list[i], byte_count)){ 805 | dprintk((KERN_DEBUG"aacraid: Could not copy sg data to user\n")); 806 | rcode = -EFAULT; 807 | goto cleanup; 808 | 809 | } 810 | } 811 | } 812 | 813 | reply = (struct aac_srb_reply *) fib_data(srbfib); 814 | if(copy_to_user(user_reply,reply,sizeof(struct aac_srb_reply))){ 815 | dprintk((KERN_DEBUG"aacraid: Could not copy reply to user\n")); 816 | rcode = -EFAULT; 817 | goto cleanup; 818 | } 819 | 820 | cleanup: 821 | kfree(user_srbcmd); 822 | for(i=0; i <= sg_indx; i++){ 823 | kfree(sg_list[i]); 824 | } 825 | if (rcode != -ERESTARTSYS) { 826 | aac_fib_complete(srbfib); 827 | aac_fib_free(srbfib); 828 | } 829 | 830 | return rcode; 831 | } 832 | 833 | struct aac_pci_info { 834 | u32 bus; 835 | u32 slot; 836 | }; 837 | 838 | 839 | static int aac_get_pci_info(struct aac_dev* dev, void __user *arg) 840 | { 841 | struct aac_pci_info pci_info; 842 | 843 | pci_info.bus = dev->pdev->bus->number; 844 | pci_info.slot = PCI_SLOT(dev->pdev->devfn); 845 | 846 | if (copy_to_user(arg, &pci_info, sizeof(struct aac_pci_info))) { 847 | dprintk((KERN_DEBUG "aacraid: Could not copy pci info\n")); 848 | return -EFAULT; 849 | } 850 | return 0; 851 | } 852 | 853 | 854 | int aac_do_ioctl(struct aac_dev * dev, int cmd, void __user *arg) 855 | { 856 | int status; 857 | 858 | /* 859 | * HBA gets first crack 860 | */ 861 | 862 | status = aac_dev_ioctl(dev, cmd, arg); 863 | if (status != -ENOTTY) 864 | return status; 865 | 866 | switch (cmd) { 867 | case FSACTL_MINIPORT_REV_CHECK: 868 | status = check_revision(dev, arg); 869 | break; 870 | case FSACTL_SEND_LARGE_FIB: 871 | case FSACTL_SENDFIB: 872 | status = ioctl_send_fib(dev, arg); 873 | break; 874 | case FSACTL_OPEN_GET_ADAPTER_FIB: 875 | status = open_getadapter_fib(dev, arg); 876 | break; 877 | case FSACTL_GET_NEXT_ADAPTER_FIB: 878 | status = next_getadapter_fib(dev, arg); 879 | break; 880 | case FSACTL_CLOSE_GET_ADAPTER_FIB: 881 | status = close_getadapter_fib(dev, arg); 882 | break; 883 | case FSACTL_SEND_RAW_SRB: 884 | status = aac_send_raw_srb(dev,arg); 885 | break; 886 | case FSACTL_GET_PCI_INFO: 887 | status = aac_get_pci_info(dev,arg); 888 | break; 889 | default: 890 | status = -ENOTTY; 891 | break; 892 | } 893 | return status; 894 | } 895 | 896 | -------------------------------------------------------------------------------- /testdir/truecases/audit.c: -------------------------------------------------------------------------------- 1 | /* audit.c -- Auditing support 2 | * Gateway between the kernel (e.g., selinux) and the user-space audit daemon. 3 | * System-call specific features have moved to auditsc.c 4 | * 5 | * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina. 6 | * All Rights Reserved. 7 | * 8 | * This program is free software; you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation; either version 2 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program; if not, write to the Free Software 20 | * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | * 22 | * Written by Rickard E. (Rik) Faith 23 | * 24 | * Goals: 1) Integrate fully with Security Modules. 25 | * 2) Minimal run-time overhead: 26 | * a) Minimal when syscall auditing is disabled (audit_enable=0). 27 | * b) Small when syscall auditing is enabled and no audit record 28 | * is generated (defer as much work as possible to record 29 | * generation time): 30 | * i) context is allocated, 31 | * ii) names from getname are stored without a copy, and 32 | * iii) inode information stored from path_lookup. 33 | * 3) Ability to disable syscall auditing at boot time (audit=0). 34 | * 4) Usable by other parts of the kernel (if audit_log* is called, 35 | * then a syscall record will be generated automatically for the 36 | * current syscall). 37 | * 5) Netlink interface to user-space. 38 | * 6) Support low-overhead kernel-based filtering to minimize the 39 | * information that must be passed to user-space. 40 | * 41 | * Example user-space utilities: http://people.redhat.com/sgrubb/audit/ 42 | */ 43 | 44 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 45 | 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | #include 53 | #include 54 | #include 55 | #include 56 | #include 57 | 58 | #include 59 | 60 | #include 61 | #include 62 | #include 63 | #ifdef CONFIG_SECURITY 64 | #include 65 | #endif 66 | #include 67 | #include 68 | #include 69 | #include 70 | 71 | #include "audit.h" 72 | 73 | /* No auditing will take place until audit_initialized == AUDIT_INITIALIZED. 74 | * (Initialization happens after skb_init is called.) */ 75 | #define AUDIT_DISABLED -1 76 | #define AUDIT_UNINITIALIZED 0 77 | #define AUDIT_INITIALIZED 1 78 | static int audit_initialized; 79 | 80 | #define AUDIT_OFF 0 81 | #define AUDIT_ON 1 82 | #define AUDIT_LOCKED 2 83 | u32 audit_enabled; 84 | u32 audit_ever_enabled; 85 | 86 | EXPORT_SYMBOL_GPL(audit_enabled); 87 | 88 | /* Default state when kernel boots without any parameters. */ 89 | static u32 audit_default; 90 | 91 | /* If auditing cannot proceed, audit_failure selects what happens. */ 92 | static u32 audit_failure = AUDIT_FAIL_PRINTK; 93 | 94 | /* 95 | * If audit records are to be written to the netlink socket, audit_pid 96 | * contains the pid of the auditd process and audit_nlk_portid contains 97 | * the portid to use to send netlink messages to that process. 98 | */ 99 | int audit_pid; 100 | static __u32 audit_nlk_portid; 101 | 102 | /* If audit_rate_limit is non-zero, limit the rate of sending audit records 103 | * to that number per second. This prevents DoS attacks, but results in 104 | * audit records being dropped. */ 105 | static u32 audit_rate_limit; 106 | 107 | /* Number of outstanding audit_buffers allowed. 108 | * When set to zero, this means unlimited. */ 109 | static u32 audit_backlog_limit = 64; 110 | #define AUDIT_BACKLOG_WAIT_TIME (60 * HZ) 111 | static u32 audit_backlog_wait_time_master = AUDIT_BACKLOG_WAIT_TIME; 112 | static u32 audit_backlog_wait_time = AUDIT_BACKLOG_WAIT_TIME; 113 | 114 | /* The identity of the user shutting down the audit system. */ 115 | kuid_t audit_sig_uid = INVALID_UID; 116 | pid_t audit_sig_pid = -1; 117 | u32 audit_sig_sid = 0; 118 | 119 | /* Records can be lost in several ways: 120 | 0) [suppressed in audit_alloc] 121 | 1) out of memory in audit_log_start [kmalloc of struct audit_buffer] 122 | 2) out of memory in audit_log_move [alloc_skb] 123 | 3) suppressed due to audit_rate_limit 124 | 4) suppressed due to audit_backlog_limit 125 | */ 126 | static atomic_t audit_lost = ATOMIC_INIT(0); 127 | 128 | /* The netlink socket. */ 129 | static struct sock *audit_sock; 130 | static int audit_net_id; 131 | 132 | /* Hash for inode-based rules */ 133 | struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS]; 134 | 135 | /* The audit_freelist is a list of pre-allocated audit buffers (if more 136 | * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of 137 | * being placed on the freelist). */ 138 | static DEFINE_SPINLOCK(audit_freelist_lock); 139 | static int audit_freelist_count; 140 | static LIST_HEAD(audit_freelist); 141 | 142 | static struct sk_buff_head audit_skb_queue; 143 | /* queue of skbs to send to auditd when/if it comes back */ 144 | static struct sk_buff_head audit_skb_hold_queue; 145 | static struct task_struct *kauditd_task; 146 | static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait); 147 | static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait); 148 | 149 | static struct audit_features af = {.vers = AUDIT_FEATURE_VERSION, 150 | .mask = -1, 151 | .features = 0, 152 | .lock = 0,}; 153 | 154 | static char *audit_feature_names[2] = { 155 | "only_unset_loginuid", 156 | "loginuid_immutable", 157 | }; 158 | 159 | 160 | /* Serialize requests from userspace. */ 161 | DEFINE_MUTEX(audit_cmd_mutex); 162 | 163 | /* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting 164 | * audit records. Since printk uses a 1024 byte buffer, this buffer 165 | * should be at least that large. */ 166 | #define AUDIT_BUFSIZ 1024 167 | 168 | /* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the 169 | * audit_freelist. Doing so eliminates many kmalloc/kfree calls. */ 170 | #define AUDIT_MAXFREE (2*NR_CPUS) 171 | 172 | /* The audit_buffer is used when formatting an audit record. The caller 173 | * locks briefly to get the record off the freelist or to allocate the 174 | * buffer, and locks briefly to send the buffer to the netlink layer or 175 | * to place it on a transmit queue. Multiple audit_buffers can be in 176 | * use simultaneously. */ 177 | struct audit_buffer { 178 | struct list_head list; 179 | struct sk_buff *skb; /* formatted skb ready to send */ 180 | struct audit_context *ctx; /* NULL or associated context */ 181 | gfp_t gfp_mask; 182 | }; 183 | 184 | struct audit_reply { 185 | __u32 portid; 186 | struct net *net; 187 | struct sk_buff *skb; 188 | }; 189 | 190 | static void audit_set_portid(struct audit_buffer *ab, __u32 portid) 191 | { 192 | if (ab) { 193 | struct nlmsghdr *nlh = nlmsg_hdr(ab->skb); 194 | nlh->nlmsg_pid = portid; 195 | } 196 | } 197 | 198 | void audit_panic(const char *message) 199 | { 200 | switch (audit_failure) { 201 | case AUDIT_FAIL_SILENT: 202 | break; 203 | case AUDIT_FAIL_PRINTK: 204 | if (printk_ratelimit()) 205 | pr_err("%s\n", message); 206 | break; 207 | case AUDIT_FAIL_PANIC: 208 | /* test audit_pid since printk is always losey, why bother? */ 209 | if (audit_pid) 210 | panic("audit: %s\n", message); 211 | break; 212 | } 213 | } 214 | 215 | static inline int audit_rate_check(void) 216 | { 217 | static unsigned long last_check = 0; 218 | static int messages = 0; 219 | static DEFINE_SPINLOCK(lock); 220 | unsigned long flags; 221 | unsigned long now; 222 | unsigned long elapsed; 223 | int retval = 0; 224 | 225 | if (!audit_rate_limit) return 1; 226 | 227 | spin_lock_irqsave(&lock, flags); 228 | if (++messages < audit_rate_limit) { 229 | retval = 1; 230 | } else { 231 | now = jiffies; 232 | elapsed = now - last_check; 233 | if (elapsed > HZ) { 234 | last_check = now; 235 | messages = 0; 236 | retval = 1; 237 | } 238 | } 239 | spin_unlock_irqrestore(&lock, flags); 240 | 241 | return retval; 242 | } 243 | 244 | /** 245 | * audit_log_lost - conditionally log lost audit message event 246 | * @message: the message stating reason for lost audit message 247 | * 248 | * Emit at least 1 message per second, even if audit_rate_check is 249 | * throttling. 250 | * Always increment the lost messages counter. 251 | */ 252 | void audit_log_lost(const char *message) 253 | { 254 | static unsigned long last_msg = 0; 255 | static DEFINE_SPINLOCK(lock); 256 | unsigned long flags; 257 | unsigned long now; 258 | int print; 259 | 260 | atomic_inc(&audit_lost); 261 | 262 | print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit); 263 | 264 | if (!print) { 265 | spin_lock_irqsave(&lock, flags); 266 | now = jiffies; 267 | if (now - last_msg > HZ) { 268 | print = 1; 269 | last_msg = now; 270 | } 271 | spin_unlock_irqrestore(&lock, flags); 272 | } 273 | 274 | if (print) { 275 | if (printk_ratelimit()) 276 | pr_warn("audit_lost=%u audit_rate_limit=%u audit_backlog_limit=%u\n", 277 | atomic_read(&audit_lost), 278 | audit_rate_limit, 279 | audit_backlog_limit); 280 | audit_panic(message); 281 | } 282 | } 283 | 284 | static int audit_log_config_change(char *function_name, u32 new, u32 old, 285 | int allow_changes) 286 | { 287 | struct audit_buffer *ab; 288 | int rc = 0; 289 | 290 | ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE); 291 | if (unlikely(!ab)) 292 | return rc; 293 | audit_log_format(ab, "%s=%u old=%u", function_name, new, old); 294 | audit_log_session_info(ab); 295 | rc = audit_log_task_context(ab); 296 | if (rc) 297 | allow_changes = 0; /* Something weird, deny request */ 298 | audit_log_format(ab, " res=%d", allow_changes); 299 | audit_log_end(ab); 300 | return rc; 301 | } 302 | 303 | static int audit_do_config_change(char *function_name, u32 *to_change, u32 new) 304 | { 305 | int allow_changes, rc = 0; 306 | u32 old = *to_change; 307 | 308 | /* check if we are locked */ 309 | if (audit_enabled == AUDIT_LOCKED) 310 | allow_changes = 0; 311 | else 312 | allow_changes = 1; 313 | 314 | if (audit_enabled != AUDIT_OFF) { 315 | rc = audit_log_config_change(function_name, new, old, allow_changes); 316 | if (rc) 317 | allow_changes = 0; 318 | } 319 | 320 | /* If we are allowed, make the change */ 321 | if (allow_changes == 1) 322 | *to_change = new; 323 | /* Not allowed, update reason */ 324 | else if (rc == 0) 325 | rc = -EPERM; 326 | return rc; 327 | } 328 | 329 | static int audit_set_rate_limit(u32 limit) 330 | { 331 | return audit_do_config_change("audit_rate_limit", &audit_rate_limit, limit); 332 | } 333 | 334 | static int audit_set_backlog_limit(u32 limit) 335 | { 336 | return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit, limit); 337 | } 338 | 339 | static int audit_set_backlog_wait_time(u32 timeout) 340 | { 341 | return audit_do_config_change("audit_backlog_wait_time", 342 | &audit_backlog_wait_time_master, timeout); 343 | } 344 | 345 | static int audit_set_enabled(u32 state) 346 | { 347 | int rc; 348 | if (state > AUDIT_LOCKED) 349 | return -EINVAL; 350 | 351 | rc = audit_do_config_change("audit_enabled", &audit_enabled, state); 352 | if (!rc) 353 | audit_ever_enabled |= !!state; 354 | 355 | return rc; 356 | } 357 | 358 | static int audit_set_failure(u32 state) 359 | { 360 | if (state != AUDIT_FAIL_SILENT 361 | && state != AUDIT_FAIL_PRINTK 362 | && state != AUDIT_FAIL_PANIC) 363 | return -EINVAL; 364 | 365 | return audit_do_config_change("audit_failure", &audit_failure, state); 366 | } 367 | 368 | /* 369 | * Queue skbs to be sent to auditd when/if it comes back. These skbs should 370 | * already have been sent via prink/syslog and so if these messages are dropped 371 | * it is not a huge concern since we already passed the audit_log_lost() 372 | * notification and stuff. This is just nice to get audit messages during 373 | * boot before auditd is running or messages generated while auditd is stopped. 374 | * This only holds messages is audit_default is set, aka booting with audit=1 375 | * or building your kernel that way. 376 | */ 377 | static void audit_hold_skb(struct sk_buff *skb) 378 | { 379 | if (audit_default && 380 | (!audit_backlog_limit || 381 | skb_queue_len(&audit_skb_hold_queue) < audit_backlog_limit)) 382 | skb_queue_tail(&audit_skb_hold_queue, skb); 383 | else 384 | kfree_skb(skb); 385 | } 386 | 387 | /* 388 | * For one reason or another this nlh isn't getting delivered to the userspace 389 | * audit daemon, just send it to printk. 390 | */ 391 | static void audit_printk_skb(struct sk_buff *skb) 392 | { 393 | struct nlmsghdr *nlh = nlmsg_hdr(skb); 394 | char *data = nlmsg_data(nlh); 395 | 396 | if (nlh->nlmsg_type != AUDIT_EOE) { 397 | if (printk_ratelimit()) 398 | pr_notice("type=%d %s\n", nlh->nlmsg_type, data); 399 | else 400 | audit_log_lost("printk limit exceeded"); 401 | } 402 | 403 | audit_hold_skb(skb); 404 | } 405 | 406 | static void kauditd_send_skb(struct sk_buff *skb) 407 | { 408 | int err; 409 | int attempts = 0; 410 | #define AUDITD_RETRIES 5 411 | 412 | restart: 413 | /* take a reference in case we can't send it and we want to hold it */ 414 | skb_get(skb); 415 | err = netlink_unicast(audit_sock, skb, audit_nlk_portid, 0); 416 | if (err < 0) { 417 | pr_err("netlink_unicast sending to audit_pid=%d returned error: %d\n", 418 | audit_pid, err); 419 | if (audit_pid) { 420 | if (err == -ECONNREFUSED || err == -EPERM 421 | || ++attempts >= AUDITD_RETRIES) { 422 | char s[32]; 423 | 424 | snprintf(s, sizeof(s), "audit_pid=%d reset", audit_pid); 425 | audit_log_lost(s); 426 | audit_pid = 0; 427 | audit_sock = NULL; 428 | } else { 429 | pr_warn("re-scheduling(#%d) write to audit_pid=%d\n", 430 | attempts, audit_pid); 431 | set_current_state(TASK_INTERRUPTIBLE); 432 | schedule(); 433 | __set_current_state(TASK_RUNNING); 434 | goto restart; 435 | } 436 | } 437 | /* we might get lucky and get this in the next auditd */ 438 | audit_hold_skb(skb); 439 | } else 440 | /* drop the extra reference if sent ok */ 441 | consume_skb(skb); 442 | } 443 | 444 | /* 445 | * kauditd_send_multicast_skb - send the skb to multicast userspace listeners 446 | * 447 | * This function doesn't consume an skb as might be expected since it has to 448 | * copy it anyways. 449 | */ 450 | static void kauditd_send_multicast_skb(struct sk_buff *skb, gfp_t gfp_mask) 451 | { 452 | struct sk_buff *copy; 453 | struct audit_net *aunet = net_generic(&init_net, audit_net_id); 454 | struct sock *sock = aunet->nlsk; 455 | 456 | if (!netlink_has_listeners(sock, AUDIT_NLGRP_READLOG)) 457 | return; 458 | 459 | /* 460 | * The seemingly wasteful skb_copy() rather than bumping the refcount 461 | * using skb_get() is necessary because non-standard mods are made to 462 | * the skb by the original kaudit unicast socket send routine. The 463 | * existing auditd daemon assumes this breakage. Fixing this would 464 | * require co-ordinating a change in the established protocol between 465 | * the kaudit kernel subsystem and the auditd userspace code. There is 466 | * no reason for new multicast clients to continue with this 467 | * non-compliance. 468 | */ 469 | copy = skb_copy(skb, gfp_mask); 470 | if (!copy) 471 | return; 472 | 473 | nlmsg_multicast(sock, copy, 0, AUDIT_NLGRP_READLOG, gfp_mask); 474 | } 475 | 476 | /* 477 | * flush_hold_queue - empty the hold queue if auditd appears 478 | * 479 | * If auditd just started, drain the queue of messages already 480 | * sent to syslog/printk. Remember loss here is ok. We already 481 | * called audit_log_lost() if it didn't go out normally. so the 482 | * race between the skb_dequeue and the next check for audit_pid 483 | * doesn't matter. 484 | * 485 | * If you ever find kauditd to be too slow we can get a perf win 486 | * by doing our own locking and keeping better track if there 487 | * are messages in this queue. I don't see the need now, but 488 | * in 5 years when I want to play with this again I'll see this 489 | * note and still have no friggin idea what i'm thinking today. 490 | */ 491 | static void flush_hold_queue(void) 492 | { 493 | struct sk_buff *skb; 494 | 495 | if (!audit_default || !audit_pid) 496 | return; 497 | 498 | skb = skb_dequeue(&audit_skb_hold_queue); 499 | if (likely(!skb)) 500 | return; 501 | 502 | while (skb && audit_pid) { 503 | kauditd_send_skb(skb); 504 | skb = skb_dequeue(&audit_skb_hold_queue); 505 | } 506 | 507 | /* 508 | * if auditd just disappeared but we 509 | * dequeued an skb we need to drop ref 510 | */ 511 | consume_skb(skb); 512 | } 513 | 514 | static int kauditd_thread(void *dummy) 515 | { 516 | set_freezable(); 517 | while (!kthread_should_stop()) { 518 | struct sk_buff *skb; 519 | 520 | flush_hold_queue(); 521 | 522 | skb = skb_dequeue(&audit_skb_queue); 523 | 524 | if (skb) { 525 | if (!audit_backlog_limit || 526 | (skb_queue_len(&audit_skb_queue) <= audit_backlog_limit)) 527 | wake_up(&audit_backlog_wait); 528 | if (audit_pid) 529 | kauditd_send_skb(skb); 530 | else 531 | audit_printk_skb(skb); 532 | continue; 533 | } 534 | 535 | wait_event_freezable(kauditd_wait, skb_queue_len(&audit_skb_queue)); 536 | } 537 | return 0; 538 | } 539 | 540 | int audit_send_list(void *_dest) 541 | { 542 | struct audit_netlink_list *dest = _dest; 543 | struct sk_buff *skb; 544 | struct net *net = dest->net; 545 | struct audit_net *aunet = net_generic(net, audit_net_id); 546 | 547 | /* wait for parent to finish and send an ACK */ 548 | mutex_lock(&audit_cmd_mutex); 549 | mutex_unlock(&audit_cmd_mutex); 550 | 551 | while ((skb = __skb_dequeue(&dest->q)) != NULL) 552 | netlink_unicast(aunet->nlsk, skb, dest->portid, 0); 553 | 554 | put_net(net); 555 | kfree(dest); 556 | 557 | return 0; 558 | } 559 | 560 | struct sk_buff *audit_make_reply(__u32 portid, int seq, int type, int done, 561 | int multi, const void *payload, int size) 562 | { 563 | struct sk_buff *skb; 564 | struct nlmsghdr *nlh; 565 | void *data; 566 | int flags = multi ? NLM_F_MULTI : 0; 567 | int t = done ? NLMSG_DONE : type; 568 | 569 | skb = nlmsg_new(size, GFP_KERNEL); 570 | if (!skb) 571 | return NULL; 572 | 573 | nlh = nlmsg_put(skb, portid, seq, t, size, flags); 574 | if (!nlh) 575 | goto out_kfree_skb; 576 | data = nlmsg_data(nlh); 577 | memcpy(data, payload, size); 578 | return skb; 579 | 580 | out_kfree_skb: 581 | kfree_skb(skb); 582 | return NULL; 583 | } 584 | 585 | static int audit_send_reply_thread(void *arg) 586 | { 587 | struct audit_reply *reply = (struct audit_reply *)arg; 588 | struct net *net = reply->net; 589 | struct audit_net *aunet = net_generic(net, audit_net_id); 590 | 591 | mutex_lock(&audit_cmd_mutex); 592 | mutex_unlock(&audit_cmd_mutex); 593 | 594 | /* Ignore failure. It'll only happen if the sender goes away, 595 | because our timeout is set to infinite. */ 596 | netlink_unicast(aunet->nlsk , reply->skb, reply->portid, 0); 597 | put_net(net); 598 | kfree(reply); 599 | return 0; 600 | } 601 | /** 602 | * audit_send_reply - send an audit reply message via netlink 603 | * @request_skb: skb of request we are replying to (used to target the reply) 604 | * @seq: sequence number 605 | * @type: audit message type 606 | * @done: done (last) flag 607 | * @multi: multi-part message flag 608 | * @payload: payload data 609 | * @size: payload size 610 | * 611 | * Allocates an skb, builds the netlink message, and sends it to the port id. 612 | * No failure notifications. 613 | */ 614 | static void audit_send_reply(struct sk_buff *request_skb, int seq, int type, int done, 615 | int multi, const void *payload, int size) 616 | { 617 | u32 portid = NETLINK_CB(request_skb).portid; 618 | struct net *net = sock_net(NETLINK_CB(request_skb).sk); 619 | struct sk_buff *skb; 620 | struct task_struct *tsk; 621 | struct audit_reply *reply = kmalloc(sizeof(struct audit_reply), 622 | GFP_KERNEL); 623 | 624 | if (!reply) 625 | return; 626 | 627 | skb = audit_make_reply(portid, seq, type, done, multi, payload, size); 628 | if (!skb) 629 | goto out; 630 | 631 | reply->net = get_net(net); 632 | reply->portid = portid; 633 | reply->skb = skb; 634 | 635 | tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply"); 636 | if (!IS_ERR(tsk)) 637 | return; 638 | kfree_skb(skb); 639 | out: 640 | kfree(reply); 641 | } 642 | 643 | /* 644 | * Check for appropriate CAP_AUDIT_ capabilities on incoming audit 645 | * control messages. 646 | */ 647 | static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type) 648 | { 649 | int err = 0; 650 | 651 | /* Only support initial user namespace for now. */ 652 | /* 653 | * We return ECONNREFUSED because it tricks userspace into thinking 654 | * that audit was not configured into the kernel. Lots of users 655 | * configure their PAM stack (because that's what the distro does) 656 | * to reject login if unable to send messages to audit. If we return 657 | * ECONNREFUSED the PAM stack thinks the kernel does not have audit 658 | * configured in and will let login proceed. If we return EPERM 659 | * userspace will reject all logins. This should be removed when we 660 | * support non init namespaces!! 661 | */ 662 | if (current_user_ns() != &init_user_ns) 663 | return -ECONNREFUSED; 664 | 665 | switch (msg_type) { 666 | case AUDIT_LIST: 667 | case AUDIT_ADD: 668 | case AUDIT_DEL: 669 | return -EOPNOTSUPP; 670 | case AUDIT_GET: 671 | case AUDIT_SET: 672 | case AUDIT_GET_FEATURE: 673 | case AUDIT_SET_FEATURE: 674 | case AUDIT_LIST_RULES: 675 | case AUDIT_ADD_RULE: 676 | case AUDIT_DEL_RULE: 677 | case AUDIT_SIGNAL_INFO: 678 | case AUDIT_TTY_GET: 679 | case AUDIT_TTY_SET: 680 | case AUDIT_TRIM: 681 | case AUDIT_MAKE_EQUIV: 682 | /* Only support auditd and auditctl in initial pid namespace 683 | * for now. */ 684 | if (task_active_pid_ns(current) != &init_pid_ns) 685 | return -EPERM; 686 | 687 | if (!netlink_capable(skb, CAP_AUDIT_CONTROL)) 688 | err = -EPERM; 689 | break; 690 | case AUDIT_USER: 691 | case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG: 692 | case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2: 693 | if (!netlink_capable(skb, CAP_AUDIT_WRITE)) 694 | err = -EPERM; 695 | break; 696 | default: /* bad msg */ 697 | err = -EINVAL; 698 | } 699 | 700 | return err; 701 | } 702 | 703 | static void audit_log_common_recv_msg(struct audit_buffer **ab, u16 msg_type) 704 | { 705 | uid_t uid = from_kuid(&init_user_ns, current_uid()); 706 | pid_t pid = task_tgid_nr(current); 707 | 708 | if (!audit_enabled && msg_type != AUDIT_USER_AVC) { 709 | *ab = NULL; 710 | return; 711 | } 712 | 713 | *ab = audit_log_start(NULL, GFP_KERNEL, msg_type); 714 | if (unlikely(!*ab)) 715 | return; 716 | audit_log_format(*ab, "pid=%d uid=%u", pid, uid); 717 | audit_log_session_info(*ab); 718 | audit_log_task_context(*ab); 719 | } 720 | 721 | int is_audit_feature_set(int i) 722 | { 723 | return af.features & AUDIT_FEATURE_TO_MASK(i); 724 | } 725 | 726 | 727 | static int audit_get_feature(struct sk_buff *skb) 728 | { 729 | u32 seq; 730 | 731 | seq = nlmsg_hdr(skb)->nlmsg_seq; 732 | 733 | audit_send_reply(skb, seq, AUDIT_GET_FEATURE, 0, 0, &af, sizeof(af)); 734 | 735 | return 0; 736 | } 737 | 738 | static void audit_log_feature_change(int which, u32 old_feature, u32 new_feature, 739 | u32 old_lock, u32 new_lock, int res) 740 | { 741 | struct audit_buffer *ab; 742 | 743 | if (audit_enabled == AUDIT_OFF) 744 | return; 745 | 746 | ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_FEATURE_CHANGE); 747 | audit_log_task_info(ab, current); 748 | audit_log_format(ab, " feature=%s old=%u new=%u old_lock=%u new_lock=%u res=%d", 749 | audit_feature_names[which], !!old_feature, !!new_feature, 750 | !!old_lock, !!new_lock, res); 751 | audit_log_end(ab); 752 | } 753 | 754 | static int audit_set_feature(struct sk_buff *skb) 755 | { 756 | struct audit_features *uaf; 757 | int i; 758 | 759 | BUILD_BUG_ON(AUDIT_LAST_FEATURE + 1 > ARRAY_SIZE(audit_feature_names)); 760 | uaf = nlmsg_data(nlmsg_hdr(skb)); 761 | 762 | /* if there is ever a version 2 we should handle that here */ 763 | 764 | for (i = 0; i <= AUDIT_LAST_FEATURE; i++) { 765 | u32 feature = AUDIT_FEATURE_TO_MASK(i); 766 | u32 old_feature, new_feature, old_lock, new_lock; 767 | 768 | /* if we are not changing this feature, move along */ 769 | if (!(feature & uaf->mask)) 770 | continue; 771 | 772 | old_feature = af.features & feature; 773 | new_feature = uaf->features & feature; 774 | new_lock = (uaf->lock | af.lock) & feature; 775 | old_lock = af.lock & feature; 776 | 777 | /* are we changing a locked feature? */ 778 | if (old_lock && (new_feature != old_feature)) { 779 | audit_log_feature_change(i, old_feature, new_feature, 780 | old_lock, new_lock, 0); 781 | return -EPERM; 782 | } 783 | } 784 | /* nothing invalid, do the changes */ 785 | for (i = 0; i <= AUDIT_LAST_FEATURE; i++) { 786 | u32 feature = AUDIT_FEATURE_TO_MASK(i); 787 | u32 old_feature, new_feature, old_lock, new_lock; 788 | 789 | /* if we are not changing this feature, move along */ 790 | if (!(feature & uaf->mask)) 791 | continue; 792 | 793 | old_feature = af.features & feature; 794 | new_feature = uaf->features & feature; 795 | old_lock = af.lock & feature; 796 | new_lock = (uaf->lock | af.lock) & feature; 797 | 798 | if (new_feature != old_feature) 799 | audit_log_feature_change(i, old_feature, new_feature, 800 | old_lock, new_lock, 1); 801 | 802 | if (new_feature) 803 | af.features |= feature; 804 | else 805 | af.features &= ~feature; 806 | af.lock |= new_lock; 807 | } 808 | 809 | return 0; 810 | } 811 | 812 | static int audit_replace(pid_t pid) 813 | { 814 | struct sk_buff *skb = audit_make_reply(0, 0, AUDIT_REPLACE, 0, 0, 815 | &pid, sizeof(pid)); 816 | 817 | if (!skb) 818 | return -ENOMEM; 819 | return netlink_unicast(audit_sock, skb, audit_nlk_portid, 0); 820 | } 821 | 822 | static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh) 823 | { 824 | u32 seq; 825 | void *data; 826 | int err; 827 | struct audit_buffer *ab; 828 | u16 msg_type = nlh->nlmsg_type; 829 | struct audit_sig_info *sig_data; 830 | char *ctx = NULL; 831 | u32 len; 832 | 833 | err = audit_netlink_ok(skb, msg_type); 834 | if (err) 835 | return err; 836 | 837 | /* As soon as there's any sign of userspace auditd, 838 | * start kauditd to talk to it */ 839 | if (!kauditd_task) { 840 | kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd"); 841 | if (IS_ERR(kauditd_task)) { 842 | err = PTR_ERR(kauditd_task); 843 | kauditd_task = NULL; 844 | return err; 845 | } 846 | } 847 | seq = nlh->nlmsg_seq; 848 | data = nlmsg_data(nlh); 849 | 850 | switch (msg_type) { 851 | case AUDIT_GET: { 852 | struct audit_status s; 853 | memset(&s, 0, sizeof(s)); 854 | s.enabled = audit_enabled; 855 | s.failure = audit_failure; 856 | s.pid = audit_pid; 857 | s.rate_limit = audit_rate_limit; 858 | s.backlog_limit = audit_backlog_limit; 859 | s.lost = atomic_read(&audit_lost); 860 | s.backlog = skb_queue_len(&audit_skb_queue); 861 | s.feature_bitmap = AUDIT_FEATURE_BITMAP_ALL; 862 | s.backlog_wait_time = audit_backlog_wait_time_master; 863 | audit_send_reply(skb, seq, AUDIT_GET, 0, 0, &s, sizeof(s)); 864 | break; 865 | } 866 | case AUDIT_SET: { 867 | struct audit_status s; 868 | memset(&s, 0, sizeof(s)); 869 | /* guard against past and future API changes */ 870 | memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh))); 871 | if (s.mask & AUDIT_STATUS_ENABLED) { 872 | err = audit_set_enabled(s.enabled); 873 | if (err < 0) 874 | return err; 875 | } 876 | if (s.mask & AUDIT_STATUS_FAILURE) { 877 | err = audit_set_failure(s.failure); 878 | if (err < 0) 879 | return err; 880 | } 881 | if (s.mask & AUDIT_STATUS_PID) { 882 | int new_pid = s.pid; 883 | pid_t requesting_pid = task_tgid_vnr(current); 884 | 885 | if ((!new_pid) && (requesting_pid != audit_pid)) { 886 | audit_log_config_change("audit_pid", new_pid, audit_pid, 0); 887 | return -EACCES; 888 | } 889 | if (audit_pid && new_pid && 890 | audit_replace(requesting_pid) != -ECONNREFUSED) { 891 | audit_log_config_change("audit_pid", new_pid, audit_pid, 0); 892 | return -EEXIST; 893 | } 894 | if (audit_enabled != AUDIT_OFF) 895 | audit_log_config_change("audit_pid", new_pid, audit_pid, 1); 896 | audit_pid = new_pid; 897 | audit_nlk_portid = NETLINK_CB(skb).portid; 898 | audit_sock = skb->sk; 899 | } 900 | if (s.mask & AUDIT_STATUS_RATE_LIMIT) { 901 | err = audit_set_rate_limit(s.rate_limit); 902 | if (err < 0) 903 | return err; 904 | } 905 | if (s.mask & AUDIT_STATUS_BACKLOG_LIMIT) { 906 | err = audit_set_backlog_limit(s.backlog_limit); 907 | if (err < 0) 908 | return err; 909 | } 910 | if (s.mask & AUDIT_STATUS_BACKLOG_WAIT_TIME) { 911 | if (sizeof(s) > (size_t)nlh->nlmsg_len) 912 | return -EINVAL; 913 | if (s.backlog_wait_time > 10*AUDIT_BACKLOG_WAIT_TIME) 914 | return -EINVAL; 915 | err = audit_set_backlog_wait_time(s.backlog_wait_time); 916 | if (err < 0) 917 | return err; 918 | } 919 | break; 920 | } 921 | case AUDIT_GET_FEATURE: 922 | err = audit_get_feature(skb); 923 | if (err) 924 | return err; 925 | break; 926 | case AUDIT_SET_FEATURE: 927 | err = audit_set_feature(skb); 928 | if (err) 929 | return err; 930 | break; 931 | case AUDIT_USER: 932 | case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG: 933 | case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2: 934 | if (!audit_enabled && msg_type != AUDIT_USER_AVC) 935 | return 0; 936 | 937 | err = audit_filter_user(msg_type); 938 | if (err == 1) { /* match or error */ 939 | err = 0; 940 | if (msg_type == AUDIT_USER_TTY) { 941 | err = tty_audit_push(); 942 | if (err) 943 | break; 944 | } 945 | mutex_unlock(&audit_cmd_mutex); 946 | audit_log_common_recv_msg(&ab, msg_type); 947 | if (msg_type != AUDIT_USER_TTY) 948 | audit_log_format(ab, " msg='%.*s'", 949 | AUDIT_MESSAGE_TEXT_MAX, 950 | (char *)data); 951 | else { 952 | int size; 953 | 954 | audit_log_format(ab, " data="); 955 | size = nlmsg_len(nlh); 956 | if (size > 0 && 957 | ((unsigned char *)data)[size - 1] == '\0') 958 | size--; 959 | audit_log_n_untrustedstring(ab, data, size); 960 | } 961 | audit_set_portid(ab, NETLINK_CB(skb).portid); 962 | audit_log_end(ab); 963 | mutex_lock(&audit_cmd_mutex); 964 | } 965 | break; 966 | case AUDIT_ADD_RULE: 967 | case AUDIT_DEL_RULE: 968 | if (nlmsg_len(nlh) < sizeof(struct audit_rule_data)) 969 | return -EINVAL; 970 | if (audit_enabled == AUDIT_LOCKED) { 971 | audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE); 972 | audit_log_format(ab, " audit_enabled=%d res=0", audit_enabled); 973 | audit_log_end(ab); 974 | return -EPERM; 975 | } 976 | err = audit_rule_change(msg_type, NETLINK_CB(skb).portid, 977 | seq, data, nlmsg_len(nlh)); 978 | break; 979 | case AUDIT_LIST_RULES: 980 | err = audit_list_rules_send(skb, seq); 981 | break; 982 | case AUDIT_TRIM: 983 | audit_trim_trees(); 984 | audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE); 985 | audit_log_format(ab, " op=trim res=1"); 986 | audit_log_end(ab); 987 | break; 988 | case AUDIT_MAKE_EQUIV: { 989 | void *bufp = data; 990 | u32 sizes[2]; 991 | size_t msglen = nlmsg_len(nlh); 992 | char *old, *new; 993 | 994 | err = -EINVAL; 995 | if (msglen < 2 * sizeof(u32)) 996 | break; 997 | memcpy(sizes, bufp, 2 * sizeof(u32)); 998 | bufp += 2 * sizeof(u32); 999 | msglen -= 2 * sizeof(u32); 1000 | old = audit_unpack_string(&bufp, &msglen, sizes[0]); 1001 | if (IS_ERR(old)) { 1002 | err = PTR_ERR(old); 1003 | break; 1004 | } 1005 | new = audit_unpack_string(&bufp, &msglen, sizes[1]); 1006 | if (IS_ERR(new)) { 1007 | err = PTR_ERR(new); 1008 | kfree(old); 1009 | break; 1010 | } 1011 | /* OK, here comes... */ 1012 | err = audit_tag_tree(old, new); 1013 | 1014 | audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE); 1015 | 1016 | audit_log_format(ab, " op=make_equiv old="); 1017 | audit_log_untrustedstring(ab, old); 1018 | audit_log_format(ab, " new="); 1019 | audit_log_untrustedstring(ab, new); 1020 | audit_log_format(ab, " res=%d", !err); 1021 | audit_log_end(ab); 1022 | kfree(old); 1023 | kfree(new); 1024 | break; 1025 | } 1026 | case AUDIT_SIGNAL_INFO: 1027 | len = 0; 1028 | if (audit_sig_sid) { 1029 | err = security_secid_to_secctx(audit_sig_sid, &ctx, &len); 1030 | if (err) 1031 | return err; 1032 | } 1033 | sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL); 1034 | if (!sig_data) { 1035 | if (audit_sig_sid) 1036 | security_release_secctx(ctx, len); 1037 | return -ENOMEM; 1038 | } 1039 | sig_data->uid = from_kuid(&init_user_ns, audit_sig_uid); 1040 | sig_data->pid = audit_sig_pid; 1041 | if (audit_sig_sid) { 1042 | memcpy(sig_data->ctx, ctx, len); 1043 | security_release_secctx(ctx, len); 1044 | } 1045 | audit_send_reply(skb, seq, AUDIT_SIGNAL_INFO, 0, 0, 1046 | sig_data, sizeof(*sig_data) + len); 1047 | kfree(sig_data); 1048 | break; 1049 | case AUDIT_TTY_GET: { 1050 | struct audit_tty_status s; 1051 | unsigned int t; 1052 | 1053 | t = READ_ONCE(current->signal->audit_tty); 1054 | s.enabled = t & AUDIT_TTY_ENABLE; 1055 | s.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD); 1056 | 1057 | audit_send_reply(skb, seq, AUDIT_TTY_GET, 0, 0, &s, sizeof(s)); 1058 | break; 1059 | } 1060 | case AUDIT_TTY_SET: { 1061 | struct audit_tty_status s, old; 1062 | struct audit_buffer *ab; 1063 | unsigned int t; 1064 | 1065 | memset(&s, 0, sizeof(s)); 1066 | /* guard against past and future API changes */ 1067 | memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh))); 1068 | /* check if new data is valid */ 1069 | if ((s.enabled != 0 && s.enabled != 1) || 1070 | (s.log_passwd != 0 && s.log_passwd != 1)) 1071 | err = -EINVAL; 1072 | 1073 | if (err) 1074 | t = READ_ONCE(current->signal->audit_tty); 1075 | else { 1076 | t = s.enabled | (-s.log_passwd & AUDIT_TTY_LOG_PASSWD); 1077 | t = xchg(¤t->signal->audit_tty, t); 1078 | } 1079 | old.enabled = t & AUDIT_TTY_ENABLE; 1080 | old.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD); 1081 | 1082 | audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE); 1083 | audit_log_format(ab, " op=tty_set old-enabled=%d new-enabled=%d" 1084 | " old-log_passwd=%d new-log_passwd=%d res=%d", 1085 | old.enabled, s.enabled, old.log_passwd, 1086 | s.log_passwd, !err); 1087 | audit_log_end(ab); 1088 | break; 1089 | } 1090 | default: 1091 | err = -EINVAL; 1092 | break; 1093 | } 1094 | 1095 | return err < 0 ? err : 0; 1096 | } 1097 | 1098 | /* 1099 | * Get message from skb. Each message is processed by audit_receive_msg. 1100 | * Malformed skbs with wrong length are discarded silently. 1101 | */ 1102 | static void audit_receive_skb(struct sk_buff *skb) 1103 | { 1104 | struct nlmsghdr *nlh; 1105 | /* 1106 | * len MUST be signed for nlmsg_next to be able to dec it below 0 1107 | * if the nlmsg_len was not aligned 1108 | */ 1109 | int len; 1110 | int err; 1111 | 1112 | nlh = nlmsg_hdr(skb); 1113 | len = skb->len; 1114 | 1115 | while (nlmsg_ok(nlh, len)) { 1116 | err = audit_receive_msg(skb, nlh); 1117 | /* if err or if this message says it wants a response */ 1118 | if (err || (nlh->nlmsg_flags & NLM_F_ACK)) 1119 | netlink_ack(skb, nlh, err); 1120 | 1121 | nlh = nlmsg_next(nlh, &len); 1122 | } 1123 | } 1124 | 1125 | /* Receive messages from netlink socket. */ 1126 | static void audit_receive(struct sk_buff *skb) 1127 | { 1128 | mutex_lock(&audit_cmd_mutex); 1129 | audit_receive_skb(skb); 1130 | mutex_unlock(&audit_cmd_mutex); 1131 | } 1132 | 1133 | /* Run custom bind function on netlink socket group connect or bind requests. */ 1134 | static int audit_bind(struct net *net, int group) 1135 | { 1136 | if (!capable(CAP_AUDIT_READ)) 1137 | return -EPERM; 1138 | 1139 | return 0; 1140 | } 1141 | 1142 | static int __net_init audit_net_init(struct net *net) 1143 | { 1144 | struct netlink_kernel_cfg cfg = { 1145 | .input = audit_receive, 1146 | .bind = audit_bind, 1147 | .flags = NL_CFG_F_NONROOT_RECV, 1148 | .groups = AUDIT_NLGRP_MAX, 1149 | }; 1150 | 1151 | struct audit_net *aunet = net_generic(net, audit_net_id); 1152 | 1153 | aunet->nlsk = netlink_kernel_create(net, NETLINK_AUDIT, &cfg); 1154 | if (aunet->nlsk == NULL) { 1155 | audit_panic("cannot initialize netlink socket in namespace"); 1156 | return -ENOMEM; 1157 | } 1158 | aunet->nlsk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; 1159 | return 0; 1160 | } 1161 | 1162 | static void __net_exit audit_net_exit(struct net *net) 1163 | { 1164 | struct audit_net *aunet = net_generic(net, audit_net_id); 1165 | struct sock *sock = aunet->nlsk; 1166 | if (sock == audit_sock) { 1167 | audit_pid = 0; 1168 | audit_sock = NULL; 1169 | } 1170 | 1171 | RCU_INIT_POINTER(aunet->nlsk, NULL); 1172 | synchronize_net(); 1173 | netlink_kernel_release(sock); 1174 | } 1175 | 1176 | static struct pernet_operations audit_net_ops __net_initdata = { 1177 | .init = audit_net_init, 1178 | .exit = audit_net_exit, 1179 | .id = &audit_net_id, 1180 | .size = sizeof(struct audit_net), 1181 | }; 1182 | 1183 | /* Initialize audit support at boot time. */ 1184 | static int __init audit_init(void) 1185 | { 1186 | int i; 1187 | 1188 | if (audit_initialized == AUDIT_DISABLED) 1189 | return 0; 1190 | 1191 | pr_info("initializing netlink subsys (%s)\n", 1192 | audit_default ? "enabled" : "disabled"); 1193 | register_pernet_subsys(&audit_net_ops); 1194 | 1195 | skb_queue_head_init(&audit_skb_queue); 1196 | skb_queue_head_init(&audit_skb_hold_queue); 1197 | audit_initialized = AUDIT_INITIALIZED; 1198 | audit_enabled = audit_default; 1199 | audit_ever_enabled |= !!audit_default; 1200 | 1201 | audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized"); 1202 | 1203 | for (i = 0; i < AUDIT_INODE_BUCKETS; i++) 1204 | INIT_LIST_HEAD(&audit_inode_hash[i]); 1205 | 1206 | return 0; 1207 | } 1208 | __initcall(audit_init); 1209 | 1210 | /* Process kernel command-line parameter at boot time. audit=0 or audit=1. */ 1211 | static int __init audit_enable(char *str) 1212 | { 1213 | audit_default = !!simple_strtol(str, NULL, 0); 1214 | if (!audit_default) 1215 | audit_initialized = AUDIT_DISABLED; 1216 | 1217 | pr_info("%s\n", audit_default ? 1218 | "enabled (after initialization)" : "disabled (until reboot)"); 1219 | 1220 | return 1; 1221 | } 1222 | __setup("audit=", audit_enable); 1223 | 1224 | /* Process kernel command-line parameter at boot time. 1225 | * audit_backlog_limit= */ 1226 | static int __init audit_backlog_limit_set(char *str) 1227 | { 1228 | u32 audit_backlog_limit_arg; 1229 | 1230 | pr_info("audit_backlog_limit: "); 1231 | if (kstrtouint(str, 0, &audit_backlog_limit_arg)) { 1232 | pr_cont("using default of %u, unable to parse %s\n", 1233 | audit_backlog_limit, str); 1234 | return 1; 1235 | } 1236 | 1237 | audit_backlog_limit = audit_backlog_limit_arg; 1238 | pr_cont("%d\n", audit_backlog_limit); 1239 | 1240 | return 1; 1241 | } 1242 | __setup("audit_backlog_limit=", audit_backlog_limit_set); 1243 | 1244 | static void audit_buffer_free(struct audit_buffer *ab) 1245 | { 1246 | unsigned long flags; 1247 | 1248 | if (!ab) 1249 | return; 1250 | 1251 | kfree_skb(ab->skb); 1252 | spin_lock_irqsave(&audit_freelist_lock, flags); 1253 | if (audit_freelist_count > AUDIT_MAXFREE) 1254 | kfree(ab); 1255 | else { 1256 | audit_freelist_count++; 1257 | list_add(&ab->list, &audit_freelist); 1258 | } 1259 | spin_unlock_irqrestore(&audit_freelist_lock, flags); 1260 | } 1261 | 1262 | static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx, 1263 | gfp_t gfp_mask, int type) 1264 | { 1265 | unsigned long flags; 1266 | struct audit_buffer *ab = NULL; 1267 | struct nlmsghdr *nlh; 1268 | 1269 | spin_lock_irqsave(&audit_freelist_lock, flags); 1270 | if (!list_empty(&audit_freelist)) { 1271 | ab = list_entry(audit_freelist.next, 1272 | struct audit_buffer, list); 1273 | list_del(&ab->list); 1274 | --audit_freelist_count; 1275 | } 1276 | spin_unlock_irqrestore(&audit_freelist_lock, flags); 1277 | 1278 | if (!ab) { 1279 | ab = kmalloc(sizeof(*ab), gfp_mask); 1280 | if (!ab) 1281 | goto err; 1282 | } 1283 | 1284 | ab->ctx = ctx; 1285 | ab->gfp_mask = gfp_mask; 1286 | 1287 | ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask); 1288 | if (!ab->skb) 1289 | goto err; 1290 | 1291 | nlh = nlmsg_put(ab->skb, 0, 0, type, 0, 0); 1292 | if (!nlh) 1293 | goto out_kfree_skb; 1294 | 1295 | return ab; 1296 | 1297 | out_kfree_skb: 1298 | kfree_skb(ab->skb); 1299 | ab->skb = NULL; 1300 | err: 1301 | audit_buffer_free(ab); 1302 | return NULL; 1303 | } 1304 | 1305 | /** 1306 | * audit_serial - compute a serial number for the audit record 1307 | * 1308 | * Compute a serial number for the audit record. Audit records are 1309 | * written to user-space as soon as they are generated, so a complete 1310 | * audit record may be written in several pieces. The timestamp of the 1311 | * record and this serial number are used by the user-space tools to 1312 | * determine which pieces belong to the same audit record. The 1313 | * (timestamp,serial) tuple is unique for each syscall and is live from 1314 | * syscall entry to syscall exit. 1315 | * 1316 | * NOTE: Another possibility is to store the formatted records off the 1317 | * audit context (for those records that have a context), and emit them 1318 | * all at syscall exit. However, this could delay the reporting of 1319 | * significant errors until syscall exit (or never, if the system 1320 | * halts). 1321 | */ 1322 | unsigned int audit_serial(void) 1323 | { 1324 | static atomic_t serial = ATOMIC_INIT(0); 1325 | 1326 | return atomic_add_return(1, &serial); 1327 | } 1328 | 1329 | static inline void audit_get_stamp(struct audit_context *ctx, 1330 | struct timespec *t, unsigned int *serial) 1331 | { 1332 | if (!ctx || !auditsc_get_stamp(ctx, t, serial)) { 1333 | *t = CURRENT_TIME; 1334 | *serial = audit_serial(); 1335 | } 1336 | } 1337 | 1338 | /* 1339 | * Wait for auditd to drain the queue a little 1340 | */ 1341 | static long wait_for_auditd(long sleep_time) 1342 | { 1343 | DECLARE_WAITQUEUE(wait, current); 1344 | set_current_state(TASK_UNINTERRUPTIBLE); 1345 | add_wait_queue_exclusive(&audit_backlog_wait, &wait); 1346 | 1347 | if (audit_backlog_limit && 1348 | skb_queue_len(&audit_skb_queue) > audit_backlog_limit) 1349 | sleep_time = schedule_timeout(sleep_time); 1350 | 1351 | __set_current_state(TASK_RUNNING); 1352 | remove_wait_queue(&audit_backlog_wait, &wait); 1353 | 1354 | return sleep_time; 1355 | } 1356 | 1357 | /** 1358 | * audit_log_start - obtain an audit buffer 1359 | * @ctx: audit_context (may be NULL) 1360 | * @gfp_mask: type of allocation 1361 | * @type: audit message type 1362 | * 1363 | * Returns audit_buffer pointer on success or NULL on error. 1364 | * 1365 | * Obtain an audit buffer. This routine does locking to obtain the 1366 | * audit buffer, but then no locking is required for calls to 1367 | * audit_log_*format. If the task (ctx) is a task that is currently in a 1368 | * syscall, then the syscall is marked as auditable and an audit record 1369 | * will be written at syscall exit. If there is no associated task, then 1370 | * task context (ctx) should be NULL. 1371 | */ 1372 | struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask, 1373 | int type) 1374 | { 1375 | struct audit_buffer *ab = NULL; 1376 | struct timespec t; 1377 | unsigned int uninitialized_var(serial); 1378 | int reserve = 5; /* Allow atomic callers to go up to five 1379 | entries over the normal backlog limit */ 1380 | unsigned long timeout_start = jiffies; 1381 | 1382 | if (audit_initialized != AUDIT_INITIALIZED) 1383 | return NULL; 1384 | 1385 | if (unlikely(audit_filter_type(type))) 1386 | return NULL; 1387 | 1388 | if (gfp_mask & __GFP_DIRECT_RECLAIM) { 1389 | if (audit_pid && audit_pid == current->tgid) 1390 | gfp_mask &= ~__GFP_DIRECT_RECLAIM; 1391 | else 1392 | reserve = 0; 1393 | } 1394 | 1395 | while (audit_backlog_limit 1396 | && skb_queue_len(&audit_skb_queue) > audit_backlog_limit + reserve) { 1397 | if (gfp_mask & __GFP_DIRECT_RECLAIM && audit_backlog_wait_time) { 1398 | long sleep_time; 1399 | 1400 | sleep_time = timeout_start + audit_backlog_wait_time - jiffies; 1401 | if (sleep_time > 0) { 1402 | sleep_time = wait_for_auditd(sleep_time); 1403 | if (sleep_time > 0) 1404 | continue; 1405 | } 1406 | } 1407 | if (audit_rate_check() && printk_ratelimit()) 1408 | pr_warn("audit_backlog=%d > audit_backlog_limit=%d\n", 1409 | skb_queue_len(&audit_skb_queue), 1410 | audit_backlog_limit); 1411 | audit_log_lost("backlog limit exceeded"); 1412 | audit_backlog_wait_time = 0; 1413 | wake_up(&audit_backlog_wait); 1414 | return NULL; 1415 | } 1416 | 1417 | if (!reserve && !audit_backlog_wait_time) 1418 | audit_backlog_wait_time = audit_backlog_wait_time_master; 1419 | 1420 | ab = audit_buffer_alloc(ctx, gfp_mask, type); 1421 | if (!ab) { 1422 | audit_log_lost("out of memory in audit_log_start"); 1423 | return NULL; 1424 | } 1425 | 1426 | audit_get_stamp(ab->ctx, &t, &serial); 1427 | 1428 | audit_log_format(ab, "audit(%lu.%03lu:%u): ", 1429 | t.tv_sec, t.tv_nsec/1000000, serial); 1430 | return ab; 1431 | } 1432 | 1433 | /** 1434 | * audit_expand - expand skb in the audit buffer 1435 | * @ab: audit_buffer 1436 | * @extra: space to add at tail of the skb 1437 | * 1438 | * Returns 0 (no space) on failed expansion, or available space if 1439 | * successful. 1440 | */ 1441 | static inline int audit_expand(struct audit_buffer *ab, int extra) 1442 | { 1443 | struct sk_buff *skb = ab->skb; 1444 | int oldtail = skb_tailroom(skb); 1445 | int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask); 1446 | int newtail = skb_tailroom(skb); 1447 | 1448 | if (ret < 0) { 1449 | audit_log_lost("out of memory in audit_expand"); 1450 | return 0; 1451 | } 1452 | 1453 | skb->truesize += newtail - oldtail; 1454 | return newtail; 1455 | } 1456 | 1457 | /* 1458 | * Format an audit message into the audit buffer. If there isn't enough 1459 | * room in the audit buffer, more room will be allocated and vsnprint 1460 | * will be called a second time. Currently, we assume that a printk 1461 | * can't format message larger than 1024 bytes, so we don't either. 1462 | */ 1463 | static void audit_log_vformat(struct audit_buffer *ab, const char *fmt, 1464 | va_list args) 1465 | { 1466 | int len, avail; 1467 | struct sk_buff *skb; 1468 | va_list args2; 1469 | 1470 | if (!ab) 1471 | return; 1472 | 1473 | BUG_ON(!ab->skb); 1474 | skb = ab->skb; 1475 | avail = skb_tailroom(skb); 1476 | if (avail == 0) { 1477 | avail = audit_expand(ab, AUDIT_BUFSIZ); 1478 | if (!avail) 1479 | goto out; 1480 | } 1481 | va_copy(args2, args); 1482 | len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args); 1483 | if (len >= avail) { 1484 | /* The printk buffer is 1024 bytes long, so if we get 1485 | * here and AUDIT_BUFSIZ is at least 1024, then we can 1486 | * log everything that printk could have logged. */ 1487 | avail = audit_expand(ab, 1488 | max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail)); 1489 | if (!avail) 1490 | goto out_va_end; 1491 | len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2); 1492 | } 1493 | if (len > 0) 1494 | skb_put(skb, len); 1495 | out_va_end: 1496 | va_end(args2); 1497 | out: 1498 | return; 1499 | } 1500 | 1501 | /** 1502 | * audit_log_format - format a message into the audit buffer. 1503 | * @ab: audit_buffer 1504 | * @fmt: format string 1505 | * @...: optional parameters matching @fmt string 1506 | * 1507 | * All the work is done in audit_log_vformat. 1508 | */ 1509 | void audit_log_format(struct audit_buffer *ab, const char *fmt, ...) 1510 | { 1511 | va_list args; 1512 | 1513 | if (!ab) 1514 | return; 1515 | va_start(args, fmt); 1516 | audit_log_vformat(ab, fmt, args); 1517 | va_end(args); 1518 | } 1519 | 1520 | /** 1521 | * audit_log_hex - convert a buffer to hex and append it to the audit skb 1522 | * @ab: the audit_buffer 1523 | * @buf: buffer to convert to hex 1524 | * @len: length of @buf to be converted 1525 | * 1526 | * No return value; failure to expand is silently ignored. 1527 | * 1528 | * This function will take the passed buf and convert it into a string of 1529 | * ascii hex digits. The new string is placed onto the skb. 1530 | */ 1531 | void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf, 1532 | size_t len) 1533 | { 1534 | int i, avail, new_len; 1535 | unsigned char *ptr; 1536 | struct sk_buff *skb; 1537 | 1538 | if (!ab) 1539 | return; 1540 | 1541 | BUG_ON(!ab->skb); 1542 | skb = ab->skb; 1543 | avail = skb_tailroom(skb); 1544 | new_len = len<<1; 1545 | if (new_len >= avail) { 1546 | /* Round the buffer request up to the next multiple */ 1547 | new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1); 1548 | avail = audit_expand(ab, new_len); 1549 | if (!avail) 1550 | return; 1551 | } 1552 | 1553 | ptr = skb_tail_pointer(skb); 1554 | for (i = 0; i < len; i++) 1555 | ptr = hex_byte_pack_upper(ptr, buf[i]); 1556 | *ptr = 0; 1557 | skb_put(skb, len << 1); /* new string is twice the old string */ 1558 | } 1559 | 1560 | /* 1561 | * Format a string of no more than slen characters into the audit buffer, 1562 | * enclosed in quote marks. 1563 | */ 1564 | void audit_log_n_string(struct audit_buffer *ab, const char *string, 1565 | size_t slen) 1566 | { 1567 | int avail, new_len; 1568 | unsigned char *ptr; 1569 | struct sk_buff *skb; 1570 | 1571 | if (!ab) 1572 | return; 1573 | 1574 | BUG_ON(!ab->skb); 1575 | skb = ab->skb; 1576 | avail = skb_tailroom(skb); 1577 | new_len = slen + 3; /* enclosing quotes + null terminator */ 1578 | if (new_len > avail) { 1579 | avail = audit_expand(ab, new_len); 1580 | if (!avail) 1581 | return; 1582 | } 1583 | ptr = skb_tail_pointer(skb); 1584 | *ptr++ = '"'; 1585 | memcpy(ptr, string, slen); 1586 | ptr += slen; 1587 | *ptr++ = '"'; 1588 | *ptr = 0; 1589 | skb_put(skb, slen + 2); /* don't include null terminator */ 1590 | } 1591 | 1592 | /** 1593 | * audit_string_contains_control - does a string need to be logged in hex 1594 | * @string: string to be checked 1595 | * @len: max length of the string to check 1596 | */ 1597 | bool audit_string_contains_control(const char *string, size_t len) 1598 | { 1599 | const unsigned char *p; 1600 | for (p = string; p < (const unsigned char *)string + len; p++) { 1601 | if (*p == '"' || *p < 0x21 || *p > 0x7e) 1602 | return true; 1603 | } 1604 | return false; 1605 | } 1606 | 1607 | /** 1608 | * audit_log_n_untrustedstring - log a string that may contain random characters 1609 | * @ab: audit_buffer 1610 | * @len: length of string (not including trailing null) 1611 | * @string: string to be logged 1612 | * 1613 | * This code will escape a string that is passed to it if the string 1614 | * contains a control character, unprintable character, double quote mark, 1615 | * or a space. Unescaped strings will start and end with a double quote mark. 1616 | * Strings that are escaped are printed in hex (2 digits per char). 1617 | * 1618 | * The caller specifies the number of characters in the string to log, which may 1619 | * or may not be the entire string. 1620 | */ 1621 | void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string, 1622 | size_t len) 1623 | { 1624 | if (audit_string_contains_control(string, len)) 1625 | audit_log_n_hex(ab, string, len); 1626 | else 1627 | audit_log_n_string(ab, string, len); 1628 | } 1629 | 1630 | /** 1631 | * audit_log_untrustedstring - log a string that may contain random characters 1632 | * @ab: audit_buffer 1633 | * @string: string to be logged 1634 | * 1635 | * Same as audit_log_n_untrustedstring(), except that strlen is used to 1636 | * determine string length. 1637 | */ 1638 | void audit_log_untrustedstring(struct audit_buffer *ab, const char *string) 1639 | { 1640 | audit_log_n_untrustedstring(ab, string, strlen(string)); 1641 | } 1642 | 1643 | /* This is a helper-function to print the escaped d_path */ 1644 | void audit_log_d_path(struct audit_buffer *ab, const char *prefix, 1645 | const struct path *path) 1646 | { 1647 | char *p, *pathname; 1648 | 1649 | if (prefix) 1650 | audit_log_format(ab, "%s", prefix); 1651 | 1652 | /* We will allow 11 spaces for ' (deleted)' to be appended */ 1653 | pathname = kmalloc(PATH_MAX+11, ab->gfp_mask); 1654 | if (!pathname) { 1655 | audit_log_string(ab, ""); 1656 | return; 1657 | } 1658 | p = d_path(path, pathname, PATH_MAX+11); 1659 | if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */ 1660 | /* FIXME: can we save some information here? */ 1661 | audit_log_string(ab, ""); 1662 | } else 1663 | audit_log_untrustedstring(ab, p); 1664 | kfree(pathname); 1665 | } 1666 | 1667 | void audit_log_session_info(struct audit_buffer *ab) 1668 | { 1669 | unsigned int sessionid = audit_get_sessionid(current); 1670 | uid_t auid = from_kuid(&init_user_ns, audit_get_loginuid(current)); 1671 | 1672 | audit_log_format(ab, " auid=%u ses=%u", auid, sessionid); 1673 | } 1674 | 1675 | void audit_log_key(struct audit_buffer *ab, char *key) 1676 | { 1677 | audit_log_format(ab, " key="); 1678 | if (key) 1679 | audit_log_untrustedstring(ab, key); 1680 | else 1681 | audit_log_format(ab, "(null)"); 1682 | } 1683 | 1684 | void audit_log_cap(struct audit_buffer *ab, char *prefix, kernel_cap_t *cap) 1685 | { 1686 | int i; 1687 | 1688 | audit_log_format(ab, " %s=", prefix); 1689 | CAP_FOR_EACH_U32(i) { 1690 | audit_log_format(ab, "%08x", 1691 | cap->cap[CAP_LAST_U32 - i]); 1692 | } 1693 | } 1694 | 1695 | static void audit_log_fcaps(struct audit_buffer *ab, struct audit_names *name) 1696 | { 1697 | kernel_cap_t *perm = &name->fcap.permitted; 1698 | kernel_cap_t *inh = &name->fcap.inheritable; 1699 | int log = 0; 1700 | 1701 | if (!cap_isclear(*perm)) { 1702 | audit_log_cap(ab, "cap_fp", perm); 1703 | log = 1; 1704 | } 1705 | if (!cap_isclear(*inh)) { 1706 | audit_log_cap(ab, "cap_fi", inh); 1707 | log = 1; 1708 | } 1709 | 1710 | if (log) 1711 | audit_log_format(ab, " cap_fe=%d cap_fver=%x", 1712 | name->fcap.fE, name->fcap_ver); 1713 | } 1714 | 1715 | static inline int audit_copy_fcaps(struct audit_names *name, 1716 | const struct dentry *dentry) 1717 | { 1718 | struct cpu_vfs_cap_data caps; 1719 | int rc; 1720 | 1721 | if (!dentry) 1722 | return 0; 1723 | 1724 | rc = get_vfs_caps_from_disk(dentry, &caps); 1725 | if (rc) 1726 | return rc; 1727 | 1728 | name->fcap.permitted = caps.permitted; 1729 | name->fcap.inheritable = caps.inheritable; 1730 | name->fcap.fE = !!(caps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE); 1731 | name->fcap_ver = (caps.magic_etc & VFS_CAP_REVISION_MASK) >> 1732 | VFS_CAP_REVISION_SHIFT; 1733 | 1734 | return 0; 1735 | } 1736 | 1737 | /* Copy inode data into an audit_names. */ 1738 | void audit_copy_inode(struct audit_names *name, const struct dentry *dentry, 1739 | struct inode *inode) 1740 | { 1741 | name->ino = inode->i_ino; 1742 | name->dev = inode->i_sb->s_dev; 1743 | name->mode = inode->i_mode; 1744 | name->uid = inode->i_uid; 1745 | name->gid = inode->i_gid; 1746 | name->rdev = inode->i_rdev; 1747 | security_inode_getsecid(inode, &name->osid); 1748 | audit_copy_fcaps(name, dentry); 1749 | } 1750 | 1751 | /** 1752 | * audit_log_name - produce AUDIT_PATH record from struct audit_names 1753 | * @context: audit_context for the task 1754 | * @n: audit_names structure with reportable details 1755 | * @path: optional path to report instead of audit_names->name 1756 | * @record_num: record number to report when handling a list of names 1757 | * @call_panic: optional pointer to int that will be updated if secid fails 1758 | */ 1759 | void audit_log_name(struct audit_context *context, struct audit_names *n, 1760 | struct path *path, int record_num, int *call_panic) 1761 | { 1762 | struct audit_buffer *ab; 1763 | ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH); 1764 | if (!ab) 1765 | return; 1766 | 1767 | audit_log_format(ab, "item=%d", record_num); 1768 | 1769 | if (path) 1770 | audit_log_d_path(ab, " name=", path); 1771 | else if (n->name) { 1772 | switch (n->name_len) { 1773 | case AUDIT_NAME_FULL: 1774 | /* log the full path */ 1775 | audit_log_format(ab, " name="); 1776 | audit_log_untrustedstring(ab, n->name->name); 1777 | break; 1778 | case 0: 1779 | /* name was specified as a relative path and the 1780 | * directory component is the cwd */ 1781 | audit_log_d_path(ab, " name=", &context->pwd); 1782 | break; 1783 | default: 1784 | /* log the name's directory component */ 1785 | audit_log_format(ab, " name="); 1786 | audit_log_n_untrustedstring(ab, n->name->name, 1787 | n->name_len); 1788 | } 1789 | } else 1790 | audit_log_format(ab, " name=(null)"); 1791 | 1792 | if (n->ino != AUDIT_INO_UNSET) 1793 | audit_log_format(ab, " inode=%lu" 1794 | " dev=%02x:%02x mode=%#ho" 1795 | " ouid=%u ogid=%u rdev=%02x:%02x", 1796 | n->ino, 1797 | MAJOR(n->dev), 1798 | MINOR(n->dev), 1799 | n->mode, 1800 | from_kuid(&init_user_ns, n->uid), 1801 | from_kgid(&init_user_ns, n->gid), 1802 | MAJOR(n->rdev), 1803 | MINOR(n->rdev)); 1804 | if (n->osid != 0) { 1805 | char *ctx = NULL; 1806 | u32 len; 1807 | if (security_secid_to_secctx( 1808 | n->osid, &ctx, &len)) { 1809 | audit_log_format(ab, " osid=%u", n->osid); 1810 | if (call_panic) 1811 | *call_panic = 2; 1812 | } else { 1813 | audit_log_format(ab, " obj=%s", ctx); 1814 | security_release_secctx(ctx, len); 1815 | } 1816 | } 1817 | 1818 | /* log the audit_names record type */ 1819 | audit_log_format(ab, " nametype="); 1820 | switch(n->type) { 1821 | case AUDIT_TYPE_NORMAL: 1822 | audit_log_format(ab, "NORMAL"); 1823 | break; 1824 | case AUDIT_TYPE_PARENT: 1825 | audit_log_format(ab, "PARENT"); 1826 | break; 1827 | case AUDIT_TYPE_CHILD_DELETE: 1828 | audit_log_format(ab, "DELETE"); 1829 | break; 1830 | case AUDIT_TYPE_CHILD_CREATE: 1831 | audit_log_format(ab, "CREATE"); 1832 | break; 1833 | default: 1834 | audit_log_format(ab, "UNKNOWN"); 1835 | break; 1836 | } 1837 | 1838 | audit_log_fcaps(ab, n); 1839 | audit_log_end(ab); 1840 | } 1841 | 1842 | int audit_log_task_context(struct audit_buffer *ab) 1843 | { 1844 | char *ctx = NULL; 1845 | unsigned len; 1846 | int error; 1847 | u32 sid; 1848 | 1849 | security_task_getsecid(current, &sid); 1850 | if (!sid) 1851 | return 0; 1852 | 1853 | error = security_secid_to_secctx(sid, &ctx, &len); 1854 | if (error) { 1855 | if (error != -EINVAL) 1856 | goto error_path; 1857 | return 0; 1858 | } 1859 | 1860 | audit_log_format(ab, " subj=%s", ctx); 1861 | security_release_secctx(ctx, len); 1862 | return 0; 1863 | 1864 | error_path: 1865 | audit_panic("error in audit_log_task_context"); 1866 | return error; 1867 | } 1868 | EXPORT_SYMBOL(audit_log_task_context); 1869 | 1870 | void audit_log_d_path_exe(struct audit_buffer *ab, 1871 | struct mm_struct *mm) 1872 | { 1873 | struct file *exe_file; 1874 | 1875 | if (!mm) 1876 | goto out_null; 1877 | 1878 | exe_file = get_mm_exe_file(mm); 1879 | if (!exe_file) 1880 | goto out_null; 1881 | 1882 | audit_log_d_path(ab, " exe=", &exe_file->f_path); 1883 | fput(exe_file); 1884 | return; 1885 | out_null: 1886 | audit_log_format(ab, " exe=(null)"); 1887 | } 1888 | 1889 | void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk) 1890 | { 1891 | const struct cred *cred; 1892 | char comm[sizeof(tsk->comm)]; 1893 | char *tty; 1894 | 1895 | if (!ab) 1896 | return; 1897 | 1898 | /* tsk == current */ 1899 | cred = current_cred(); 1900 | 1901 | spin_lock_irq(&tsk->sighand->siglock); 1902 | if (tsk->signal && tsk->signal->tty && tsk->signal->tty->name) 1903 | tty = tsk->signal->tty->name; 1904 | else 1905 | tty = "(none)"; 1906 | spin_unlock_irq(&tsk->sighand->siglock); 1907 | 1908 | audit_log_format(ab, 1909 | " ppid=%d pid=%d auid=%u uid=%u gid=%u" 1910 | " euid=%u suid=%u fsuid=%u" 1911 | " egid=%u sgid=%u fsgid=%u tty=%s ses=%u", 1912 | task_ppid_nr(tsk), 1913 | task_pid_nr(tsk), 1914 | from_kuid(&init_user_ns, audit_get_loginuid(tsk)), 1915 | from_kuid(&init_user_ns, cred->uid), 1916 | from_kgid(&init_user_ns, cred->gid), 1917 | from_kuid(&init_user_ns, cred->euid), 1918 | from_kuid(&init_user_ns, cred->suid), 1919 | from_kuid(&init_user_ns, cred->fsuid), 1920 | from_kgid(&init_user_ns, cred->egid), 1921 | from_kgid(&init_user_ns, cred->sgid), 1922 | from_kgid(&init_user_ns, cred->fsgid), 1923 | tty, audit_get_sessionid(tsk)); 1924 | 1925 | audit_log_format(ab, " comm="); 1926 | audit_log_untrustedstring(ab, get_task_comm(comm, tsk)); 1927 | 1928 | audit_log_d_path_exe(ab, tsk->mm); 1929 | audit_log_task_context(ab); 1930 | } 1931 | EXPORT_SYMBOL(audit_log_task_info); 1932 | 1933 | /** 1934 | * audit_log_link_denied - report a link restriction denial 1935 | * @operation: specific link operation 1936 | * @link: the path that triggered the restriction 1937 | */ 1938 | void audit_log_link_denied(const char *operation, struct path *link) 1939 | { 1940 | struct audit_buffer *ab; 1941 | struct audit_names *name; 1942 | 1943 | name = kzalloc(sizeof(*name), GFP_NOFS); 1944 | if (!name) 1945 | return; 1946 | 1947 | /* Generate AUDIT_ANOM_LINK with subject, operation, outcome. */ 1948 | ab = audit_log_start(current->audit_context, GFP_KERNEL, 1949 | AUDIT_ANOM_LINK); 1950 | if (!ab) 1951 | goto out; 1952 | audit_log_format(ab, "op=%s", operation); 1953 | audit_log_task_info(ab, current); 1954 | audit_log_format(ab, " res=0"); 1955 | audit_log_end(ab); 1956 | 1957 | /* Generate AUDIT_PATH record with object. */ 1958 | name->type = AUDIT_TYPE_NORMAL; 1959 | audit_copy_inode(name, link->dentry, d_backing_inode(link->dentry)); 1960 | audit_log_name(current->audit_context, name, link, 0, NULL); 1961 | out: 1962 | kfree(name); 1963 | } 1964 | 1965 | /** 1966 | * audit_log_end - end one audit record 1967 | * @ab: the audit_buffer 1968 | * 1969 | * netlink_unicast() cannot be called inside an irq context because it blocks 1970 | * (last arg, flags, is not set to MSG_DONTWAIT), so the audit buffer is placed 1971 | * on a queue and a tasklet is scheduled to remove them from the queue outside 1972 | * the irq context. May be called in any context. 1973 | */ 1974 | void audit_log_end(struct audit_buffer *ab) 1975 | { 1976 | if (!ab) 1977 | return; 1978 | if (!audit_rate_check()) { 1979 | audit_log_lost("rate limit exceeded"); 1980 | } else { 1981 | struct nlmsghdr *nlh = nlmsg_hdr(ab->skb); 1982 | 1983 | nlh->nlmsg_len = ab->skb->len; 1984 | kauditd_send_multicast_skb(ab->skb, ab->gfp_mask); 1985 | 1986 | /* 1987 | * The original kaudit unicast socket sends up messages with 1988 | * nlmsg_len set to the payload length rather than the entire 1989 | * message length. This breaks the standard set by netlink. 1990 | * The existing auditd daemon assumes this breakage. Fixing 1991 | * this would require co-ordinating a change in the established 1992 | * protocol between the kaudit kernel subsystem and the auditd 1993 | * userspace code. 1994 | */ 1995 | nlh->nlmsg_len -= NLMSG_HDRLEN; 1996 | 1997 | if (audit_pid) { 1998 | skb_queue_tail(&audit_skb_queue, ab->skb); 1999 | wake_up_interruptible(&kauditd_wait); 2000 | } else { 2001 | audit_printk_skb(ab->skb); 2002 | } 2003 | ab->skb = NULL; 2004 | } 2005 | audit_buffer_free(ab); 2006 | } 2007 | 2008 | /** 2009 | * audit_log - Log an audit record 2010 | * @ctx: audit context 2011 | * @gfp_mask: type of allocation 2012 | * @type: audit message type 2013 | * @fmt: format string to use 2014 | * @...: variable parameters matching the format string 2015 | * 2016 | * This is a convenience function that calls audit_log_start, 2017 | * audit_log_vformat, and audit_log_end. It may be called 2018 | * in any context. 2019 | */ 2020 | void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type, 2021 | const char *fmt, ...) 2022 | { 2023 | struct audit_buffer *ab; 2024 | va_list args; 2025 | 2026 | ab = audit_log_start(ctx, gfp_mask, type); 2027 | if (ab) { 2028 | va_start(args, fmt); 2029 | audit_log_vformat(ab, fmt, args); 2030 | va_end(args); 2031 | audit_log_end(ab); 2032 | } 2033 | } 2034 | 2035 | #ifdef CONFIG_SECURITY 2036 | /** 2037 | * audit_log_secctx - Converts and logs SELinux context 2038 | * @ab: audit_buffer 2039 | * @secid: security number 2040 | * 2041 | * This is a helper function that calls security_secid_to_secctx to convert 2042 | * secid to secctx and then adds the (converted) SELinux context to the audit 2043 | * log by calling audit_log_format, thus also preventing leak of internal secid 2044 | * to userspace. If secid cannot be converted audit_panic is called. 2045 | */ 2046 | void audit_log_secctx(struct audit_buffer *ab, u32 secid) 2047 | { 2048 | u32 len; 2049 | char *secctx; 2050 | 2051 | if (security_secid_to_secctx(secid, &secctx, &len)) { 2052 | audit_panic("Cannot convert secid to context"); 2053 | } else { 2054 | audit_log_format(ab, " obj=%s", secctx); 2055 | security_release_secctx(secctx, len); 2056 | } 2057 | } 2058 | EXPORT_SYMBOL(audit_log_secctx); 2059 | #endif 2060 | 2061 | EXPORT_SYMBOL(audit_log_start); 2062 | EXPORT_SYMBOL(audit_log_end); 2063 | EXPORT_SYMBOL(audit_log_format); 2064 | EXPORT_SYMBOL(audit_log); 2065 | --------------------------------------------------------------------------------