repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/README.md
# Note This code is from [PRBonn/semantic-kitti-api](https://github.com/PRBonn/semantic-kitti-api). # API for SemanticKITTI This repository contains helper scripts to open, visualize, process, and evaluate results for point clouds and labels from the SemanticKITTI dataset. - Link to original [KITTI Odometry Benchmark](http://www.cvlibs.net/datasets/kitti/eval_odometry.php) Dataset - Link to [SemanticKITTI dataset](http://semantic-kitti.org/). - Link to SemanticKITTI benchmark [competition](http://semantic-kitti.org/tasks.html). - Link to SemanticKITTI MOS benchmark [competition](http://bit.ly/mos-benchmark) (may be deleted after adding MOS to SemanticKITTI website). --- ##### Example of 3D pointcloud from sequence 13: <img src="https://image.ibb.co/kyhCrV/scan1.png" width="1000"> --- ##### Example of 2D spherical projection from sequence 13: <img src="https://image.ibb.co/hZtVdA/scan2.png" width="1000"> --- ##### Example of voxelized point clouds for semantic scene completion: <img src="https://user-images.githubusercontent.com/11506664/70214770-4d43ff80-173c-11ea-940d-3950d8f24eaf.png" width="1000"> --- ## Data organization The data is organized in the following format: ``` /kitti/dataset/ └── sequences/ β”œβ”€β”€ 00/ β”‚Β Β  β”œβ”€β”€ poses.txt β”‚ β”œβ”€β”€ image_2/ β”‚Β Β  β”œβ”€β”€ image_3/ β”‚Β Β  β”œβ”€β”€ labels/ β”‚ β”‚ β”œ 000000.label β”‚ β”‚ β”” 000001.label | β”œβ”€β”€ voxels/ | | β”œ 000000.bin | | β”œ 000000.label | | β”œ 000000.occluded | | β”œ 000000.invalid | | β”œ 000001.bin | | β”œ 000001.label | | β”œ 000001.occluded | | β”œ 000001.invalid β”‚Β Β  └── velodyne/ β”‚ β”œ 000000.bin β”‚ β”” 000001.bin β”œβ”€β”€ 01/ β”œβ”€β”€ 02/ . . . └── 21/ ``` - From [KITTI Odometry](http://www.cvlibs.net/datasets/kitti/eval_odometry.php): - `image_2` and `image_3` correspond to the rgb images for each sequence. - `velodyne` contains the pointclouds for each scan in each sequence. Each `.bin` scan is a list of float32 points in [x,y,z,remission] format. See [laserscan.py](auxiliary/laserscan.py) to see how the points are read. - From SemanticKITTI: - `labels` contains the labels for each scan in each sequence. Each `.label` file contains a uint32 label for each point in the corresponding `.bin` scan. See [laserscan.py](auxiliary/laserscan.py) to see how the labels are read. - `poses.txt` contain the manually looped-closed poses for each capture (in the camera frame) that were used in the annotation tools to aggregate all the point clouds. - `voxels` contains all information needed for the task of semantic scene completion. Each `.bin` file contains for each voxel if that voxel is occupied by laser measurements in a packed binary format. This is the input to the semantic scene completion task and it corresponds to the voxelization of a single LiDAR scan. Each`.label` file contains for each voxel of the completed scene a label in binary format. The label is a 16-bit unsigned integer (aka uint16_t) for each voxel. `.invalid` and `.occluded` contain information about the occlusion of voxel. Invalid voxels are voxels that are occluded from each view position and occluded voxels are occluded in the first view point. See also [SSCDataset.py](auxiliary/SSCDataset.py) for more information on loading the data. The main configuration file for the data is in `config/semantic-kitti.yaml`. In this file you will find: - `labels`: dictionary which maps numeric labels in `.label` file to a string class. Example: `10: "car"` - `color_map`: dictionary which maps numeric labels in `.label` file to a bgr color for visualization. Example `10: [245, 150, 100] # car, blue-ish` - `content`: dictionary with content of each class in labels, as a ratio to the number of total points in the dataset. This can be obtained by running the [./content.py](./content.py) script, and is used to calculate the weights for the cross entropy in all baseline methods (in order handle class imbalance). - `learning_map`: dictionary which maps each class label to its cross entropy equivalent, for learning. This is done to mask undesired classes, map different classes together, and because the cross entropy expects a value in [0, numclasses - 1]. We also provide [./remap_semantic_labels.py](./remap_semantic_labels.py), a script that uses this dictionary to put the label files in the cross entropy format, so that you can use the labels directly in your training pipeline. Examples: ```yaml 0 : 0 # "unlabeled" 1 : 0 # "outlier" to "unlabeled" -> gets ignored in training, with unlabeled 10: 1 # "car" 252: 1 # "moving-car" to "car" -> gets merged with static car class ``` - `learning_map_inv`: dictionary with inverse of the previous mapping, allows to map back the classes only to the interest ones (for saving pointclouds predictions in original label format). We also provide [./remap_semantic_labels.py](./remap_semantic_labels.py), a script that uses this dictionary to put the label files in the original format, when instantiated with the `--inverse` flag. - `learning_ignore`: dictionary that cointains for each cross entropy class if it will be ignored during training and evaluation or not. For example, class `unlabeled` gets ignored in both training and evaluation. - `split`: contains 3 lists, with the sequence numbers for training, validation, and evaluation. ## Dependencies for API: System dependencies ```sh $ sudo apt install python3-dev python3-pip python3-pyqt5.qtopengl # for visualization ``` Python dependencies ```sh $ sudo pip3 install -r requirements.txt ``` ## Scripts: **ALL OF THE SCRIPTS CAN BE INVOKED WITH THE --help (-h) FLAG, FOR EXTRA INFORMATION AND OPTIONS.** #### Visualization ##### Point Clouds To visualize the data, use the `visualize.py` script. It will open an interactive opengl visualization of the pointclouds along with a spherical projection of each scan into a 64 x 1024 image. ```sh $ ./visualize.py --sequence 00 --dataset /path/to/kitti/dataset/ ``` where: - `sequence` is the sequence to be accessed. - `dataset` is the path to the kitti dataset where the `sequences` directory is. Navigation: - `n` is next scan, - `b` is previous scan, - `esc` or `q` exits. In order to visualize your predictions instead, the `--predictions` option replaces visualization of the labels with the visualization of your predictions: ```sh $ ./visualize.py --sequence 00 --dataset /path/to/kitti/dataset/ --predictions /path/to/your/predictions ``` #### Voxel Grids for Semantic Scene Completion To visualize the data, use the `visualize_voxels.py` script. It will open an interactive opengl visualization of the voxel grids and options to visualize the provided voxelizations of the LiDAR data. ```sh $ ./visualize_voxels.py --sequence 00 --dataset /path/to/kitti/dataset/ ``` where: - `sequence` is the sequence to be accessed. - `dataset` is the path to the kitti dataset where the `sequences` directory is. Navigation: - `n` is next scan, - `b` is previous scan, - `esc` or `q` exits. Note: Holding the forward/backward buttons triggers the playback mode. #### LiDAR-based Moving Object Segmentation ([LiDAR-MOS](https://github.com/PRBonn/LiDAR-MOS)) To visualize the data, use the `visualize_mos.py` script. It will open an interactive opengl visualization of the voxel grids and options to visualize the provided voxelizations of the LiDAR data. ```sh $ ./visualize_mos.py --sequence 00 --dataset /path/to/kitti/dataset/ ``` where: - `sequence` is the sequence to be accessed. - `dataset` is the path to the kitti dataset where the `sequences` directory is. Navigation: - `n` is next scan, - `b` is previous scan, - `esc` or `q` exits. Note: Holding the forward/backward buttons triggers the playback mode. #### Evaluation To evaluate the predictions of a method, use the [evaluate_semantics.py](./evaluate_semantics.py) to evaluate semantic segmentation, [evaluate_completion.py](./evaluate_completion.py) to evaluate the semantic scene completion and [evaluate_panoptic.py](./evaluate_panoptic.py) to evaluate panoptic segmentation. **Important:** The labels and the predictions need to be in the original label format, which means that if a method learns the cross-entropy mapped classes, they need to be passed through the `learning_map_inv` dictionary to be sent to the original dataset format. This is to prevent changes in the dataset interest classes from affecting intermediate outputs of approaches, since the original labels will stay the same. For semantic segmentation, we provide the `remap_semantic_labels.py` script to make this shift before the training, and once again before the evaluation, selecting which are the interest classes in the configuration file. The data needs to be either: - In a separate directory with this format: ``` /method_predictions/ └── sequences β”œβ”€β”€ 00 β”‚Β Β  └── predictions β”‚ β”œ 000000.label β”‚ β”” 000001.label β”œβ”€β”€ 01 β”œβ”€β”€ 02 . . . └── 21 ``` And run: ```sh $ ./evaluate_semantics.py --dataset /path/to/kitti/dataset/ --predictions /path/to/method_predictions --split train/valid/test # depending of desired split to evaluate ``` or ```sh $ ./evaluate_completion.py --dataset /path/to/kitti/dataset/ --predictions /path/to/method_predictions --split train/valid/test # depending of desired split to evaluate ``` or ```sh $ ./evaluate_panoptic.py --dataset /path/to/kitti/dataset/ --predictions /path/to/method_predictions --split train/valid/test # depending of desired split to evaluate ``` or for moving object segmentation ```sh $ ./evaluate_mos.py --dataset /path/to/kitti/dataset/ --predictions /path/to/method_predictions --split train/valid/test # depending of desired split to evaluate ``` - In the same directory as the dataset ``` /kitti/dataset/ β”œβ”€β”€ poses └── sequences β”œβ”€β”€ 00 β”‚Β Β  β”œβ”€β”€ image_2 β”‚Β Β  β”œβ”€β”€ image_3 β”‚Β Β  β”œβ”€β”€ labels β”‚ β”‚ β”œ 000000.label β”‚ β”‚ β”” 000001.label β”‚ β”œβ”€β”€ predictions β”‚ β”‚ β”œ 000000.label β”‚ β”‚ β”” 000001.label β”‚Β Β  └── velodyne β”‚ β”œ 000000.bin β”‚ β”” 000001.bin β”œβ”€β”€ 01 β”œβ”€β”€ 02 . . . └── 21 ``` And run (which sets the predictions directory as the same directory as the dataset): ```sh $ ./evaluate_semantics.py --dataset /path/to/kitti/dataset/ --split train/valid/test # depending of desired split to evaluate ``` If instead, the IoU vs distance is wanted, the evaluation is performed in the same way, but with the [evaluate_semantics_by_distance.py](./evaluate_semantics_by_distance.py) script. This will analyze the IoU for a set of 5 distance ranges: `{(0m:10m), [10m:20m), [20m:30m), [30m:40m), (40m:50m)}`. #### Validation To ensure that your zip file is valid, we provide a small validation script [validate_submission.py](./validate_submission.py) that checks for the correct folder structure and consistent number of labels for each scan. The submission folder expects to get an zip file containing the following folder structure (as the separate case above) ``` sequences β”œβ”€β”€ description.txt (optional) β”œβ”€β”€ 11 β”‚Β Β  └── predictions β”‚ β”œ 000000.label β”‚ β”œ 000001.label β”‚ β”œ ... β”œβ”€β”€ 12 β”‚Β Β  └── predictions β”‚ β”œ 000000.label β”‚ β”œ 000001.label β”‚ β”œ ... β”œβ”€β”€ 13 . . . └── 21 ``` In summary, you only have to provide the label files containing your predictions for every point of the scan and this is also checked by our validation script. If you want to have more information on our maintained leaderboard (coming soon!), you (currently) have to provide an additional `description.txt` file containing information, which we currently cannot access via the API. ``` method name: method description: project url: publication url: bibtex: organization or affiliation: ``` Run: ```sh $ ./validate_submission.py --task {segmentation|completion|panoptic} /path/to/submission.zip /path/to/kitti/dataset ``` to check your `submission.zip`. ***Note:*** We don't check if the labels are valid, since invalid labels are simply ignored by the evaluation script. #### Statistics - [content.py](content.py) allows to evaluate the class content of the training set, in order to weigh the loss for training, handling imbalanced data. - [count.py](count.py) returns the scan count for each sequence in the data. #### Generation - [generate_sequential.py](generate_sequential.py) generates a sequence of scans using the manually looped closed poses used in our labeling tool, and stores them as individual point clouds. If, for example, we want to generate a dataset containing, for each point cloud, the aggregation of itself with the previous 4 scans, then: ```sh $ ./generate_sequential.py --dataset /path/to/kitti/dataset/ --sequence_length 5 --output /path/to/put/new/dataset ``` - [remap_semantic_labels.py](remap_semantic_labels.py) allows to remap the labels to and from the cross-entropy format, so that the labels can be used for training, and the predictions can be used for evaluation. This file uses the `learning_map` and `learning_map_inv` dictionaries from the config file to map the labels and predictions. ## Docker for API If not installing the requirements is preferred, then a [docker](https://docs.docker.com/install/linux/docker-ce/ubuntu/) container is provided to run the scripts. To build and run the container in an interactive session, which allows to run X11 apps (and GL), and copies this repo to the working directory, use ``` $ ./docker.sh /path/to/dataset ``` Where `/path/to/dataset` is the location of your semantic kitti dataset, and will be available inside the image in `~/data` or `/home/developer/data` inside the container for further usage with the api. This is done by creating a shared volume, so it can be any directory containing data that is to be used by the API scripts. ## Citation: If you use this dataset and/or this API in your work, please cite its [paper](https://arxiv.org/abs/1904.01416) ``` @inproceedings{behley2019iccv, author = {J. Behley and M. Garbade and A. Milioto and J. Quenzel and S. Behnke and C. Stachniss and J. Gall}, title = {{SemanticKITTI: A Dataset for Semantic Scene Understanding of LiDAR Sequences}}, booktitle = {Proc. of the IEEE/CVF International Conf.~on Computer Vision (ICCV)}, year = {2019} } ``` And the paper for the [original KITTI dataset](http://www.cvlibs.net/datasets/kitti/eval_odometry.php): ``` @inproceedings{geiger2012cvpr, author = {A. Geiger and P. Lenz and R. Urtasun}, title = {{Are we ready for Autonomous Driving? The KITTI Vision Benchmark Suite}}, booktitle = {Proc.~of the IEEE Conf.~on Computer Vision and Pattern Recognition (CVPR)}, pages = {3354--3361}, year = {2012}} ```
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/evaluate_semantics_by_distance.py
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import argparse import os import yaml import sys import numpy as np DISTANCES = [(1e-8, 10.0), (10.0, 20.0), (20.0, 30.0), (30.0, 40.0), (40.0, 50.0)] # possible splits splits = ["train", "valid", "test"] # possible backends backends = ["numpy", "torch"] if __name__ == '__main__': parser = argparse.ArgumentParser("./evaluate_semantics_by_distance.py") parser.add_argument( '--dataset', '-d', type=str, required=True, help='Dataset dir. No Default', ) parser.add_argument( '--predictions', '-p', type=str, required=None, help='Prediction dir. Same organization as dataset, but predictions in' 'each sequences "prediction" directory. No Default. If no option is set' ' we look for the labels in the same directory as dataset' ) parser.add_argument( '--split', '-s', type=str, required=False, default="valid", help='Split to evaluate on. One of ' + str(splits) + '. Defaults to %(default)s', ) parser.add_argument( '--backend', '-b', type=str, required=False, default="numpy", help='Backend for evaluation. One of ' + str(backends) + ' Defaults to %(default)s', ) parser.add_argument( '--datacfg', '-dc', type=str, required=False, default="config/semantic-kitti.yaml", help='Dataset config file. Defaults to %(default)s', ) parser.add_argument( '--limit', '-l', type=int, required=False, default=None, help='Limit to the first "--limit" points of each scan. Useful for' ' evaluating single scan from agregated pointcloud.' ' Defaults to %(default)s', ) parser.add_argument( '--codalab', dest='codalab', default=False, action='store_true', help='Exports "segmentation_scores_distance.txt" for codalab' 'Defaults to %(default)s', ) FLAGS, unparsed = parser.parse_known_args() # fill in real predictions dir if FLAGS.predictions is None: FLAGS.predictions = FLAGS.dataset # print summary of what we will do print("*" * 80) print("INTERFACE:") print("Data: ", FLAGS.dataset) print("Predictions: ", FLAGS.predictions) print("Backend: ", FLAGS.backend) print("Split: ", FLAGS.split) print("Config: ", FLAGS.datacfg) print("Limit: ", FLAGS.limit) print("Codalab: ", FLAGS.codalab) print("*" * 80) # assert split assert(FLAGS.split in splits) # assert backend assert(FLAGS.backend in backends) print("Opening data config file %s" % FLAGS.datacfg) DATA = yaml.safe_load(open(FLAGS.datacfg, 'r')) # get number of interest classes, and the label mappings class_strings = DATA["labels"] class_remap = DATA["learning_map"] class_inv_remap = DATA["learning_map_inv"] class_ignore = DATA["learning_ignore"] nr_classes = len(class_inv_remap) # make lookup table for mapping maxkey = max(class_remap.keys()) # +100 hack making lut bigger just in case there are unknown labels remap_lut = np.zeros((maxkey + 100), dtype=np.int32) remap_lut[list(class_remap.keys())] = list(class_remap.values()) # print(remap_lut) # create evaluator ignore = [] for cl, ign in class_ignore.items(): if ign: x_cl = int(cl) ignore.append(x_cl) print("Ignoring xentropy class ", x_cl, " in IoU evaluation") # create evaluator evaluators = [] for i in range(len(DISTANCES)): if FLAGS.backend == "torch": from auxiliary.torch_ioueval import iouEval evaluators.append(iouEval(nr_classes, ignore)) evaluators[i].reset() elif FLAGS.backend == "numpy": from auxiliary.np_ioueval import iouEval evaluators.append(iouEval(nr_classes, ignore)) evaluators[i].reset() else: print("Backend for evaluator should be one of ", str(backends)) quit() # get test set test_sequences = DATA["split"][FLAGS.split] # get scan paths scan_names = [] for sequence in test_sequences: sequence = '{0:02d}'.format(int(sequence)) label_paths = os.path.join(FLAGS.dataset, "sequences", str(sequence), "velodyne") # populate the label names seq_scan_names = [os.path.join(dp, f) for dp, dn, fn in os.walk( os.path.expanduser(label_paths)) for f in fn if ".bin" in f] seq_scan_names.sort() scan_names.extend(seq_scan_names) # print(scan_names) # get label paths label_names = [] for sequence in test_sequences: sequence = '{0:02d}'.format(int(sequence)) label_paths = os.path.join(FLAGS.dataset, "sequences", str(sequence), "labels") # populate the label names seq_label_names = [os.path.join(dp, f) for dp, dn, fn in os.walk( os.path.expanduser(label_paths)) for f in fn if ".label" in f] seq_label_names.sort() label_names.extend(seq_label_names) # print(label_names) # get predictions paths pred_names = [] for sequence in test_sequences: sequence = '{0:02d}'.format(int(sequence)) pred_paths = os.path.join(FLAGS.predictions, "sequences", sequence, "predictions") # populate the label names seq_pred_names = [os.path.join(dp, f) for dp, dn, fn in os.walk( os.path.expanduser(pred_paths)) for f in fn if ".label" in f] seq_pred_names.sort() pred_names.extend(seq_pred_names) # print(pred_names) # check that I have the same number of files print("scans", len(scan_names)) print("labels: ", len(label_names)) print("predictions: ", len(pred_names)) assert(len(label_names) == len(pred_names) and len(scan_names) == len(label_names)) # open each file, get the tensor, and make the iou comparison for scan_file, label_file, pred_file in zip(scan_names, label_names, pred_names): print("evaluating scan ", scan_file) # open scan scan = np.fromfile(scan_file, dtype=np.float32) scan = scan.reshape((-1, 4)) # reshape to matrix if FLAGS.limit is not None: scan = scan[:FLAGS.limit] # limit to desired length depth = np.linalg.norm(scan[:, :3], 2, axis=1) # get depth to filter by distance # open label label = np.fromfile(label_file, dtype=np.int32) label = label.reshape((-1)) # reshape to vector label = label & 0xFFFF # get lower half for semantics if FLAGS.limit is not None: label = label[:FLAGS.limit] # limit to desired length label = remap_lut[label] # remap to xentropy format # open prediction pred = np.fromfile(pred_file, dtype=np.int32) pred = pred.reshape((-1)) # reshape to vector pred = pred & 0xFFFF # get lower half for semantics if FLAGS.limit is not None: pred = pred[:FLAGS.limit] # limit to desired length pred = remap_lut[pred] # remap to xentropy format # evaluate for all distances for idx in range(len(DISTANCES)): # select by range lrange = DISTANCES[idx][0] hrange = DISTANCES[idx][1] mask = np.logical_and(depth > lrange, depth < hrange) # mask by distance # mask_depth = depth[mask] # print("mask range, ", mask_depth.max(), mask_depth.min()) mask_label = label[mask] mask_pred = pred[mask] # add single scan to evaluation evaluators[idx].addBatch(mask_pred, mask_label) # print for all ranges print("*" * 80) for idx in range(len(DISTANCES)): # when I am done, print the evaluation m_accuracy = evaluators[idx].getacc() m_jaccard, class_jaccard = evaluators[idx].getIoU() # print for spreadsheet sys.stdout.write('range {lrange}m to {hrange}m,'.format(lrange=DISTANCES[idx][0], hrange=DISTANCES[idx][1])) for i, jacc in enumerate(class_jaccard): if i not in ignore: sys.stdout.write('{jacc:.3f}'.format(jacc=jacc.item())) sys.stdout.write(",") sys.stdout.write('{jacc:.3f}'.format(jacc=m_jaccard.item())) sys.stdout.write(",") sys.stdout.write('{acc:.3f}'.format(acc=m_accuracy.item())) sys.stdout.write('\n') sys.stdout.flush() # if codalab is necessary, then do it if FLAGS.codalab: results = {} for idx in range(len(DISTANCES)): # make string for distance d_str = str(DISTANCES[idx][-1])+"m_" # get values for this distance range m_accuracy = evaluators[idx].getacc() m_jaccard, class_jaccard = evaluators[idx].getIoU() # put in dictionary results[d_str+"accuracy_mean"] = float(m_accuracy) results[d_str+"iou_mean"] = float(m_jaccard) for i, jacc in enumerate(class_jaccard): if i not in ignore: results[d_str+"iou_"+class_strings[class_inv_remap[i]]] = float(jacc) # save to file with open('segmentation_scores_distance.txt', 'w') as yaml_file: yaml.dump(results, yaml_file, default_flow_style=False)
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/content.py
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import argparse import os import yaml import numpy as np import collections from auxiliary.laserscan import SemLaserScan if __name__ == '__main__': parser = argparse.ArgumentParser("./content.py") parser.add_argument( '--dataset', '-d', type=str, required=True, help='Dataset to calculate content. No Default', ) parser.add_argument( '--config', '-c', type=str, required=False, default="config/semantic-kitti.yaml", help='Dataset config file. Defaults to %(default)s', ) FLAGS, unparsed = parser.parse_known_args() # print summary of what we will do print("*" * 80) print("INTERFACE:") print("Dataset", FLAGS.dataset) print("Config", FLAGS.config) print("*" * 80) # open config file try: print("Opening config file %s" % FLAGS.config) CFG = yaml.safe_load(open(FLAGS.config, 'r')) except Exception as e: print(e) print("Error opening yaml file.") quit() # get training sequences to calculate statistics sequences = CFG["split"]["train"] print("Analizing sequences", sequences) # create content accumulator accum = {} total = 0.0 for key, _ in CFG["labels"].items(): accum[key] = 0 # itearate over sequences for seq in sequences: seq_accum = {} seq_total = 0.0 for key, _ in CFG["labels"].items(): seq_accum[key] = 0 # make seq string print("*" * 80) seqstr = '{0:02d}'.format(int(seq)) print("parsing seq {}".format(seq)) # does sequence folder exist? scan_paths = os.path.join(FLAGS.dataset, "sequences", seqstr, "velodyne") if os.path.isdir(scan_paths): print("Sequence folder exists!") else: print("Sequence folder doesn't exist! Exiting...") quit() # populate the pointclouds scan_names = [os.path.join(dp, f) for dp, dn, fn in os.walk( os.path.expanduser(scan_paths)) for f in fn] scan_names.sort() # does sequence folder exist? label_paths = os.path.join(FLAGS.dataset, "sequences", seqstr, "labels") if os.path.isdir(label_paths): print("Labels folder exists!") else: print("Labels folder doesn't exist! Exiting...") quit() # populate the pointclouds label_names = [os.path.join(dp, f) for dp, dn, fn in os.walk( os.path.expanduser(label_paths)) for f in fn] label_names.sort() # check that there are same amount of labels and scans print(len(label_names)) print(len(scan_names)) assert(len(label_names) == len(scan_names)) # create a scan nclasses = len(CFG["labels"]) scan = SemLaserScan(nclasses, CFG["color_map"], project=False) for idx in range(len(scan_names)): # open scan print(label_names[idx]) scan.open_scan(scan_names[idx]) scan.open_label(label_names[idx]) # make histogram and accumulate count = np.bincount(scan.sem_label) seq_total += count.sum() for key, data in seq_accum.items(): if count.size > key: seq_accum[key] += count[key] # zero the count count[key] = 0 for i, c in enumerate(count): if c > 0: print("wrong label ", i, ", nr: ", c) seq_accum = collections.OrderedDict( sorted(seq_accum.items(), key=lambda t: t[0])) # print and send to total total += seq_total print("seq ", seqstr, "total", seq_total) for key, data in seq_accum.items(): accum[key] += data print(data) # print content to fill yaml file print("*" * 80) print("Content in training set") print(accum) accum = collections.OrderedDict(sorted(accum.items(), key=lambda t: t[0])) for key, data in accum.items(): print(" {}: {}".format(key, data / total))
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/remap_semantic_labels.py
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import argparse import os import yaml import numpy as np # possible splits splits = ["train", "valid", "test"] if __name__ == '__main__': parser = argparse.ArgumentParser("./remap_semantic_labels.py") parser.add_argument( '--dataset', '-d', type=str, required=False, default=None, help='Dataset dir. WARNING: This file remaps the labels in place, so the original labels will be lost. Cannot be used together with -predictions- flag.' ) parser.add_argument( '--predictions', '-p', type=str, required=False, default=None, help='Prediction dir. WARNING: This file remaps the predictions in place, so the original predictions will be lost. Cannot be used together with -dataset- flag.' ) parser.add_argument( '--split', '-s', type=str, required=False, default="valid", help='Split to evaluate on. One of ' + str(splits) + '. Defaults to %(default)s', ) parser.add_argument( '--datacfg', '-dc', type=str, required=False, default="config/semantic-kitti.yaml", help='Dataset config file. Defaults to %(default)s', ) parser.add_argument( '--inverse', dest='inverse', default=False, action='store_true', help='Map from xentropy to original, instead of original to xentropy. ' 'Defaults to %(default)s', ) FLAGS, unparsed = parser.parse_known_args() # print summary of what we will do print("*" * 80) print("INTERFACE:") print("Data: ", FLAGS.dataset) print("Predictions: ", FLAGS.predictions) print("Split: ", FLAGS.split) print("Config: ", FLAGS.datacfg) print("Inverse: ", FLAGS.inverse) print("*" * 80) # only predictions or dataset can be handled at once and one MUST be given (xor) assert((FLAGS.dataset is not None) != (FLAGS.predictions is not None)) # check name root_directory = "" label_directory = "" if(FLAGS.dataset is not None): root_directory = FLAGS.dataset label_directory = "labels" elif(FLAGS.predictions is not None): root_directory = FLAGS.predictions label_directory = "predictions" else: print("I don't even know how I got here") quit() # assert split assert(FLAGS.split in splits) print("Opening data config file %s" % FLAGS.datacfg) DATA = yaml.safe_load(open(FLAGS.datacfg, 'r')) # get number of interest classes, and the label mappings if FLAGS.inverse: print("Mapping xentropy to original labels") remapdict = DATA["learning_map_inv"] else: remapdict = DATA["learning_map"] nr_classes = len(remapdict) # make lookup table for mapping maxkey = max(remapdict.keys()) # +100 hack making lut bigger just in case there are unknown labels remap_lut = np.zeros((maxkey + 100), dtype=np.int32) remap_lut[list(remapdict.keys())] = list(remapdict.values()) # print(remap_lut) # get wanted set sequence = [] sequence.extend(DATA["split"][FLAGS.split]) # get label paths label_names = [] for sequence in sequence: sequence = '{0:02d}'.format(int(sequence)) label_paths = os.path.join(root_directory, "sequences", sequence, label_directory) # populate the label names seq_label_names = [os.path.join(dp, f) for dp, dn, fn in os.walk( os.path.expanduser(label_paths)) for f in fn if ".label" in f] seq_label_names.sort() label_names.extend(seq_label_names) # print(label_names) # open each file, get the tensor, and remap only the lower half (semantics) for label_file in label_names: # open label print(label_file) label = np.fromfile(label_file, dtype=np.uint32) label = label.reshape((-1)) upper_half = label >> 16 # get upper half for instances lower_half = label & 0xFFFF # get lower half for semantics lower_half = remap_lut[lower_half] # do the remapping of semantics label = (upper_half << 16) + lower_half # reconstruct full label label = label.astype(np.uint32) label.tofile(label_file)
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/evaluate_completion.py
#!/usr/bin/python3 import argparse import numpy as np import scipy.io as sio import yaml import os import time epsilon = np.finfo(np.float32).eps def get_eval_mask(labels, invalid_voxels): """ Ignore labels set to 255 and invalid voxels (the ones never hit by a laser ray, probed using ray tracing) :param labels: input ground truth voxels :param invalid_voxels: voxels ignored during evaluation since the lie beyond the scene that was captured by the laser :return: boolean mask to subsample the voxels to evaluate """ masks = np.ones_like(labels, dtype=np.bool) masks[labels == 255] = False masks[invalid_voxels == 1] = False return masks def unpack(compressed): ''' given a bit encoded voxel grid, make a normal voxel grid out of it. ''' uncompressed = np.zeros(compressed.shape[0] * 8, dtype=np.uint8) uncompressed[::8] = compressed[:] >> 7 & 1 uncompressed[1::8] = compressed[:] >> 6 & 1 uncompressed[2::8] = compressed[:] >> 5 & 1 uncompressed[3::8] = compressed[:] >> 4 & 1 uncompressed[4::8] = compressed[:] >> 3 & 1 uncompressed[5::8] = compressed[:] >> 2 & 1 uncompressed[6::8] = compressed[:] >> 1 & 1 uncompressed[7::8] = compressed[:] & 1 return uncompressed def load_gt_volume(filename): basename = os.path.splitext(filename)[0] labels = np.fromfile(filename, dtype=np.uint16) invalid_voxels = unpack(np.fromfile(basename + ".invalid", dtype=np.uint8)) return labels, invalid_voxels def load_pred_volume(filename): labels = np.fromfile(filename, dtype=np.uint16) return labels # possible splits splits = ["train", "valid", "test"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="SSC semantic-kitti") parser.add_argument( '--dataset', '-d', type=str, required=True, help='Dataset dir. No Default', ) parser.add_argument( '--predictions', '-p', type=str, required=False, help='Prediction dir. Same organization as dataset, but predictions in' 'each sequences "prediction" directory.' ) parser.add_argument( '--datacfg', '-dc', type=str, required=False, default="config/semantic-kitti.yaml", help='Dataset config file. Defaults to %(default)s', ) parser.add_argument( '--split', '-s', type=str, required=False, choices=["train", "valid", "test"], default="valid", help='Split to evaluate on. One of ' + str(splits) + '. Defaults to %(default)s', ) parser.add_argument( '--output', dest='output', type=str, default=".", help='Exports "scores.txt" to given output directory for codalab' 'Defaults to %(default)s', ) args = parser.parse_args() print(" ========================== Arguments ========================== ") print("\n".join([" {}:\t{}".format(k,v) for (k,v) in vars(args).items()])) print(" =============================================================== \n") gt_data_root = args.dataset DATA = yaml.safe_load(open(args.datacfg, 'r')) # get number of interest classes, and the label mappings class_strings = DATA["labels"] class_remap = DATA["learning_map"] class_inv_remap = DATA["learning_map_inv"] class_ignore = DATA["learning_ignore"] n_classes = len(class_inv_remap) test_sequences = DATA["split"][args.split] # make lookup table for mapping maxkey = max(class_remap.keys()) # +100 hack making lut bigger just in case there are unknown labels remap_lut = np.zeros((maxkey + 100), dtype=np.int32) remap_lut[list(class_remap.keys())] = list(class_remap.values()) # in completion we have to distinguish empty and invalid voxels. # Important: For voxels 0 corresponds to "empty" and not "unlabeled". remap_lut[remap_lut == 0] = 255 # map 0 to 'invalid' remap_lut[0] = 0 # only 'empty' stays 'empty'. from auxiliary.np_ioueval import iouEval evaluator = iouEval(n_classes, []) # get files from ground truth and predictions. filenames_gt = [] filenames_pred = [] for seq in test_sequences: seq_dir_gt = os.path.join("sequences", '{0:02d}'.format(int(seq)), "voxels") seq_dir_pred = os.path.join("sequences", '{0:02d}'.format(int(seq)), "predictions") gt_file_list = [f for f in os.listdir(os.path.join(args.dataset, seq_dir_gt)) if f.endswith(".label")] filenames_gt.extend([os.path.join(seq_dir_gt, f) for f in gt_file_list]) filenames_pred.extend([os.path.join(seq_dir_pred, f) for f in gt_file_list]) missing_pred_files = False if args.predictions is None: prediction_dir = args.dataset else: prediction_dir = args.predictions # check that all prediction files exist for pred_file in filenames_pred: if not os.path.exists(os.path.join(prediction_dir, pred_file)): print("Expected to have {}, but file does not exist!".format(pred_file)) missing_pred_files = True if missing_pred_files: raise RuntimeError("Error: Missing prediction files! Aborting evaluation.") evaluation_pairs = list(zip(filenames_gt, filenames_pred)) print("Evaluating: ", end="", flush=True) progress = 10 for i, f in enumerate(evaluation_pairs): if 100.0 * i / len(evaluation_pairs) >= progress: print("{}% ".format(progress), end="", flush=True) progress = progress + 10 filename_gt = os.path.join(args.dataset, f[0]) filename_pred = os.path.join(prediction_dir, f[1]) pred = load_pred_volume(filename_pred) target, invalid_voxels = load_gt_volume(filename_gt) # Map labels "pred_labels" and "gt_labels" from semantic-kitti ID's to [0 : n_classes -1] pred = remap_lut[pred] target = remap_lut[target] masks = get_eval_mask(target, invalid_voxels) target = target[masks] pred = pred[masks] # add single scan to evaluation evaluator.addBatch(pred, target) print("Done \U0001F389.") print("\n ========================== RESULTS ========================== ") # when I am done, print the evaluation _, class_jaccard = evaluator.getIoU() m_jaccard = class_jaccard[1:].mean() print('Validation set:\nIoU avg {m_jaccard:.3f}'.format(m_jaccard=m_jaccard)) ignore = [0] # print also classwise for i, jacc in enumerate(class_jaccard): if i not in ignore: print('IoU class {i:} [{class_str:}] = {jacc:.3f}'.format( i=i, class_str=class_strings[class_inv_remap[i]], jacc=jacc)) # compute remaining metrics. conf = evaluator.get_confusion() precision = np.sum(conf[1:,1:]) / (np.sum(conf[1:,:]) + epsilon) recall = np.sum(conf[1:,1:]) / (np.sum(conf[:,1:]) + epsilon) acc_cmpltn = (np.sum(conf[1:, 1:])) / (np.sum(conf) - conf[0,0]) mIoU_ssc = m_jaccard print("Precision =\t" + str(np.round(precision * 100, 2)) + '\n' + "Recall =\t" + str(np.round(recall * 100, 2)) + '\n' + "IoU Cmpltn =\t" + str(np.round(acc_cmpltn * 100, 2)) + '\n' + "mIoU SSC =\t" + str(np.round(mIoU_ssc * 100, 2))) # write "scores.txt" with all information results = {} results["iou_completion"] = float(acc_cmpltn) results["iou_mean"] = float(mIoU_ssc) for i, jacc in enumerate(class_jaccard): if i not in ignore: results["iou_"+class_strings[class_inv_remap[i]]] = float(jacc) output_filename = os.path.join(args.output, 'scores.txt') with open(output_filename, 'w') as yaml_file: yaml.dump(results, yaml_file, default_flow_style=False)
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/visualize_voxels.py
#!/usr/bin/python3 import math import sys import os import time import argparse import glfw import OpenGL from OpenGL.GL.shaders import compileProgram, compileShader from OpenGL.GL import * import numpy as np import yaml import imgui from imgui.integrations.glfw import GlfwRenderer import auxiliary.glow as glow from auxiliary.camera import Camera OpenGL.ERROR_ON_COPY = True OpenGL.ERROR_CHECKING = True def glPerspective(fov, aspect, znear, zfar): # https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml # assert(znear > 0.0) M = np.zeros((4, 4)) # Copied from gluPerspective f = 1.0 / math.tan(0.5 * fov) M[0, 0] = f / aspect M[1, 1] = f M[2, 2] = (znear + zfar) / (znear - zfar) M[2, 3] = (2.0 * zfar * znear) / (znear - zfar) M[3, 2] = -1.0 return M def unpack(compressed): ''' given a bit encoded voxel grid, make a normal voxel grid out of it. ''' uncompressed = np.zeros(compressed.shape[0] * 8, dtype=np.uint8) uncompressed[::8] = compressed[:] >> 7 & 1 uncompressed[1::8] = compressed[:] >> 6 & 1 uncompressed[2::8] = compressed[:] >> 5 & 1 uncompressed[3::8] = compressed[:] >> 4 & 1 uncompressed[4::8] = compressed[:] >> 3 & 1 uncompressed[5::8] = compressed[:] >> 2 & 1 uncompressed[6::8] = compressed[:] >> 1 & 1 uncompressed[7::8] = compressed[:] & 1 return uncompressed class Window: def __init__(self): if not glfw.init(): raise RuntimeError("Unable to initialize glfw.") w_window, h_window = 800, 600 self.window = glfw.create_window(w_window, h_window, "Voxel Visualizer", None, None) if not self.window: glfw.terminate() raise RuntimeError("Unable to create window.") monitor = glfw.get_primary_monitor() mode = glfw.get_video_mode(monitor) w_mon, h_mon = mode.size # center window. glfw.set_window_pos(self.window, int(0.5 * w_mon - 0.5 * w_window), int(0.5 * h_mon - 0.5 * h_window)) # Make the window's context current glfw.make_context_current(self.window) glfw.set_framebuffer_size_callback(self.window, self.on_resize) # add mouse handlers. glfw.set_input_mode(self.window, glfw.STICKY_MOUSE_BUTTONS, glfw.TRUE) glfw.set_mouse_button_callback(self.window, self.on_mouse_btn) glfw.set_cursor_pos_callback(self.window, self.on_mouse_move) glfw.set_window_size_callback(self.window, self.on_resize) glfw.set_key_callback(self.window, self.keyboard_callback) glfw.set_char_callback(self.window, self.char_callback) glfw.set_scroll_callback(self.window, self.scroll_callback) self.voxel_dims = glow.ivec3(256, 256, 32) # read config file. CFG = yaml.safe_load(open("config/semantic-kitti.yaml", 'r')) color_dict = CFG["color_map"] self.label_colors = glow.GlTextureRectangle(1024, 1, internalFormat=GL_RGB, format=GL_RGB) cols = np.zeros((1024 * 3), dtype=np.uint8) for label_id, color in color_dict.items(): cols[3 * label_id + 0] = color[2] cols[3 * label_id + 1] = color[1] cols[3 * label_id + 2] = color[0] self.label_colors.assign(cols) self.initializeGL() # initialize imgui imgui.create_context() self.impl = GlfwRenderer(self.window, attach_callbacks=False) self.on_resize(self.window, w_window, h_window) self.data = [] self.isDrag = False self.buttonPressed = None self.cam = Camera() self.cam.lookAt(25.0, 25.0, 25.0, 0.0, 0.0, 0.0) self.currentTimestep = 0 self.sliderValue = 0 self.showLabels = True def initializeGL(self): """ initialize GL related stuff. """ self.num_instances = np.prod(self.voxel_dims) # see https://stackoverflow.com/questions/28375338/cube-using-single-gl-triangle-strip, but the normals are a problem. # verts = np.array([ # -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, # -1, 1, -1, -1, -1, 1, -1, 1, 1, -1 # ], # dtype=np.float32) # yapf: disable p1 = [1, 0, 0] p2 = [0, 0, 0] p3 = [1, 1, 0] p4 = [0, 1, 0] p5 = [1, 0, 1] p6 = [0, 0, 1] p7 = [0, 1, 1] p8 = [1, 1, 1] verts = np.array([ # first face p4, p3, p7, p3, p7, p8, # second face p7, p8, p5, p7, p6, p5, # third face p8, p5, p3, p5, p3, p1, # fourth face p3, p1, p4, p1, p4, p2, # fifth face p4, p2, p7, p2, p7, p6, # sixth face p6, p5, p2, p5, p2, p1 ], dtype=np.float32).reshape(-1) normals = np.array([[0, 1, 0] * 6, [0, 0, 1] * 6, [1, 0, 0] * 6, [0, 0, -1] * 6, [-1, 0, 0] * 6, [0, -1, 0] * 6 ], dtype=np.float32).reshape(-1) # yapf: enable glow.WARN_INVALID_UNIFORMS = True self.labels = np.array([], dtype=np.float32) self.cube_verts = glow.GlBuffer() self.cube_verts.assign(verts) self.cube_normals = glow.GlBuffer() self.cube_normals.assign(normals) self.label_vbo = glow.GlBuffer() glPointSize(5.0) self.vao = glGenVertexArrays(1) glBindVertexArray(self.vao) SIZEOF_FLOAT = 4 self.cube_verts.bind() glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * SIZEOF_FLOAT, GLvoidp(0)) glEnableVertexAttribArray(0) self.cube_verts.release() self.cube_normals.bind() glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * SIZEOF_FLOAT, GLvoidp(0)) glEnableVertexAttribArray(1) self.cube_normals.release() glEnableVertexAttribArray(2) self.label_vbo.bind() # Note: GL_UNSINGED_INT did not work as expected! I could not figure out what was wrong there! glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, SIZEOF_FLOAT, GLvoidp(0)) self.label_vbo.release() glVertexAttribDivisor(2, 1) glBindVertexArray(0) self.program = glow.GlProgram() self.program.attach(glow.GlShader.fromFile(GL_VERTEX_SHADER, "auxiliary/shaders/draw_voxels.vert")) self.program.attach(glow.GlShader.fromFile(GL_FRAGMENT_SHADER, "auxiliary/shaders/draw_voxels.frag")) self.program.link() self.prgDrawPose = glow.GlProgram() self.prgDrawPose.attach(glow.GlShader.fromFile(GL_VERTEX_SHADER, "auxiliary/shaders/empty.vert")) self.prgDrawPose.attach(glow.GlShader.fromFile(GL_GEOMETRY_SHADER, "auxiliary/shaders/draw_pose.geom")) self.prgDrawPose.attach(glow.GlShader.fromFile(GL_FRAGMENT_SHADER, "auxiliary/shaders/passthrough.frag")) self.prgDrawPose.link() self.prgTestUniform = glow.GlProgram() self.prgTestUniform.attach(glow.GlShader.fromFile(GL_VERTEX_SHADER, "auxiliary/shaders/check_uniforms.vert")) self.prgTestUniform.attach(glow.GlShader.fromFile(GL_FRAGMENT_SHADER, "auxiliary/shaders/passthrough.frag")) self.prgTestUniform.link() # general parameters glClearColor(1.0, 1.0, 1.0, 1.0) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) glEnable(GL_LINE_SMOOTH) # x = forward, y = left, z = up to x = right, y = up, z = backward self.conversion_ = np.array([0, -1, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 1], dtype=np.float32).reshape(4, 4) self.program.bind() self.program["voxel_size"] = 0.5 self.program["voxel_dims"] = self.voxel_dims self.program["label_colors"] = 0 self.program.release() self.vao_no_points = glGenVertexArrays(1) def open_directory(self, directory): """ open given sequences directory and get filenames of relevant files. """ self.subdirs = [subdir for subdir in ["voxels", "predictions"] if os.path.exists(os.path.join(directory, subdir))] if len(self.subdirs) == 0: raise RuntimeError("Neither 'voxels' nor 'predictions' found in " + directory) self.availableData = {} self.data = {} for subdir in self.subdirs: self.availableData[subdir] = [] self.data[subdir] = {} complete_path = os.path.join(directory, subdir) files = os.listdir(complete_path) data = sorted([os.path.join(complete_path, f) for f in files if f.endswith(".bin")]) if len(data) > 0: self.availableData[subdir].append("input") self.data[subdir]["input"] = data self.num_scans = len(data) data = sorted([os.path.join(complete_path, f) for f in files if f.endswith(".label")]) if len(data) > 0: self.availableData[subdir].append("labels") self.data[subdir]["labels"] = data self.num_scans = len(data) data = sorted([os.path.join(complete_path, f) for f in files if f.endswith(".invalid")]) if len(data) > 0: self.availableData[subdir].append("invalid") self.data[subdir]["invalid"] = data self.num_scans = len(data) data = sorted([os.path.join(complete_path, f) for f in files if f.endswith(".occluded")]) if len(data) > 0: self.availableData[subdir].append("occluded") self.data[subdir]["occluded"] = data self.num_scans = len(data) self.current_subdir = 0 self.current_data = self.availableData[self.subdirs[self.current_subdir]][0] self.currentTimestep = 0 self.sliderValue = 0 self.lastChange = None self.lastUpdate = time.time() self.button_backward_hold = False self.button_forward_hold = False # todo: modify based on available stuff. self.showLabels = (self.current_data == "labels") self.showInput = (self.current_data == "input") self.showInvalid = (self.current_data == "invalid") self.showOccluded = (self.current_data == "occludded") def setCurrentBufferData(self, data_name, t): # update buffer content with given data identified by data_name. subdir = self.subdirs[self.current_subdir] if len(self.data[subdir][data_name]) < t: return False # Note: uint with np.uint32 did not work as expected! (with instances and uint32 this causes problems!) if data_name == "labels": buffer_data = np.fromfile(self.data[subdir][data_name][t], dtype=np.uint16).astype(np.float32) else: buffer_data = unpack(np.fromfile(self.data[subdir][data_name][t], dtype=np.uint8)).astype(np.float32) self.label_vbo.assign(buffer_data) return True def on_resize(self, window, w, h): # set projection matrix fov = math.radians(45.0) aspect = w / h self.projection_ = glPerspective(fov, aspect, 0.1, 2000.0) self.impl.resize_callback(window, w, h) def on_mouse_btn(self, window, button, action, mods): x, y = glfw.get_cursor_pos(self.window) imgui.get_io().mouse_pos = (x, y) if imgui.get_io().want_capture_mouse: return if action == glfw.PRESS: self.buttonPressed = button self.isDrag = True self.cam.mousePressed(x, y, self.buttonPressed, None) else: self.buttonPressed = None self.isDrag = False self.cam.mouseReleased(x, y, self.buttonPressed, None) def on_mouse_move(self, window, x, y): if self.isDrag: self.cam.mouseMoved(x, y, self.buttonPressed, None) def keyboard_callback(self, window, key, scancode, action, mods): self.impl.keyboard_callback(window, key, scancode, action, mods) if not imgui.get_io().want_capture_keyboard: if key == glfw.KEY_B or key == glfw.KEY_LEFT: self.currentTimestep = self.sliderValue = max(0, self.currentTimestep - 1) if key == glfw.KEY_N or key == glfw.KEY_RIGHT: self.currentTimestep = self.sliderValue = min(self.num_scans - 1, self.currentTimestep + 1) if key == glfw.KEY_Q or key == glfw.KEY_ESCAPE: exit(0) def char_callback(self, window, char): self.impl.char_callback(window, char) def scroll_callback(self, window, x_offset, y_offset): self.impl.scroll_callback(window, x_offset, y_offset) def run(self): # Loop until the user closes the window while not glfw.window_should_close(self.window): # Poll for and process events glfw.poll_events() # build gui. self.impl.process_inputs() w, h = glfw.get_window_size(self.window) glViewport(0, 0, w, h) imgui.new_frame() timeline_height = 35 imgui.push_style_var(imgui.STYLE_WINDOW_ROUNDING, 0) imgui.push_style_var(imgui.STYLE_FRAME_ROUNDING, 0) imgui.set_next_window_position(0, h - timeline_height - 10) imgui.set_next_window_size(w, timeline_height) imgui.begin("Timeline", False, imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_SCROLLBAR) imgui.columns(1) imgui.same_line(0, 0) imgui.push_item_width(-50) changed, value = imgui.slider_int("", self.sliderValue, 0, self.num_scans - 1) if changed: self.sliderValue = value if self.sliderValue != self.currentTimestep: self.currentTimestep = self.sliderValue imgui.push_style_var(imgui.STYLE_FRAME_ROUNDING, 3) play_delay = 1 refresh_rate = 0.05 current_time = time.time() imgui.same_line(spacing=5) changed = imgui.button("<", 20) if self.currentTimestep > 0: # just a click if changed: self.currentTimestep = self.sliderValue = self.currentTimestep - 1 self.lastUpdate = current_time # button pressed. if imgui.is_item_active() and not self.button_backward_hold: self.hold_start = current_time self.button_backward_hold = True if not imgui.is_item_active() and self.button_backward_hold: self.button_backward_hold = False # start playback when button pressed long enough if self.button_backward_hold and ((current_time - self.hold_start) > play_delay): if (current_time - self.lastUpdate) > refresh_rate: self.currentTimestep = self.sliderValue = self.currentTimestep - 1 self.lastUpdate = current_time imgui.same_line(spacing=2) changed = imgui.button(">", 20) if self.currentTimestep < self.num_scans - 1: # just a click if changed: self.currentTimestep = self.sliderValue = self.currentTimestep + 1 self.lastUpdate = current_time # button pressed. if imgui.is_item_active() and not self.button_forward_hold: self.hold_start = current_time self.button_forward_hold = True if not imgui.is_item_active() and self.button_forward_hold: self.button_forward_hold = False # start playback when button pressed long enough if self.button_forward_hold and ((current_time - self.hold_start) > play_delay): if (current_time - self.lastUpdate) > refresh_rate: self.currentTimestep = self.sliderValue = self.currentTimestep + 1 self.lastUpdate = current_time imgui.pop_style_var(3) imgui.end() imgui.set_next_window_position(20, 20, imgui.FIRST_USE_EVER) imgui.set_next_window_size(200, 150, imgui.FIRST_USE_EVER) imgui.begin("Show Data") if len(self.subdirs) > 1: for i, subdir in enumerate(self.subdirs): changed, value = imgui.checkbox(subdir, self.current_subdir == i) if i < len(self.subdirs) - 1: imgui.same_line() if changed and value: self.current_subdir = i subdir = self.subdirs[self.current_subdir] data_available = "input" in self.availableData[subdir] if data_available: imgui.push_style_var(imgui.STYLE_ALPHA, 1.0) else: imgui.push_style_var(imgui.STYLE_ALPHA, 0.3) changed, value = imgui.checkbox("input", self.showInput) if changed and value and data_available: self.showInput = True self.showLabels = False imgui.pop_style_var() data_available = "labels" in self.availableData[subdir] if data_available: imgui.push_style_var(imgui.STYLE_ALPHA, 1.0) else: imgui.push_style_var(imgui.STYLE_ALPHA, 0.3) changed, value = imgui.checkbox("labels", self.showLabels) if changed and value and data_available: self.showInput = False self.showLabels = True imgui.pop_style_var() data_available = "invalid" in self.availableData[subdir] if data_available: imgui.push_style_var(imgui.STYLE_ALPHA, 1.0) else: imgui.push_style_var(imgui.STYLE_ALPHA, 0.3) changed, value = imgui.checkbox("invalid", self.showInvalid) if changed and data_available: self.showInvalid = value imgui.pop_style_var() data_available = "occluded" in self.availableData[subdir] if data_available: imgui.push_style_var(imgui.STYLE_ALPHA, 1.0) else: imgui.push_style_var(imgui.STYLE_ALPHA, 0.3) changed, value = imgui.checkbox("occluded", self.showOccluded) if changed and data_available: self.showOccluded = value imgui.pop_style_var() imgui.end() # imgui.show_demo_window() showData = [] if self.showInput: showData.append("input") if self.showOccluded: showData.append("occluded") if self.showInvalid: showData.append("invalid") mvp = self.projection_ @ self.cam.matrix @ self.conversion_ glClearColor(1.0, 1.0, 1.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glBindVertexArray(self.vao) self.program.bind() self.program["mvp"] = mvp.transpose() self.program["view_mat"] = (self.cam.matrix @ self.conversion_).transpose() self.program["lightPos"] = glow.vec3(10, 10, 10) self.program["voxel_scale"] = 0.8 self.program["voxel_alpha"] = 1.0 self.program["use_label_colors"] = True self.label_colors.bind(0) if self.showLabels: self.setCurrentBufferData("labels", self.currentTimestep) glDrawArraysInstanced(GL_TRIANGLES, 0, 36, self.num_instances) self.program["use_label_colors"] = False self.program["voxel_color"] = glow.vec3(0.3, 0.3, 0.3) self.program["voxel_alpha"] = 0.5 for data_name in showData: self.program["voxel_scale"] = 0.5 if data_name == "input": self.program["voxel_scale"] = 0.8 self.setCurrentBufferData(data_name, self.currentTimestep) glDrawArraysInstanced(GL_TRIANGLES, 0, 36, self.num_instances) self.program.release() self.label_colors.release(0) glBindVertexArray(self.vao_no_points) self.prgDrawPose.bind() self.prgDrawPose["mvp"] = mvp.transpose() self.prgDrawPose["pose"] = np.identity(4, dtype=np.float32) self.prgDrawPose["size"] = 1.0 glDrawArrays(GL_POINTS, 0, 1) self.prgDrawPose.release() glBindVertexArray(0) # draw gui ontop. imgui.render() self.impl.render(imgui.get_draw_data()) # Swap front and back buffers glfw.swap_buffers(self.window) if __name__ == "__main__": parser = argparse.ArgumentParser("./visualize_voxels.py") parser.add_argument( '--dataset', '-d', type=str, required=True, help='Dataset to visualize. No Default', ) parser.add_argument( '--sequence', '-s', type=str, default="00", required=False, help='Sequence to visualize. Defaults to %(default)s', ) FLAGS, unparsed = parser.parse_known_args() sequence_directory = os.path.join(FLAGS.dataset, "sequences", FLAGS.sequence) window = Window() window.open_directory(sequence_directory) window.run() glfw.terminate()
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/docker.sh
#!/bin/bash # This file is covered by the LICENSE file in the root of this project. docker build -t api --build-arg uid=$(id -g) --build-arg gid=$(id -g) . docker run --privileged \ -ti --rm -e DISPLAY=$DISPLAY \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -v $1:/home/developer/data/ \ api
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/count.py
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import argparse import os import yaml import numpy as np import collections from auxiliary.laserscan import SemLaserScan if __name__ == '__main__': parser = argparse.ArgumentParser("./count.py") parser.add_argument( '--dataset', '-d', type=str, required=True, help='Dataset to calculate scan count. No Default', ) parser.add_argument( '--config', '-c', type=str, required=False, default="config/semantic-kitti.yaml", help='Dataset config file. Defaults to %(default)s', ) FLAGS, unparsed = parser.parse_known_args() # print summary of what we will do print("*" * 80) print("INTERFACE:") print("Dataset", FLAGS.dataset) print("Config", FLAGS.config) print("*" * 80) # open config file try: print("Opening config file %s" % FLAGS.config) CFG = yaml.safe_load(open(FLAGS.config, 'r')) except Exception as e: print(e) print("Error opening yaml file.") quit() # get training sequences to calculate statistics sequences = CFG["split"]["train"] sequences.extend(CFG["split"]["valid"]) sequences.extend(CFG["split"]["test"]) sequences.sort() print("Analizing sequences", sequences, "to count number of scans") # iterate over sequences and count scan number for seq in sequences: seqstr = '{0:02d}'.format(int(seq)) scan_paths = os.path.join(FLAGS.dataset, "sequences", seqstr, "velodyne") if not os.path.isdir(scan_paths): print("Sequence", seqstr, "doesn't exist! Exiting...") quit() scan_names = [os.path.join(dp, f) for dp, dn, fn in os.walk( os.path.expanduser(scan_paths)) for f in fn] print(seqstr, ",", len(scan_names))
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/config/semantic-kitti.yaml
# This file is covered by the LICENSE file in the root of this project. labels: 0 : "unlabeled" 1 : "outlier" 10: "car" 11: "bicycle" 13: "bus" 15: "motorcycle" 16: "on-rails" 18: "truck" 20: "other-vehicle" 30: "person" 31: "bicyclist" 32: "motorcyclist" 40: "road" 44: "parking" 48: "sidewalk" 49: "other-ground" 50: "building" 51: "fence" 52: "other-structure" 60: "lane-marking" 70: "vegetation" 71: "trunk" 72: "terrain" 80: "pole" 81: "traffic-sign" 99: "other-object" 252: "moving-car" 253: "moving-bicyclist" 254: "moving-person" 255: "moving-motorcyclist" 256: "moving-on-rails" 257: "moving-bus" 258: "moving-truck" 259: "moving-other-vehicle" color_map: # bgr 0 : [0, 0, 0] 1 : [0, 0, 255] 10: [245, 150, 100] 11: [245, 230, 100] 13: [250, 80, 100] 15: [150, 60, 30] 16: [255, 0, 0] 18: [180, 30, 80] 20: [255, 0, 0] 30: [30, 30, 255] 31: [200, 40, 255] 32: [90, 30, 150] 40: [255, 0, 255] 44: [255, 150, 255] 48: [75, 0, 75] 49: [75, 0, 175] 50: [0, 200, 255] 51: [50, 120, 255] 52: [0, 150, 255] 60: [170, 255, 150] 70: [0, 175, 0] 71: [0, 60, 135] 72: [80, 240, 150] 80: [150, 240, 255] 81: [0, 0, 255] 99: [255, 255, 50] 252: [245, 150, 100] 256: [255, 0, 0] 253: [200, 40, 255] 254: [30, 30, 255] 255: [90, 30, 150] 257: [250, 80, 100] 258: [180, 30, 80] 259: [255, 0, 0] content: # as a ratio with the total number of points 0: 0.018889854628292943 1: 0.0002937197336781505 10: 0.040818519255974316 11: 0.00016609538710764618 13: 2.7879693665067774e-05 15: 0.00039838616015114444 16: 0.0 18: 0.0020633612104619787 20: 0.0016218197275284021 30: 0.00017698551338515307 31: 1.1065903904919655e-08 32: 5.532951952459828e-09 40: 0.1987493871255525 44: 0.014717169549888214 48: 0.14392298360372 49: 0.0039048553037472045 50: 0.1326861944777486 51: 0.0723592229456223 52: 0.002395131480328884 60: 4.7084144280367186e-05 70: 0.26681502148037506 71: 0.006035012012626033 72: 0.07814222006271769 80: 0.002855498193863172 81: 0.0006155958086189918 99: 0.009923127583046915 252: 0.001789309418528068 253: 0.00012709999297008662 254: 0.00016059776092534436 255: 3.745553104802113e-05 256: 0.0 257: 0.00011351574470342043 258: 0.00010157861367183268 259: 4.3840131989471124e-05 # classes that are indistinguishable from single scan or inconsistent in # ground truth are mapped to their closest equivalent learning_map: 0 : 0 # "unlabeled" 1 : 0 # "outlier" mapped to "unlabeled" --------------------------mapped 10: 1 # "car" 11: 2 # "bicycle" 13: 5 # "bus" mapped to "other-vehicle" --------------------------mapped 15: 3 # "motorcycle" 16: 5 # "on-rails" mapped to "other-vehicle" ---------------------mapped 18: 4 # "truck" 20: 5 # "other-vehicle" 30: 6 # "person" 31: 7 # "bicyclist" 32: 8 # "motorcyclist" 40: 9 # "road" 44: 10 # "parking" 48: 11 # "sidewalk" 49: 12 # "other-ground" 50: 13 # "building" 51: 14 # "fence" 52: 0 # "other-structure" mapped to "unlabeled" ------------------mapped 60: 9 # "lane-marking" to "road" ---------------------------------mapped 70: 15 # "vegetation" 71: 16 # "trunk" 72: 17 # "terrain" 80: 18 # "pole" 81: 19 # "traffic-sign" 99: 0 # "other-object" to "unlabeled" ----------------------------mapped 252: 1 # "moving-car" to "car" ------------------------------------mapped 253: 7 # "moving-bicyclist" to "bicyclist" ------------------------mapped 254: 6 # "moving-person" to "person" ------------------------------mapped 255: 8 # "moving-motorcyclist" to "motorcyclist" ------------------mapped 256: 5 # "moving-on-rails" mapped to "other-vehicle" --------------mapped 257: 5 # "moving-bus" mapped to "other-vehicle" -------------------mapped 258: 4 # "moving-truck" to "truck" --------------------------------mapped 259: 5 # "moving-other"-vehicle to "other-vehicle" ----------------mapped learning_map_inv: # inverse of previous map 0: 0 # "unlabeled", and others ignored 1: 10 # "car" 2: 11 # "bicycle" 3: 15 # "motorcycle" 4: 18 # "truck" 5: 20 # "other-vehicle" 6: 30 # "person" 7: 31 # "bicyclist" 8: 32 # "motorcyclist" 9: 40 # "road" 10: 44 # "parking" 11: 48 # "sidewalk" 12: 49 # "other-ground" 13: 50 # "building" 14: 51 # "fence" 15: 70 # "vegetation" 16: 71 # "trunk" 17: 72 # "terrain" 18: 80 # "pole" 19: 81 # "traffic-sign" learning_ignore: # Ignore classes 0: True # "unlabeled", and others ignored 1: False # "car" 2: False # "bicycle" 3: False # "motorcycle" 4: False # "truck" 5: False # "other-vehicle" 6: False # "person" 7: False # "bicyclist" 8: False # "motorcyclist" 9: False # "road" 10: False # "parking" 11: False # "sidewalk" 12: False # "other-ground" 13: False # "building" 14: False # "fence" 15: False # "vegetation" 16: False # "trunk" 17: False # "terrain" 18: False # "pole" 19: False # "traffic-sign" split: # sequence numbers train: - 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 9 - 10 valid: - 8 test: - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20 - 21
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/config/semantic-kitti-mos.yaml
# This file is covered by the LICENSE file in the root of this project. # developed by Xieyuanli Chen name: "kitti" labels: 0 : "unlabeled" 1 : "outlier" 9 : "static" # for lidar-mos static 10: "car" 11: "bicycle" 13: "bus" 15: "motorcycle" 16: "on-rails" 18: "truck" 20: "other-vehicle" 30: "person" 31: "bicyclist" 32: "motorcyclist" 40: "road" 44: "parking" 48: "sidewalk" 49: "other-ground" 50: "building" 51: "fence" 52: "other-structure" 60: "lane-marking" 70: "vegetation" 71: "trunk" 72: "terrain" 80: "pole" 81: "traffic-sign" 99: "other-object" 251: "moving" # lidar-mos mod moving 252: "moving-car" 253: "moving-bicyclist" 254: "moving-person" 255: "moving-motorcyclist" 256: "moving-on-rails" 257: "moving-bus" 258: "moving-truck" 259: "moving-other-vehicle" color_map: # bgr 0 : [0, 0, 0] 1 : [0, 0, 0] # [0, 0, 255] 9 : [0, 0, 0] # for lidar-mos static 10: [245, 150, 100] 11: [245, 230, 100] 13: [250, 80, 100] 15: [150, 60, 30] 16: [255, 0, 0] 18: [180, 30, 80] 20: [255, 0, 0] 30: [30, 30, 255] 31: [200, 40, 255] 32: [90, 30, 150] 40: [255, 0, 255] 44: [255, 150, 255] 48: [75, 0, 75] 49: [75, 0, 175] 50: [0, 200, 255] 51: [50, 120, 255] 52: [0, 150, 255] 60: [170, 255, 150] 70: [0, 175, 0] 71: [0, 60, 135] 72: [80, 240, 150] 80: [150, 240, 255] 81: [0, 0, 255] 99: [255, 255, 50] 251: [0, 0, 255] # lidar-mos mod moving 252: [245, 150, 100] 256: [255, 0, 0] 253: [200, 40, 255] 254: [30, 30, 255] 255: [90, 30, 150] 257: [250, 80, 100] 258: [180, 30, 80] 259: [255, 0, 0] content: # as a ratio with the total number of points 0: 0.018889854628292943 1: 0.0002937197336781505 10: 0.040818519255974316 11: 0.00016609538710764618 13: 2.7879693665067774e-05 15: 0.00039838616015114444 16: 0.0 18: 0.0020633612104619787 20: 0.0016218197275284021 30: 0.00017698551338515307 31: 1.1065903904919655e-08 32: 5.532951952459828e-09 40: 0.1987493871255525 44: 0.014717169549888214 48: 0.14392298360372 49: 0.0039048553037472045 50: 0.1326861944777486 51: 0.0723592229456223 52: 0.002395131480328884 60: 4.7084144280367186e-05 70: 0.26681502148037506 71: 0.006035012012626033 72: 0.07814222006271769 80: 0.002855498193863172 81: 0.0006155958086189918 99: 0.009923127583046915 252: 0.001789309418528068 253: 0.00012709999297008662 254: 0.00016059776092534436 255: 3.745553104802113e-05 256: 0.0 257: 0.00011351574470342043 258: 0.00010157861367183268 259: 4.3840131989471124e-05 # classes that are indistinguishable from single scan or inconsistent in # ground truth are mapped to their closest equivalent learning_map: 0 : 0 # "unlabeled" mapped to "unlabeled" ------------------------mapped 1 : 0 # "outlier" mapped to "unlabeled" ------------------------mapped 9 : 1 # "static" mapped to "static" ---------------------------mapped 10: 1 # "car" mapped to "static" ---------------------------mapped 11: 1 # "bicycle" mapped to "static" ---------------------------mapped 13: 1 # "bus" mapped to "static" ---------------------------mapped 15: 1 # "motorcycle" mapped to "static" ---------------------------mapped 16: 1 # "on-rails" mapped to "static" ---------------------------mapped 18: 1 # "truck" mapped to "static" ---------------------------mapped 20: 1 # "other-vehicle" mapped to "static" ---------------------------mapped 30: 1 # "person" mapped to "static" ---------------------------mapped 31: 1 # "bicyclist" mapped to "static" ---------------------------mapped 32: 1 # "motorcyclist" mapped to "static" ---------------------------mapped 40: 1 # "road" mapped to "static" ---------------------------mapped 44: 1 # "parking" mapped to "static" ---------------------------mapped 48: 1 # "sidewalk" mapped to "static" ---------------------------mapped 49: 1 # "other-ground" mapped to "static" ---------------------------mapped 50: 1 # "building" mapped to "static" ---------------------------mapped 51: 1 # "fence" mapped to "static" ---------------------------mapped 52: 1 # "other-structure" mapped to "static" ---------------------------mapped 60: 1 # "lane-marking" mapped to "static" ---------------------------mapped 70: 1 # "vegetation" mapped to "static" ---------------------------mapped 71: 1 # "trunk" mapped to "static" ---------------------------mapped 72: 1 # "terrain" mapped to "static" ---------------------------mapped 80: 1 # "pole" mapped to "static" ---------------------------mapped 81: 1 # "traffic-sign" mapped to "static" ---------------------------mapped 99: 1 # "other-object" mapped to "static" ---------------------------mapped 251: 2 # "moving" mapped to "moving" ---------------------------mapped 252: 2 # "moving-car" mapped to "moving" ---------------------------mapped 253: 2 # "moving-bicyclist" mapped to "moving" ---------------------------mapped 254: 2 # "moving-person" mapped to "moving" ---------------------------mapped 255: 2 # "moving-motorcyclist" mapped to "moving" ---------------------------mapped 256: 2 # "moving-on-rails" mapped to "moving" ---------------------------mapped 257: 2 # "moving-bus" mapped to "moving" ---------------------------mapped 258: 2 # "moving-truck" mapped to "moving" ---------------------------mapped 259: 2 # "moving-other" mapped to "moving" ---------------------------mapped learning_map_inv: # inverse of previous map 0: 0 # "unlabeled", and others ignored 1: 9 # "static" 2: 251 # "moving" learning_ignore: # Ignore classes 0: True # "unlabeled", and others ignored 1: False # "static" 2: False # "moving" split: # sequence numbers train: - 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 9 - 10 valid: - 8 test: - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20 - 21
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/config/semantic-kitti-all.yaml
# This file is covered by the LICENSE file in the root of this project. labels: 0 : "unlabeled" 1 : "outlier" 10: "car" 11: "bicycle" 13: "bus" 15: "motorcycle" 16: "on-rails" 18: "truck" 20: "other-vehicle" 30: "person" 31: "bicyclist" 32: "motorcyclist" 40: "road" 44: "parking" 48: "sidewalk" 49: "other-ground" 50: "building" 51: "fence" 52: "other-structure" 60: "lane-marking" 70: "vegetation" 71: "trunk" 72: "terrain" 80: "pole" 81: "traffic-sign" 99: "other-object" 252: "moving-car" 253: "moving-bicyclist" 254: "moving-person" 255: "moving-motorcyclist" 256: "moving-on-rails" 257: "moving-bus" 258: "moving-truck" 259: "moving-other-vehicle" color_map: # bgr 0 : [0, 0, 0] 1 : [0, 0, 255] 10: [245, 150, 100] 11: [245, 230, 100] 13: [250, 80, 100] 15: [150, 60, 30] 16: [255, 0, 0] 18: [180, 30, 80] 20: [255, 0, 0] 30: [30, 30, 255] 31: [200, 40, 255] 32: [90, 30, 150] 40: [255, 0, 255] 44: [255, 150, 255] 48: [75, 0, 75] 49: [75, 0, 175] 50: [0, 200, 255] 51: [50, 120, 255] 52: [0, 150, 255] 60: [170, 255, 150] 70: [0, 175, 0] 71: [0, 60, 135] 72: [80, 240, 150] 80: [150, 240, 255] 81: [0, 0, 255] 99: [255, 255, 50] 252: [245, 150, 100] 256: [255, 0, 0] 253: [200, 40, 255] 254: [30, 30, 255] 255: [90, 30, 150] 257: [250, 80, 100] 258: [180, 30, 80] 259: [255, 0, 0] content: # as a ratio with the total number of points 0: 0.018889854628292943 1: 0.0002937197336781505 10: 0.040818519255974316 11: 0.00016609538710764618 13: 2.7879693665067774e-05 15: 0.00039838616015114444 16: 0.0 18: 0.0020633612104619787 20: 0.0016218197275284021 30: 0.00017698551338515307 31: 1.1065903904919655e-08 32: 5.532951952459828e-09 40: 0.1987493871255525 44: 0.014717169549888214 48: 0.14392298360372 49: 0.0039048553037472045 50: 0.1326861944777486 51: 0.0723592229456223 52: 0.002395131480328884 60: 4.7084144280367186e-05 70: 0.26681502148037506 71: 0.006035012012626033 72: 0.07814222006271769 80: 0.002855498193863172 81: 0.0006155958086189918 99: 0.009923127583046915 252: 0.001789309418528068 253: 0.00012709999297008662 254: 0.00016059776092534436 255: 3.745553104802113e-05 256: 0.0 257: 0.00011351574470342043 258: 0.00010157861367183268 259: 4.3840131989471124e-05 # classes that are indistinguishable from single scan or inconsistent in # ground truth are mapped to their closest equivalent learning_map: 0 : 0 # "unlabeled" 1 : 0 # "outlier" mapped to "unlabeled" --------------------------mapped 10: 1 # "car" 11: 2 # "bicycle" 13: 5 # "bus" mapped to "other-vehicle" --------------------------mapped 15: 3 # "motorcycle" 16: 5 # "on-rails" mapped to "other-vehicle" ---------------------mapped 18: 4 # "truck" 20: 5 # "other-vehicle" 30: 6 # "person" 31: 7 # "bicyclist" 32: 8 # "motorcyclist" 40: 9 # "road" 44: 10 # "parking" 48: 11 # "sidewalk" 49: 12 # "other-ground" 50: 13 # "building" 51: 14 # "fence" 52: 0 # "other-structure" mapped to "unlabeled" ------------------mapped 60: 9 # "lane-marking" to "road" ---------------------------------mapped 70: 15 # "vegetation" 71: 16 # "trunk" 72: 17 # "terrain" 80: 18 # "pole" 81: 19 # "traffic-sign" 99: 0 # "other-object" to "unlabeled" ----------------------------mapped 252: 20 # "moving-car" 253: 21 # "moving-bicyclist" 254: 22 # "moving-person" 255: 23 # "moving-motorcyclist" 256: 24 # "moving-on-rails" mapped to "moving-other-vehicle" ------mapped 257: 24 # "moving-bus" mapped to "moving-other-vehicle" -----------mapped 258: 25 # "moving-truck" 259: 24 # "moving-other-vehicle" learning_map_inv: # inverse of previous map 0: 0 # "unlabeled", and others ignored 1: 10 # "car" 2: 11 # "bicycle" 3: 15 # "motorcycle" 4: 18 # "truck" 5: 20 # "other-vehicle" 6: 30 # "person" 7: 31 # "bicyclist" 8: 32 # "motorcyclist" 9: 40 # "road" 10: 44 # "parking" 11: 48 # "sidewalk" 12: 49 # "other-ground" 13: 50 # "building" 14: 51 # "fence" 15: 70 # "vegetation" 16: 71 # "trunk" 17: 72 # "terrain" 18: 80 # "pole" 19: 81 # "traffic-sign" 20: 252 # "moving-car" 21: 253 # "moving-bicyclist" 22: 254 # "moving-person" 23: 255 # "moving-motorcyclist" 24: 259 # "moving-other-vehicle" 25: 258 # "moving-truck" learning_ignore: # Ignore classes 0: True # "unlabeled", and others ignored 1: False # "car" 2: False # "bicycle" 3: False # "motorcycle" 4: False # "truck" 5: False # "other-vehicle" 6: False # "person" 7: False # "bicyclist" 8: False # "motorcyclist" 9: False # "road" 10: False # "parking" 11: False # "sidewalk" 12: False # "other-ground" 13: False # "building" 14: False # "fence" 15: False # "vegetation" 16: False # "trunk" 17: False # "terrain" 18: False # "pole" 19: False # "traffic-sign" 20: False # "moving-car" 21: False # "moving-bicyclist" 22: False # "moving-person" 23: False # "moving-motorcyclist" 24: False # "moving-other-vehicle" 25: False # "moving-truck" split: # sequence numbers train: - 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 9 - 10 valid: - 8 test: - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18 - 19 - 20 - 21
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/torch_ioueval.py
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import sys import torch import numpy as np class iouEval: def __init__(self, n_classes, ignore=None): # classes self.n_classes = n_classes # What to include and ignore from the means self.ignore = torch.tensor(ignore).long() self.include = torch.tensor( [n for n in range(self.n_classes) if n not in self.ignore]).long() print("[IOU EVAL] IGNORE: ", self.ignore) print("[IOU EVAL] INCLUDE: ", self.include) # get device self.device = torch.device('cpu') if torch.cuda.is_available(): self.device = torch.device('cuda') # reset the class counters self.reset() def num_classes(self): return self.n_classes def reset(self): self.conf_matrix = torch.zeros( (self.n_classes, self.n_classes), device=self.device).long() def addBatch(self, x, y): # x=preds, y=targets # to tensor x_row = torch.from_numpy(x).to(self.device).long() y_row = torch.from_numpy(y).to(self.device).long() # sizes should be matching x_row = x_row.reshape(-1) # de-batchify y_row = y_row.reshape(-1) # de-batchify # check assert(x_row.shape == x_row.shape) # idxs are labels and predictions idxs = torch.stack([x_row, y_row], dim=0) # ones is what I want to add to conf when I ones = torch.ones((idxs.shape[-1]), device=self.device).long() # make confusion matrix (cols = gt, rows = pred) self.conf_matrix = self.conf_matrix.index_put_( tuple(idxs), ones, accumulate=True) def getStats(self): # remove fp from confusion on the ignore classes cols conf = self.conf_matrix.clone().double() conf[:, self.ignore] = 0 # get the clean stats tp = conf.diag() fp = conf.sum(dim=1) - tp fn = conf.sum(dim=0) - tp return tp, fp, fn def getIoU(self): tp, fp, fn = self.getStats() intersection = tp union = tp + fp + fn + 1e-15 iou = intersection / union iou_mean = (intersection[self.include] / union[self.include]).mean() return iou_mean, iou # returns "iou mean", "iou per class" ALL CLASSES def getacc(self): tp, fp, fn = self.getStats() total_tp = tp.sum() total = tp[self.include].sum() + fp[self.include].sum() + 1e-15 acc_mean = total_tp / total return acc_mean # returns "acc mean" if __name__ == "__main__": # mock problem nclasses = 2 ignore = [] # test with 2 squares and a known IOU lbl = np.zeros((7, 7), dtype=np.int64) argmax = np.zeros((7, 7), dtype=np.int64) # put squares lbl[2:4, 2:4] = 1 argmax[3:5, 3:5] = 1 # make evaluator eval = iouEval(nclasses, ignore) # run eval.addBatch(argmax, lbl) m_iou, iou = eval.getIoU() print("IoU: ", m_iou) print("IoU class: ", iou) m_acc = eval.getacc() print("Acc: ", m_acc)
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/glow.py
import OpenGL.GL as gl gl.ERROR_CHECKING = True gl.ERROR_ON_COPY = True gl.WARN_ON_FORMAT_UNAVAILABLE = True import numpy as np import re """ openGL Object Wrapper (GLOW) in python. Some convenience classes to simplify resource management """ WARN_INVALID_UNIFORMS = False def vec2(x, y): """ returns an vec2-compatible numpy array """ return np.array([x, y], dtype=np.float32) def vec3(x, y, z): """ returns an vec3-compatible numpy array """ return np.array([x, y, z], dtype=np.float32) def vec4(x, y, z, w): """ returns an vec4-compatible numpy array """ return np.array([x, y, z, w], dtype=np.float32) def ivec2(x, y): """ returns an ivec2-compatible numpy array """ return np.array([x, y], dtype=np.int32) def ivec3(x, y, z): """ returns an ivec3-compatible numpy array """ return np.array([x, y, z], dtype=np.int32) def ivec4(x, y, z, w): """ returns an ivec4-compatible numpy array """ return np.array([x, y, z, w], dtype=np.int32) def uivec2(x, y): """ returns an ivec2-compatible numpy array """ return np.array([x, y], dtype=np.uint32) def uivec3(x, y, z): """ returns an ivec3-compatible numpy array """ return np.array([x, y, z], dtype=np.uint32) def uivec4(x, y, z, w): """ returns an ivec4-compatible numpy array """ return np.array([x, y, z, w], dtype=np.uint32) class GlBuffer: """ Buffer object representing a vertex array buffer. """ def __init__(self, target=gl.GL_ARRAY_BUFFER, usage=gl.GL_STATIC_DRAW): self.id_ = gl.glGenBuffers(1) self.target_ = target self.usage_ = usage # def __del__(self): # gl.glDeleteBuffers(1, self.id_) def assign(self, array): gl.glBindBuffer(self.target_, self.id_) gl.glBufferData(self.target_, array, self.usage_) gl.glBindBuffer(self.target_, 0) def bind(self): gl.glBindBuffer(self.target_, self.id_) def release(self): gl.glBindBuffer(self.target_, 0) @property def id(self): return self.id_ @property def usage(self): return self.usage_ @property def target(self): return self.target_ class GlTextureRectangle: def __init__(self, width, height, internalFormat=gl.GL_RGBA, format=gl.GL_RGBA): self.id_ = gl.glGenTextures(1) self.internalFormat_ = internalFormat # gl.GL_RGB_FLOAT, gl.GL_RGB_UNSIGNED, ... self.format = format # GL_RG. GL_RG_INTEGER, ... self.width_ = width self.height_ = height gl.glBindTexture(gl.GL_TEXTURE_RECTANGLE, self.id_) gl.glTexParameteri(gl.GL_TEXTURE_RECTANGLE, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_RECTANGLE, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_RECTANGLE, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_BORDER) gl.glTexParameteri(gl.GL_TEXTURE_RECTANGLE, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_BORDER) gl.glBindTexture(gl.GL_TEXTURE_RECTANGLE, 0) def bind(self, textureUnitId): gl.glActiveTexture(gl.GL_TEXTURE0 + int(textureUnitId)) gl.glBindTexture(gl.GL_TEXTURE_RECTANGLE, self.id_) def release(self, textureUnitId): gl.glActiveTexture(gl.GL_TEXTURE0 + int(textureUnitId)) gl.glBindTexture(gl.GL_TEXTURE_RECTANGLE, 0) def assign(self, array): gl.glBindTexture(gl.GL_TEXTURE_RECTANGLE, self.id_) if array.dtype == np.uint8: gl.glTexImage2D(gl.GL_TEXTURE_RECTANGLE, 0, self.internalFormat_, self.width_, self.height_, 0, self.format, gl.GL_UNSIGNED_BYTE, array) elif array.dtype == np.float32: gl.glTexImage2D(gl.GL_TEXTURE_RECTANGLE, 0, self.internalFormat_, self.width_, self.height_, 0, self.format, gl.GL_FLOAT, array) else: raise NotImplementedError("pixel type not implemented.") gl.glBindTexture(gl.GL_TEXTURE_RECTANGLE, 0) @property def id(self): return self.id_ class GlShader: def __init__(self, shader_type, source): self.code_ = source self.shader_type_ = shader_type self.id_ = gl.glCreateShader(self.shader_type_) gl.glShaderSource(self.id_, source) gl.glCompileShader(self.id_) success = gl.glGetShaderiv(self.id_, gl.GL_COMPILE_STATUS) if success == gl.GL_FALSE: error_string = gl.glGetShaderInfoLog(self.id_).decode("utf-8") raise RuntimeError(error_string) def __del__(self): gl.glDeleteShader(self.id_) @property def type(self): return self.shader_type_ @property def id(self): return self.id_ @property def code(self): return self.code_ @staticmethod def fromFile(shader_type, filename): f = open(filename) source = "\n".join(f.readlines()) # todo: preprocess. f.close() return GlShader(shader_type, source) class GlProgram: """ An OpenGL program handle. """ def __init__(self): self.id_ = gl.glCreateProgram() self.shaders_ = {} self.uniform_types_ = {} self.is_linked = False def __del__(self): gl.glDeleteProgram(self.id_) def bind(self): if not self.is_linked: raise RuntimeError("Program must be linked before usage.") gl.glUseProgram(self.id_) def release(self): gl.glUseProgram(0) def attach(self, shader): self.shaders_[shader.type] = shader def __setitem__(self, name, value): # quitely ignore if name not in self.uniform_types_: if WARN_INVALID_UNIFORMS: print("No uniform with name '{}' available.".format(name)) return loc = gl.glGetUniformLocation(self.id_, name) T = self.uniform_types_[name] if T == "int": gl.glUniform1i(loc, np.int32(value)) if T == "uint": gl.glUniform1ui(loc, np.uint32(value)) elif T == "float": gl.glUniform1f(loc, np.float32(value)) elif T == "bool": gl.glUniform1f(loc, value) elif T == "vec2": gl.glUniform2fv(loc, 1, value) elif T == "vec3": gl.glUniform3fv(loc, 1, value) elif T == "vec4": gl.glUniform4fv(loc, 1, value) elif T == "ivec2": gl.glUniform2iv(loc, 1, value) elif T == "ivec3": gl.glUniform3iv(loc, 1, value) elif T == "ivec4": gl.glUniform4iv(loc, 1, value) elif T == "uivec2": gl.glUniform2uiv(loc, 1, value) elif T == "uivec3": gl.glUniform3uiv(loc, 1, value) elif T == "uivec4": gl.glUniform4uiv(loc, 1, value) elif T == "mat4": #print("set matrix: ", value) gl.glUniformMatrix4fv(loc, 1, False, value.astype(np.float32)) elif T == "sampler2D": gl.glUniform1i(loc, np.int32(value)) elif T == "sampler2DRect": gl.glUniform1i(loc, np.int32(value)) else: raise NotImplementedError("uniform type {} not implemented. :(".format(T)) def link(self): if gl.GL_VERTEX_SHADER not in self.shaders_ or gl.GL_FRAGMENT_SHADER not in self.shaders_: raise RuntimeError("program needs at least vertex and fragment shader") for shader in self.shaders_.values(): gl.glAttachShader(self.id_, shader.id) for line in shader.code.split("\n"): match = re.search(r"uniform\s+(\S+)\s+(\S+)\s*;", line) if match: self.uniform_types_[match.group(2)] = match.group(1) gl.glLinkProgram(self.id_) isLinked = bool(gl.glGetProgramiv(self.id_, gl.GL_LINK_STATUS)) if not isLinked: msg = gl.glGetProgramInfoLog(self.id_) raise RuntimeError(str(msg.decode("utf-8"))) # after linking we don't need the source code anymore. self.shaders_ = {} self.is_linked = True
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/filelist2files.py
#!/usr/bin/python3 import os import sys import shutil import numpy as np import scipy.io as sio from tqdm import tqdm def pack(array): """ convert a boolean array into a bitwise array. """ array = array.reshape((-1)) #compressing bit flags. # yapf: disable compressed = array[::8] << 7 | array[1::8] << 6 | array[2::8] << 5 | array[3::8] << 4 | array[4::8] << 3 | array[5::8] << 2 | array[6::8] << 1 | array[7::8] # yapf: enable return np.array(compressed, dtype=np.uint8) if __name__ == "__main__": """ Convert a given directory of mat files and the given filelist into a separate directory containing the files in the file list. """ if len(sys.argv) < 2: print("./filelist2files.py <input-root-directory> <output-root-directory> [<filelist>]") exit(1) src_dir = sys.argv[1] dst_dir = sys.argv[2] files = None if len(sys.argv) > 3: files = [line.strip().split("_") for line in open(sys.argv[3])] else: seq_dirs = [d for d in os.listdir(src_dir) if os.path.isdir(os.path.join(src_dir, d))] files = [] for d in seq_dirs: files.extend([(d, os.path.splitext(f)[0]) for f in os.listdir(os.path.join(src_dir, d, "input"))]) print("Processing {} files.".format(len(files))) for seq_dir, filename in tqdm(files): if os.path.exists(os.path.join(src_dir, seq_dir, "input", filename + ".mat")): data = sio.loadmat(os.path.join(src_dir, seq_dir, "input", filename + ".mat")) out_dir = os.path.join(dst_dir, seq_dir, "voxels") os.makedirs(out_dir, exist_ok=True) compressed = pack(data["voxels"]) compressed.tofile(os.path.join(out_dir, os.path.splitext(filename)[0] + ".bin")) if os.path.exists(os.path.join(src_dir, seq_dir, "target_gt", filename + ".mat")): data = sio.loadmat(os.path.join(src_dir, seq_dir, "target_gt", filename + ".mat")) out_dir = os.path.join(dst_dir, seq_dir, "voxels") os.makedirs(out_dir, exist_ok=True) labels = data["voxels"].astype(np.uint16) labels.tofile(os.path.join(out_dir, os.path.splitext(filename)[0] + ".label")) occlusions = pack(data["occluded"]) occlusions.tofile(os.path.join(out_dir, os.path.splitext(filename)[0] + ".occluded")) invalid = pack(data["invalid"]) invalid.tofile(os.path.join(out_dir, os.path.splitext(filename)[0] + ".invalid"))
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/np_ioueval.py
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import sys import numpy as np class iouEval: def __init__(self, n_classes, ignore=None): # classes self.n_classes = n_classes # What to include and ignore from the means self.ignore = np.array(ignore, dtype=np.int64) self.include = np.array( [n for n in range(self.n_classes) if n not in self.ignore], dtype=np.int64) print("[IOU EVAL] IGNORE: ", self.ignore) print("[IOU EVAL] INCLUDE: ", self.include) # reset the class counters self.reset() def num_classes(self): return self.n_classes def reset(self): self.conf_matrix = np.zeros((self.n_classes, self.n_classes), dtype=np.int64) def addBatch(self, x, y): # x=preds, y=targets # sizes should be matching x_row = x.reshape(-1) # de-batchify y_row = y.reshape(-1) # de-batchify # check assert(x_row.shape == y_row.shape) # create indexes idxs = tuple(np.stack((x_row, y_row), axis=0)) # make confusion matrix (cols = gt, rows = pred) np.add.at(self.conf_matrix, idxs, 1) def getStats(self): # remove fp from confusion on the ignore classes cols conf = self.conf_matrix.copy() conf[:, self.ignore] = 0 # get the clean stats tp = np.diag(conf) fp = conf.sum(axis=1) - tp fn = conf.sum(axis=0) - tp return tp, fp, fn def getIoU(self): tp, fp, fn = self.getStats() intersection = tp union = tp + fp + fn + 1e-15 iou = intersection / union iou_mean = (intersection[self.include] / union[self.include]).mean() return iou_mean, iou # returns "iou mean", "iou per class" ALL CLASSES def getacc(self): tp, fp, fn = self.getStats() total_tp = tp.sum() total = tp[self.include].sum() + fp[self.include].sum() + 1e-15 acc_mean = total_tp / total return acc_mean # returns "acc mean" def get_confusion(self): return self.conf_matrix.copy() if __name__ == "__main__": # mock problem nclasses = 2 ignore = [] # test with 2 squares and a known IOU lbl = np.zeros((7, 7), dtype=np.int64) argmax = np.zeros((7, 7), dtype=np.int64) # put squares lbl[2:4, 2:4] = 1 argmax[3:5, 3:5] = 1 # make evaluator eval = iouEval(nclasses, ignore) # run eval.addBatch(argmax, lbl) m_iou, iou = eval.getIoU() print("IoU: ", m_iou) print("IoU class: ", iou) m_acc = eval.getacc() print("Acc: ", m_acc)
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/camera.py
import math import numpy as np import time import glfw def RotX(angle): sin_t = math.sin(angle) cos_t = math.cos(angle) return np.array([1, 0, 0, 0, 0, cos_t, -sin_t, 0, 0, sin_t, cos_t, 0, 0, 0, 0, 1], dtype=np.float32).reshape(4, 4) def RotY(angle): sin_t = math.sin(angle) cos_t = math.cos(angle) return np.array([cos_t, 0, sin_t, 0, 0, 1, 0, 0, -sin_t, 0, cos_t, 0, 0, 0, 0, 1], dtype=np.float32).reshape(4, 4) def Trans(x, y, z): return np.array([1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1], dtype=np.float32).reshape(4, 4) class Camera: """ Camera for handling the view matrix based on mouse inputs. """ def __init__(self): self.x_ = self.y_ = self.z_ = 0.0 self.pitch_ = 0.0 self.yaw_ = 0.0 self.startdrag_ = False self.startTime_ = 0 self.startx_ = 0 self.starty_ = 0 self.startyaw_ = 0 self.startpitch_ = 0 self.forwardVel_ = 0.0 self.upVel_ = 0.0 self.sideVel_ = 0.0 self.turnVel_ = 0.0 self.startdrag_ = False def lookAt(self, x_cam, y_cam, z_cam, x_ref, y_ref, z_ref): self.x_ = x_cam self.y_ = y_cam self.z_ = z_cam x = x_ref - self.x_ y = y_ref - self.y_ z = z_ref - self.z_ length = math.sqrt(x * x + y * y + z * z) self.pitch_ = math.asin(y / length) # = std: : acos(-dir.y()) - M_PI_2 in [-pi/2, pi/2] self.yaw_ = math.atan2(-x, -z) self.startdrag_ = False @property def matrix(self): # current time. end = time.time() dt = end - self.startTime_ if dt > 0 and self.startdrag_: # apply velocity & reset timer... self.rotate(self.turnVel_ * dt, 0.0) self.translate(self.forwardVel_ * dt, self.upVel_ * dt, self.sideVel_ * dt) self.startTime_ = end # recompute the view matrix (Euler angles) Remember: Inv(AB) = Inv(B)*Inv(A) # Inv(translate*rotateYaw*rotatePitch) = Inv(rotatePitch)*Inv(rotateYaw)*Inv(translate) view_ = RotX(-self.pitch_) view_ = view_ @ RotY(-self.yaw_) view_ = view_ @ Trans(-self.x_, -self.y_, -self.z_) return view_ def mousePressed(self, x, y, btn, modifier): self.startx_ = x self.starty_ = y self.startyaw_ = self.yaw_ self.startpitch_ = self.pitch_ self.startTime_ = time.time() self.startdrag_ = True return True def mouseReleased(self, x, y, btn, modifier): self.forwardVel_ = 0.0 self.upVel_ = 0.0 self.sideVel_ = 0.0 self.turnVel_ = 0.0 self.startdrag_ = False return True def translate(self, forward, up, sideways): # forward = -z, sideways = x , up = y. Remember: inverse of yaw is applied, i.e., we have to apply yaw (?) # Also keep in mind: sin(-alpha) = -sin(alpha) and cos(-alpha) = -cos(alpha) # We only apply the yaw to move along the yaw direction; # x' = x*cos(yaw) - z*sin(yaw) # z' = x*sin(yaw) + z*cos(yaw) s = math.sin(self.yaw_) c = math.cos(self.yaw_) self.x_ = self.x_ + sideways * c - forward * s self.y_ = self.y_ + up self.z_ = self.z_ - (sideways * s + forward * c) def rotate(self, yaw, pitch): self.yaw_ += yaw self.pitch_ += pitch if self.pitch_ < -0.5 * math.pi: self.pitch_ = -0.5 * math.pi if self.pitch_ > 0.5 * math.pi: self.pitch_ = 0.5 * math.pi def mouseMoved(self, x, y, btn, modifier): # some constants. MIN_MOVE = 0 WALK_SENSITIVITY = 0.5 TURN_SENSITIVITY = 0.01 SLIDE_SENSITIVITY = 0.5 RAISE_SENSITIVITY = 0.5 LOOK_SENSITIVITY = 0.01 FREE_TURN_SENSITIVITY = 0.01 dx = x - self.startx_ dy = y - self.starty_ if dx > 0.0: dx = max(0.0, dx - MIN_MOVE) if dx < 0.0: dx = min(0.0, dx + MIN_MOVE) if dy > 0.0: dy = max(0.0, dy - MIN_MOVE) if dy < 0.0: dy = min(0.0, dy + MIN_MOVE) # idea: if the velocity changes, we have to reset the start_time and update the camera parameters. if btn == glfw.MOUSE_BUTTON_RIGHT: self.forwardVel_ = 0 self.upVel_ = 0 self.sideVel_ = 0 self.turnVel_ = 0 self.yaw_ = self.startyaw_ - FREE_TURN_SENSITIVITY * dx self.pitch_ = self.startpitch_ - LOOK_SENSITIVITY * dy # ensure valid values. if self.pitch_ < -0.5 * math.pi: self.pitch_ = -0.5 * math.pi if self.pitch_ > 0.5 * math.pi: self.pitch_ = 0.5 * math.pi elif btn == glfw.MOUSE_BUTTON_LEFT: # apply transformation: end = time.time() dt = end - self.startTime_ if dt > 0.0: self.rotate(self.turnVel_ * dt, 0.0) self.translate(self.forwardVel_ * dt, self.upVel_ * dt, self.sideVel_ * dt) self.startTime_ = end # reset timer. self.forwardVel_ = -WALK_SENSITIVITY * dy self.upVel_ = 0 self.sideVel_ = 0 self.turnVel_ = -(TURN_SENSITIVITY * dx) elif btn == glfw.MOUSE_BUTTON_MIDDLE: # apply transformation: end = time.time() dt = end - self.startTime_ if dt > 0.0: self.rotate(self.turnVel_ * dt, 0.0) self.translate(self.forwardVel_ * dt, self.upVel_ * dt, self.sideVel_ * dt) self.startTime_ = end # reset timer. self.forwardVel_ = 0 self.upVel_ = -RAISE_SENSITIVITY * dy self.sideVel_ = SLIDE_SENSITIVITY * dx self.turnVel_ = 0 return True
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/laserscanvis.py
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import vispy from vispy.scene import visuals, SceneCanvas import numpy as np from matplotlib import pyplot as plt from auxiliary.laserscan import LaserScan, SemLaserScan class LaserScanVis: """Class that creates and handles a visualizer for a pointcloud""" def __init__(self, scan, scan_names, label_names, offset=0, semantics=True, instances=False): self.scan = scan self.scan_names = scan_names self.label_names = label_names self.offset = offset self.total = len(self.scan_names) self.semantics = semantics self.instances = instances # sanity check if not self.semantics and self.instances: print("Instances are only allowed in when semantics=True") raise ValueError self.reset() self.update_scan() def reset(self): """ Reset. """ # last key press (it should have a mutex, but visualization is not # safety critical, so let's do things wrong) self.action = "no" # no, next, back, quit are the possibilities # new canvas prepared for visualizing data self.canvas = SceneCanvas(keys='interactive', show=True) # interface (n next, b back, q quit, very simple) self.canvas.events.key_press.connect(self.key_press) self.canvas.events.draw.connect(self.draw) # grid self.grid = self.canvas.central_widget.add_grid() # laserscan part self.scan_view = vispy.scene.widgets.ViewBox( border_color='white', parent=self.canvas.scene) self.grid.add_widget(self.scan_view, 0, 0) self.scan_vis = visuals.Markers() self.scan_view.camera = 'turntable' self.scan_view.add(self.scan_vis) visuals.XYZAxis(parent=self.scan_view.scene) # add semantics if self.semantics: print("Using semantics in visualizer") self.sem_view = vispy.scene.widgets.ViewBox( border_color='white', parent=self.canvas.scene) self.grid.add_widget(self.sem_view, 0, 1) self.sem_vis = visuals.Markers() self.sem_view.camera = 'turntable' self.sem_view.add(self.sem_vis) visuals.XYZAxis(parent=self.sem_view.scene) # self.sem_view.camera.link(self.scan_view.camera) if self.instances: print("Using instances in visualizer") self.inst_view = vispy.scene.widgets.ViewBox( border_color='white', parent=self.canvas.scene) self.grid.add_widget(self.inst_view, 0, 2) self.inst_vis = visuals.Markers() self.inst_view.camera = 'turntable' self.inst_view.add(self.inst_vis) visuals.XYZAxis(parent=self.inst_view.scene) # self.inst_view.camera.link(self.scan_view.camera) # img canvas size self.multiplier = 1 self.canvas_W = 1024 self.canvas_H = 64 if self.semantics: self.multiplier += 1 if self.instances: self.multiplier += 1 # new canvas for img self.img_canvas = SceneCanvas(keys='interactive', show=True, size=(self.canvas_W, self.canvas_H * self.multiplier)) # grid self.img_grid = self.img_canvas.central_widget.add_grid() # interface (n next, b back, q quit, very simple) self.img_canvas.events.key_press.connect(self.key_press) self.img_canvas.events.draw.connect(self.draw) # add a view for the depth self.img_view = vispy.scene.widgets.ViewBox( border_color='white', parent=self.img_canvas.scene) self.img_grid.add_widget(self.img_view, 0, 0) self.img_vis = visuals.Image(cmap='viridis') self.img_view.add(self.img_vis) # add semantics if self.semantics: self.sem_img_view = vispy.scene.widgets.ViewBox( border_color='white', parent=self.img_canvas.scene) self.img_grid.add_widget(self.sem_img_view, 1, 0) self.sem_img_vis = visuals.Image(cmap='viridis') self.sem_img_view.add(self.sem_img_vis) # add instances if self.instances: self.inst_img_view = vispy.scene.widgets.ViewBox( border_color='white', parent=self.img_canvas.scene) self.img_grid.add_widget(self.inst_img_view, 2, 0) self.inst_img_vis = visuals.Image(cmap='viridis') self.inst_img_view.add(self.inst_img_vis) def get_mpl_colormap(self, cmap_name): cmap = plt.get_cmap(cmap_name) # Initialize the matplotlib color map sm = plt.cm.ScalarMappable(cmap=cmap) # Obtain linear color range color_range = sm.to_rgba(np.linspace(0, 1, 256), bytes=True)[:, 2::-1] return color_range.reshape(256, 3).astype(np.float32) / 255.0 def update_scan(self): # first open data self.scan.open_scan(self.scan_names[self.offset]) if self.semantics: self.scan.open_label(self.label_names[self.offset]) self.scan.colorize() # then change names title = "scan " + str(self.offset) self.canvas.title = title self.img_canvas.title = title # then do all the point cloud stuff # plot scan power = 16 # print() range_data = np.copy(self.scan.unproj_range) # print(range_data.max(), range_data.min()) range_data = range_data**(1 / power) # print(range_data.max(), range_data.min()) viridis_range = ((range_data - range_data.min()) / (range_data.max() - range_data.min()) * 255).astype(np.uint8) viridis_map = self.get_mpl_colormap("viridis") viridis_colors = viridis_map[viridis_range] self.scan_vis.set_data(self.scan.points, face_color=viridis_colors[..., ::-1], edge_color=viridis_colors[..., ::-1], size=1) # plot semantics if self.semantics: self.sem_vis.set_data(self.scan.points, face_color=self.scan.sem_label_color[..., ::-1], edge_color=self.scan.sem_label_color[..., ::-1], size=1) # plot instances if self.instances: self.inst_vis.set_data(self.scan.points, face_color=self.scan.inst_label_color[..., ::-1], edge_color=self.scan.inst_label_color[..., ::-1], size=1) # now do all the range image stuff # plot range image data = np.copy(self.scan.proj_range) # print(data[data > 0].max(), data[data > 0].min()) data[data > 0] = data[data > 0]**(1 / power) data[data < 0] = data[data > 0].min() # print(data.max(), data.min()) data = (data - data[data > 0].min()) / \ (data.max() - data[data > 0].min()) # print(data.max(), data.min()) self.img_vis.set_data(data) self.img_vis.update() if self.semantics: self.sem_img_vis.set_data(self.scan.proj_sem_color[..., ::-1]) self.sem_img_vis.update() if self.instances: self.inst_img_vis.set_data(self.scan.proj_inst_color[..., ::-1]) self.inst_img_vis.update() # interface def key_press(self, event): self.canvas.events.key_press.block() self.img_canvas.events.key_press.block() if event.key == 'N': self.offset += 1 if self.offset >= self.total: self.offset = 0 self.update_scan() elif event.key == 'B': self.offset -= 1 if self.offset < 0: self.offset = self.total - 1 self.update_scan() elif event.key == 'Q' or event.key == 'Escape': self.destroy() def draw(self, event): if self.canvas.events.key_press.blocked(): self.canvas.events.key_press.unblock() if self.img_canvas.events.key_press.blocked(): self.img_canvas.events.key_press.unblock() def destroy(self): # destroy the visualization self.canvas.close() self.img_canvas.close() vispy.app.quit() def run(self): vispy.app.run()
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/laserscan.py
#!/usr/bin/env python3 import numpy as np class LaserScan: """Class that contains LaserScan with x,y,z,r""" EXTENSIONS_SCAN = ['.bin'] def __init__(self, project=False, H=64, W=1024, fov_up=3.0, fov_down=-25.0): self.project = project self.proj_H = H self.proj_W = W self.proj_fov_up = fov_up self.proj_fov_down = fov_down self.reset() def reset(self): """ Reset scan members. """ self.points = np.zeros((0, 3), dtype=np.float32) # [m, 3]: x, y, z self.remissions = np.zeros((0, 1), dtype=np.float32) # [m ,1]: remission # projected range image - [H,W] range (-1 is no data) self.proj_range = np.full((self.proj_H, self.proj_W), -1, dtype=np.float32) # unprojected range (list of depths for each point) self.unproj_range = np.zeros((0, 1), dtype=np.float32) # projected point cloud xyz - [H,W,3] xyz coord (-1 is no data) self.proj_xyz = np.full((self.proj_H, self.proj_W, 3), -1, dtype=np.float32) # projected remission - [H,W] intensity (-1 is no data) self.proj_remission = np.full((self.proj_H, self.proj_W), -1, dtype=np.float32) # projected index (for each pixel, what I am in the pointcloud) # [H,W] index (-1 is no data) self.proj_idx = np.full((self.proj_H, self.proj_W), -1, dtype=np.int32) # for each point, where it is in the range image self.proj_x = np.zeros((0, 1), dtype=np.float32) # [m, 1]: x self.proj_y = np.zeros((0, 1), dtype=np.float32) # [m, 1]: y # mask containing for each pixel, if it contains a point or not self.proj_mask = np.zeros((self.proj_H, self.proj_W), dtype=np.int32) # [H,W] mask def size(self): """ Return the size of the point cloud. """ return self.points.shape[0] def __len__(self): return self.size() def open_scan(self, filename): """ Open raw scan and fill in attributes """ # reset just in case there was an open structure self.reset() # check filename is string if not isinstance(filename, str): raise TypeError("Filename should be string type, " "but was {type}".format(type=str(type(filename)))) # check extension is a laserscan if not any(filename.endswith(ext) for ext in self.EXTENSIONS_SCAN): raise RuntimeError("Filename extension is not valid scan file.") # if all goes well, open pointcloud scan = np.fromfile(filename, dtype=np.float32) scan = scan.reshape((-1, 4)) # put in attribute points = scan[:, 0:3] # get xyz remissions = scan[:, 3] # get remission self.set_points(points, remissions) def set_points(self, points, remissions=None): """ Set scan attributes (instead of opening from file) """ # reset just in case there was an open structure self.reset() # check scan makes sense if not isinstance(points, np.ndarray): raise TypeError("Scan should be numpy array") # check remission makes sense if remissions is not None and not isinstance(remissions, np.ndarray): raise TypeError("Remissions should be numpy array") # put in attribute self.points = points # get xyz if remissions is not None: self.remissions = remissions # get remission else: self.remissions = np.zeros((points.shape[0]), dtype=np.float32) # if projection is wanted, then do it and fill in the structure if self.project: self.do_range_projection() def do_range_projection(self): """ Project a pointcloud into a spherical projection image.projection. Function takes no arguments because it can be also called externally if the value of the constructor was not set (in case you change your mind about wanting the projection) """ # laser parameters fov_up = self.proj_fov_up / 180.0 * np.pi # field of view up in rad fov_down = self.proj_fov_down / 180.0 * np.pi # field of view down in rad fov = abs(fov_down) + abs(fov_up) # get field of view total in rad # get depth of all points depth = np.linalg.norm(self.points, 2, axis=1) # get scan components scan_x = self.points[:, 0] scan_y = self.points[:, 1] scan_z = self.points[:, 2] # get angles of all points yaw = -np.arctan2(scan_y, scan_x) pitch = np.arcsin(scan_z / depth) # get projections in image coords proj_x = 0.5 * (yaw / np.pi + 1.0) # in [0.0, 1.0] proj_y = 1.0 - (pitch + abs(fov_down)) / fov # in [0.0, 1.0] # scale to image size using angular resolution proj_x *= self.proj_W # in [0.0, W] proj_y *= self.proj_H # in [0.0, H] # round and clamp for use as index proj_x = np.floor(proj_x) proj_x = np.minimum(self.proj_W - 1, proj_x) proj_x = np.maximum(0, proj_x).astype(np.int32) # in [0,W-1] self.proj_x = np.copy(proj_x) # store a copy in orig order proj_y = np.floor(proj_y) proj_y = np.minimum(self.proj_H - 1, proj_y) proj_y = np.maximum(0, proj_y).astype(np.int32) # in [0,H-1] self.proj_y = np.copy(proj_y) # stope a copy in original order # copy of depth in original order self.unproj_range = np.copy(depth) # order in decreasing depth indices = np.arange(depth.shape[0]) order = np.argsort(depth)[::-1] depth = depth[order] indices = indices[order] points = self.points[order] remission = self.remissions[order] proj_y = proj_y[order] proj_x = proj_x[order] # assing to images self.proj_range[proj_y, proj_x] = depth self.proj_xyz[proj_y, proj_x] = points self.proj_remission[proj_y, proj_x] = remission self.proj_idx[proj_y, proj_x] = indices self.proj_mask = (self.proj_idx > 0).astype(np.float32) class SemLaserScan(LaserScan): """Class that contains LaserScan with x,y,z,r,sem_label,sem_color_label,inst_label,inst_color_label""" EXTENSIONS_LABEL = ['.label'] def __init__(self, nclasses, sem_color_dict=None, project=False, H=64, W=1024, fov_up=3.0, fov_down=-25.0): super(SemLaserScan, self).__init__(project, H, W, fov_up, fov_down) self.reset() self.nclasses = nclasses # number of classes # make semantic colors max_sem_key = 0 for key, data in sem_color_dict.items(): if key + 1 > max_sem_key: max_sem_key = key + 1 self.sem_color_lut = np.zeros((max_sem_key + 100, 3), dtype=np.float32) for key, value in sem_color_dict.items(): self.sem_color_lut[key] = np.array(value, np.float32) / 255.0 # make instance colors max_inst_id = 100000 self.inst_color_lut = np.random.uniform(low=0.0, high=1.0, size=(max_inst_id, 3)) # force zero to a gray-ish color self.inst_color_lut[0] = np.full((3), 0.1) def reset(self): """ Reset scan members. """ super(SemLaserScan, self).reset() # semantic labels self.sem_label = np.zeros((0, 1), dtype=np.uint32) # [m, 1]: label self.sem_label_color = np.zeros((0, 3), dtype=np.float32) # [m ,3]: color # instance labels self.inst_label = np.zeros((0, 1), dtype=np.uint32) # [m, 1]: label self.inst_label_color = np.zeros((0, 3), dtype=np.float32) # [m ,3]: color # projection color with semantic labels self.proj_sem_label = np.zeros((self.proj_H, self.proj_W), dtype=np.int32) # [H,W] label self.proj_sem_color = np.zeros((self.proj_H, self.proj_W, 3), dtype=np.float) # [H,W,3] color # projection color with instance labels self.proj_inst_label = np.zeros((self.proj_H, self.proj_W), dtype=np.int32) # [H,W] label self.proj_inst_color = np.zeros((self.proj_H, self.proj_W, 3), dtype=np.float) # [H,W,3] color def open_label(self, filename): """ Open raw scan and fill in attributes """ # check filename is string if not isinstance(filename, str): raise TypeError("Filename should be string type, " "but was {type}".format(type=str(type(filename)))) # check extension is a laserscan if not any(filename.endswith(ext) for ext in self.EXTENSIONS_LABEL): raise RuntimeError("Filename extension is not valid label file.") # if all goes well, open label label = np.fromfile(filename, dtype=np.uint32) label = label.reshape((-1)) # set it self.set_label(label) def set_label(self, label): """ Set points for label not from file but from np """ # check label makes sense if not isinstance(label, np.ndarray): raise TypeError("Label should be numpy array") # only fill in attribute if the right size if label.shape[0] == self.points.shape[0]: self.sem_label = label & 0xFFFF # semantic label in lower half self.inst_label = label >> 16 # instance id in upper half else: print("Points shape: ", self.points.shape) print("Label shape: ", label.shape) raise ValueError("Scan and Label don't contain same number of points") # sanity check assert((self.sem_label + (self.inst_label << 16) == label).all()) if self.project: self.do_label_projection() def colorize(self): """ Colorize pointcloud with the color of each semantic label """ self.sem_label_color = self.sem_color_lut[self.sem_label] self.sem_label_color = self.sem_label_color.reshape((-1, 3)) self.inst_label_color = self.inst_color_lut[self.inst_label] self.inst_label_color = self.inst_label_color.reshape((-1, 3)) def do_label_projection(self): # only map colors to labels that exist mask = self.proj_idx >= 0 # semantics self.proj_sem_label[mask] = self.sem_label[self.proj_idx[mask]] self.proj_sem_color[mask] = self.sem_color_lut[self.sem_label[self.proj_idx[mask]]] # instances self.proj_inst_label[mask] = self.inst_label[self.proj_idx[mask]] self.proj_inst_color[mask] = self.inst_color_lut[self.inst_label[self.proj_idx[mask]]]
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/eval_np.py
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import numpy as np import time class PanopticEval: """ Panoptic evaluation using numpy authors: Andres Milioto and Jens Behley """ def __init__(self, n_classes, device=None, ignore=None, offset=2**32, min_points=30): self.n_classes = n_classes assert (device == None) self.ignore = np.array(ignore, dtype=np.int64) self.include = np.array([n for n in range(self.n_classes) if n not in self.ignore], dtype=np.int64) print("[PANOPTIC EVAL] IGNORE: ", self.ignore) print("[PANOPTIC EVAL] INCLUDE: ", self.include) self.reset() self.offset = offset # largest number of instances in a given scan self.min_points = min_points # smallest number of points to consider instances in gt self.eps = 1e-15 def num_classes(self): return self.n_classes def reset(self): # general things # iou stuff self.px_iou_conf_matrix = np.zeros((self.n_classes, self.n_classes), dtype=np.int64) # panoptic stuff self.pan_tp = np.zeros(self.n_classes, dtype=np.int64) self.pan_iou = np.zeros(self.n_classes, dtype=np.double) self.pan_fp = np.zeros(self.n_classes, dtype=np.int64) self.pan_fn = np.zeros(self.n_classes, dtype=np.int64) ################################# IoU STUFF ################################## def addBatchSemIoU(self, x_sem, y_sem): # idxs are labels and predictions idxs = np.stack([x_sem, y_sem], axis=0) # make confusion matrix (cols = gt, rows = pred) np.add.at(self.px_iou_conf_matrix, tuple(idxs), 1) def getSemIoUStats(self): # clone to avoid modifying the real deal conf = self.px_iou_conf_matrix.copy().astype(np.double) # remove fp from confusion on the ignore classes predictions # points that were predicted of another class, but were ignore # (corresponds to zeroing the cols of those classes, since the predictions # go on the rows) conf[:, self.ignore] = 0 # get the clean stats tp = conf.diagonal() fp = conf.sum(axis=1) - tp fn = conf.sum(axis=0) - tp return tp, fp, fn def getSemIoU(self): tp, fp, fn = self.getSemIoUStats() # print(f"tp={tp}") # print(f"fp={fp}") # print(f"fn={fn}") intersection = tp union = tp + fp + fn union = np.maximum(union, self.eps) iou = intersection.astype(np.double) / union.astype(np.double) iou_mean = (intersection[self.include].astype(np.double) / union[self.include].astype(np.double)).mean() return iou_mean, iou # returns "iou mean", "iou per class" ALL CLASSES def getSemAcc(self): tp, fp, fn = self.getSemIoUStats() total_tp = tp.sum() total = tp[self.include].sum() + fp[self.include].sum() total = np.maximum(total, self.eps) acc_mean = total_tp.astype(np.double) / total.astype(np.double) return acc_mean # returns "acc mean" ################################# IoU STUFF ################################## ############################################################################## ############################# Panoptic STUFF ################################ def addBatchPanoptic(self, x_sem_row, x_inst_row, y_sem_row, y_inst_row): # make sure instances are not zeros (it messes with my approach) x_inst_row = x_inst_row + 1 y_inst_row = y_inst_row + 1 # only interested in points that are outside the void area (not in excluded classes) for cl in self.ignore: # make a mask for this class gt_not_in_excl_mask = y_sem_row != cl # remove all other points x_sem_row = x_sem_row[gt_not_in_excl_mask] y_sem_row = y_sem_row[gt_not_in_excl_mask] x_inst_row = x_inst_row[gt_not_in_excl_mask] y_inst_row = y_inst_row[gt_not_in_excl_mask] # first step is to count intersections > 0.5 IoU for each class (except the ignored ones) for cl in self.include: # print("*"*80) # print("CLASS", cl.item()) # get a class mask x_inst_in_cl_mask = x_sem_row == cl y_inst_in_cl_mask = y_sem_row == cl # get instance points in class (makes outside stuff 0) x_inst_in_cl = x_inst_row * x_inst_in_cl_mask.astype(np.int64) y_inst_in_cl = y_inst_row * y_inst_in_cl_mask.astype(np.int64) # generate the areas for each unique instance prediction unique_pred, counts_pred = np.unique(x_inst_in_cl[x_inst_in_cl > 0], return_counts=True) id2idx_pred = {id: idx for idx, id in enumerate(unique_pred)} matched_pred = np.array([False] * unique_pred.shape[0]) # print("Unique predictions:", unique_pred) # generate the areas for each unique instance gt_np unique_gt, counts_gt = np.unique(y_inst_in_cl[y_inst_in_cl > 0], return_counts=True) id2idx_gt = {id: idx for idx, id in enumerate(unique_gt)} matched_gt = np.array([False] * unique_gt.shape[0]) # print("Unique ground truth:", unique_gt) # generate intersection using offset valid_combos = np.logical_and(x_inst_in_cl > 0, y_inst_in_cl > 0) offset_combo = x_inst_in_cl[valid_combos] + self.offset * y_inst_in_cl[valid_combos] unique_combo, counts_combo = np.unique(offset_combo, return_counts=True) # generate an intersection map # count the intersections with over 0.5 IoU as TP gt_labels = unique_combo // self.offset pred_labels = unique_combo % self.offset gt_areas = np.array([counts_gt[id2idx_gt[id]] for id in gt_labels]) pred_areas = np.array([counts_pred[id2idx_pred[id]] for id in pred_labels]) intersections = counts_combo unions = gt_areas + pred_areas - intersections ious = intersections.astype(np.float) / unions.astype(np.float) tp_indexes = ious > 0.5 self.pan_tp[cl] += np.sum(tp_indexes) self.pan_iou[cl] += np.sum(ious[tp_indexes]) matched_gt[[id2idx_gt[id] for id in gt_labels[tp_indexes]]] = True matched_pred[[id2idx_pred[id] for id in pred_labels[tp_indexes]]] = True # count the FN self.pan_fn[cl] += np.sum(np.logical_and(counts_gt >= self.min_points, matched_gt == False)) # count the FP self.pan_fp[cl] += np.sum(np.logical_and(counts_pred >= self.min_points, matched_pred == False)) def getPQ(self): # first calculate for all classes sq_all = self.pan_iou.astype(np.double) / np.maximum(self.pan_tp.astype(np.double), self.eps) rq_all = self.pan_tp.astype(np.double) / np.maximum( self.pan_tp.astype(np.double) + 0.5 * self.pan_fp.astype(np.double) + 0.5 * self.pan_fn.astype(np.double), self.eps) pq_all = sq_all * rq_all # then do the REAL mean (no ignored classes) SQ = sq_all[self.include].mean() RQ = rq_all[self.include].mean() PQ = pq_all[self.include].mean() return PQ, SQ, RQ, pq_all, sq_all, rq_all ############################# Panoptic STUFF ################################ ############################################################################## def addBatch(self, x_sem, x_inst, y_sem, y_inst): # x=preds, y=targets ''' IMPORTANT: Inputs must be batched. Either [N,H,W], or [N, P] ''' # add to IoU calculation (for checking purposes) self.addBatchSemIoU(x_sem, y_sem) # now do the panoptic stuff self.addBatchPanoptic(x_sem, x_inst, y_sem, y_inst) if __name__ == "__main__": # generate problem from He paper (https://arxiv.org/pdf/1801.00868.pdf) classes = 5 # ignore, grass, sky, person, dog cl_strings = ["ignore", "grass", "sky", "person", "dog"] ignore = [0] # only ignore ignore class min_points = 1 # for this example we care about all points # generate ground truth and prediction sem_pred = [] inst_pred = [] sem_gt = [] inst_gt = [] # some ignore stuff N_ignore = 50 sem_pred.extend([0 for i in range(N_ignore)]) inst_pred.extend([0 for i in range(N_ignore)]) sem_gt.extend([0 for i in range(N_ignore)]) inst_gt.extend([0 for i in range(N_ignore)]) # grass segment N_grass = 50 N_grass_pred = 40 # rest is sky sem_pred.extend([1 for i in range(N_grass_pred)]) # grass sem_pred.extend([2 for i in range(N_grass - N_grass_pred)]) # sky inst_pred.extend([0 for i in range(N_grass)]) sem_gt.extend([1 for i in range(N_grass)]) # grass inst_gt.extend([0 for i in range(N_grass)]) # sky segment N_sky = 50 N_sky_pred = 40 # rest is grass sem_pred.extend([2 for i in range(N_sky_pred)]) # sky sem_pred.extend([1 for i in range(N_sky - N_sky_pred)]) # grass inst_pred.extend([0 for i in range(N_sky)]) # first instance sem_gt.extend([2 for i in range(N_sky)]) # sky inst_gt.extend([0 for i in range(N_sky)]) # first instance # wrong dog as person prediction N_dog = 50 N_person = N_dog sem_pred.extend([3 for i in range(N_person)]) inst_pred.extend([35 for i in range(N_person)]) sem_gt.extend([4 for i in range(N_dog)]) inst_gt.extend([22 for i in range(N_dog)]) # two persons in prediction, but three in gt N_person = 50 sem_pred.extend([3 for i in range(6 * N_person)]) inst_pred.extend([8 for i in range(4 * N_person)]) inst_pred.extend([95 for i in range(2 * N_person)]) sem_gt.extend([3 for i in range(6 * N_person)]) inst_gt.extend([33 for i in range(3 * N_person)]) inst_gt.extend([42 for i in range(N_person)]) inst_gt.extend([11 for i in range(2 * N_person)]) # gt and pred to numpy sem_pred = np.array(sem_pred, dtype=np.int64).reshape(1, -1) inst_pred = np.array(inst_pred, dtype=np.int64).reshape(1, -1) sem_gt = np.array(sem_gt, dtype=np.int64).reshape(1, -1) inst_gt = np.array(inst_gt, dtype=np.int64).reshape(1, -1) # evaluator evaluator = PanopticEval(classes, ignore=ignore, min_points=1) evaluator.addBatch(sem_pred, inst_pred, sem_gt, inst_gt) pq, sq, rq, all_pq, all_sq, all_rq = evaluator.getPQ() iou, all_iou = evaluator.getSemIoU() # [PANOPTIC EVAL] IGNORE: [0] # [PANOPTIC EVAL] INCLUDE: [1 2 3 4] # TOTALS # PQ: 0.47916666666666663 # SQ: 0.5520833333333333 # RQ: 0.6666666666666666 # IoU: 0.5476190476190476 # Class ignore PQ: 0.0 SQ: 0.0 RQ: 0.0 IoU: 0.0 # Class grass PQ: 0.6666666666666666 SQ: 0.6666666666666666 RQ: 1.0 IoU: 0.6666666666666666 # Class sky PQ: 0.6666666666666666 SQ: 0.6666666666666666 RQ: 1.0 IoU: 0.6666666666666666 # Class person PQ: 0.5833333333333333 SQ: 0.875 RQ: 0.6666666666666666 IoU: 0.8571428571428571 # Class dog PQ: 0.0 SQ: 0.0 RQ: 0.0 IoU: 0.0 print("TOTALS") print("PQ:", pq.item(), pq.item() == 0.47916666666666663) print("SQ:", sq.item(), sq.item() == 0.5520833333333333) print("RQ:", rq.item(), rq.item() == 0.6666666666666666) print("IoU:", iou.item(), iou.item() == 0.5476190476190476) for i, (pq, sq, rq, iou) in enumerate(zip(all_pq, all_sq, all_rq, all_iou)): print("Class", cl_strings[i], "\t", "PQ:", pq.item(), "SQ:", sq.item(), "RQ:", rq.item(), "IoU:", iou.item())
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/SSCDataset.py
import os import numpy as np def unpack(compressed): ''' given a bit encoded voxel grid, make a normal voxel grid out of it. ''' uncompressed = np.zeros(compressed.shape[0] * 8, dtype=np.uint8) uncompressed[::8] = compressed[:] >> 7 & 1 uncompressed[1::8] = compressed[:] >> 6 & 1 uncompressed[2::8] = compressed[:] >> 5 & 1 uncompressed[3::8] = compressed[:] >> 4 & 1 uncompressed[4::8] = compressed[:] >> 3 & 1 uncompressed[5::8] = compressed[:] >> 2 & 1 uncompressed[6::8] = compressed[:] >> 1 & 1 uncompressed[7::8] = compressed[:] & 1 return uncompressed SPLIT_SEQUENCES = { "train": ["00", "01", "02", "03", "04", "05", "06", "07", "09", "10"], "valid": ["08"], "test": ["11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21"] } SPLIT_FILES = { "train": [".bin", ".label", ".invalid", ".occluded"], "valid": [".bin", ".label", ".invalid", ".occluded"], "test": [".bin"] } EXT_TO_NAME = {".bin": "input", ".label": "label", ".invalid": "invalid", ".occluded": "occluded"} VOXEL_DIMS = (256, 256, 32) class SSCDataset: def __init__(self, directory, split="train"): """ Load data from given dataset directory. """ self.files = {} self.filenames = [] for ext in SPLIT_FILES[split]: self.files[EXT_TO_NAME[ext]] = [] for sequence in SPLIT_SEQUENCES[split]: complete_path = os.path.join(directory, "sequences", sequence, "voxels") if not os.path.exists(complete_path): raise RuntimeError("Voxel directory missing: " + complete_path) files = os.listdir(complete_path) for ext in SPLIT_FILES[split]: data = sorted([os.path.join(complete_path, f) for f in files if f.endswith(ext)]) if len(data) == 0: raise RuntimeError("Missing data for " + EXT_TO_NAME[ext]) self.files[EXT_TO_NAME[ext]].extend(data) # this information is handy for saving the data later, since you need to provide sequences/XX/predictions/000000.label: self.filenames.extend( sorted([(sequence, os.path.splitext(f)[0]) for f in files if f.endswith(SPLIT_FILES[split][0])])) self.num_files = len(self.filenames) # sanity check: for k, v in self.files.items(): print(k, len(v)) assert (len(v) == self.num_files) def __len__(self): return self.num_files def __getitem__(self, t): """ fill dictionary with available data for given index . """ collection = {} # read raw data and unpack (if necessary) for typ in self.files.keys(): scan_data = None if typ == "label": scan_data = np.fromfile(self.files[typ][t], dtype=np.uint16) else: scan_data = unpack(np.fromfile(self.files[typ][t], dtype=np.uint8)) # turn in actual voxel grid representation. collection[typ] = scan_data.reshape(VOXEL_DIMS) return self.filenames[t], collection if __name__ == "__main__": # Small example of the usage. # Replace "/path/to/semantic/kitti/" with actual path to the folder containing the "sequences" folder dataset = SSCDataset("/path/to/semantic/kitti/") print("# files: {}".format(len(dataset))) (seq, filename), data = dataset[100] print("Contents of entry 100 (" + seq + ":" + filename + "):") for k, v in data.items(): print(" {:8} : shape = {}, contents = {}".format(k, v.shape, np.unique(v)))
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/shaders/empty.frag
#version 330 core void main() { }
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/shaders/passthrough.frag
#version 330 core in vec4 color; out vec4 out_color; void main() { out_color = color; }
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/shaders/draw_voxels.vert
# version 330 core layout(location = 0) in vec3 in_position; layout(location = 1) in vec3 in_normal; layout(location = 2) in float in_label; // Note: uint with np.uint32 did not work as expected! uniform mat4 mvp; uniform mat4 view_mat; uniform sampler2DRect label_colors; uniform bool use_label_colors; uniform ivec3 voxel_dims; uniform float voxel_size; uniform float voxel_scale; uniform vec3 voxel_color; uniform float voxel_alpha; out vec3 position; out vec3 normal; out vec4 color; void main() { // instance id corresponds to the index in the grid. vec3 idx; idx.x = int(float(gl_InstanceID) / float(voxel_dims.y * voxel_dims.z)); idx.y = int(float(gl_InstanceID - idx.x * voxel_dims.y * voxel_dims.z) / float(voxel_dims.z)); idx.z = int(gl_InstanceID - idx.x * voxel_dims.y * voxel_dims.z - idx.y * voxel_dims.z); // centerize the voxelgrid. vec3 offset = voxel_size * vec3(0, 0.5, 0.5) * voxel_dims; vec3 pos = voxel_scale * voxel_size * (in_position - 0.5); // centerize the voxel coordinates and resize. position = (view_mat * vec4(pos + idx * voxel_size - offset, 1)).xyz; normal = (view_mat * vec4(in_normal, 0)).xyz; uint label = uint(in_label); if(label == uint(0)) // empty voxels gl_Position = vec4(-10, -10, -10, 1); else gl_Position = mvp * vec4(pos + idx * voxel_size - offset, 1); color = vec4(voxel_color, voxel_alpha); if (use_label_colors) color = vec4(texture(label_colors, vec2(label, 0)).rgb, voxel_alpha); }
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/shaders/empty.vert
#version 330 core void main() { }
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/shaders/draw_pose.geom
#version 330 core layout(points) in; layout(line_strip, max_vertices = 6) out; uniform mat4 mvp; uniform mat4 pose; uniform float size; out vec4 color; void main() { color = vec4(1, 0, 0, 1); gl_Position = mvp * pose * vec4(0, 0, 0, 1); EmitVertex(); gl_Position = mvp * pose * vec4(size, 0, 0, 1); EmitVertex(); EndPrimitive(); color = vec4(0, 1, 0, 1); gl_Position = mvp * pose * vec4(0, 0, 0, 1); EmitVertex(); gl_Position = mvp * pose * vec4(0, size, 0, 1); EmitVertex(); EndPrimitive(); color = vec4(0, 0, 1, 1); gl_Position = mvp * pose * vec4(0, 0, 0, 1); EmitVertex(); gl_Position = mvp * pose * vec4(0, 0, size, 1); EmitVertex(); EndPrimitive(); }
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/shaders/draw_voxels.frag
#version 330 core // simple Blinn-Phong Shading. out vec4 out_color; in vec4 color; in vec3 position; in vec3 normal; uniform mat4 view_mat; uniform vec3 lightPos; void main() { vec3 viewPos = view_mat[3].xyz; vec3 ambient = 0.05 * color.xyz; vec3 lightDir = normalize(lightPos - position); vec3 normal1 = normalize(normal); float diff = max(dot(lightDir, normal1), 0.0); vec3 diffuse = diff * color.xyz; vec3 viewDir = normalize(viewPos - position); vec3 reflectDir = reflect(-lightDir, normal); vec3 halfwayDir = normalize(lightDir + viewDir); float spec = pow(max(dot(normal, halfwayDir), 0.0), 32.0); vec3 specular = vec3(0.1) * spec; out_color = vec4(ambient + diffuse + specular, 1.0); }
0
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary
apollo_public_repos/apollo-model-centerpoint/paddle3d/thirdparty/semantic_kitti_api/auxiliary/shaders/check_uniforms.vert
#version 330 core uniform mat4 test; out vec4 color; void main() { float value = float(gl_VertexID); gl_Position = vec4(value/16.0, value/16.0, 0, 1); if(test[int(value/4)][int(value)%4] == value) { color = vec4(0,1,0,1); } else { color = vec4(1,0,0,1); } }
0
apollo_public_repos
apollo_public_repos/apollo-contrib/README.md
# Apollo-contrib Repository This repository is for code not running on the Apollo Computing Unit. Code here will be organized by contributing organizations, and will be covered under difference licenses.
0
apollo_public_repos
apollo_public_repos/apollo-contrib/.clang-format
--- BasedOnStyle: Google --- Language: Cpp Cpp11BracedListStyle: true Standard: Cpp11 CommentPragmas: '^ NOLINT' # Mimic cpplint style IncludeCategories: # Note that the "main" header is priority 0 # The priority is assigned to first match in the ordered list # Miscelaneous system libraries - Regex: '<(immintrin.h|malloc.h|wait.h|x86intrin.h|cuda.*)>' Priority: 3 # C standard libraries - Regex: '<(arpa/|netinet/|net/if|sys/)?[^\./]*\.h>' Priority: 1 # C++ standard libraries - Regex: '<[^/\./]*>' Priority: 2 # Experimental or other system libraries - Regex: '<' Priority: 3 # Test libs - Regex: '"(gtest|gmock)/' Priority: 4 # Protobuf Files - Regex: '\.pb\.h' Priority: 6 # Apollo libs - Regex: '^"(cyber|modules)' Priority: 7 # The rest - Regex: '.*' Priority: 5 ---
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/baidu/Makefile
# # Makefile for Baidu softwares # LIBADV_TRIGGER=src/lib/adv_trigger LIBADV_BCAN=src/lib/bcan ADV_TRIGGER=src/tools/adv_trigger BCAN=src/tools/bcan BASA=src/kernel/drivers/baidu/basa MODULES=$(LIBADV_TRIGGER) $(LIBADV_BCAN) $(ADV_TRIGGER) $(BCAN) $(BASA) MODINSTALL=$(addsuffix .install,$(MODULES)) MODCLEAN=$(addsuffix .clean,$(MODULES)) .PHONY:all $(MODULES) all: $(MODULES) $(MODULES): $(MAKE) -C $@ .PHONY:install $(MODINSTALL) install: $(MODINSTALL) $(MODINSTALL): %.install: $(MAKE) install -C $* .PHONY:clean $(MODCLEAN) clean: $(MODCLEAN) $(MODCLEAN): %.clean: $(MAKE) clean -C $*
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/baidu/README.md
This repository contains code contributed by Baidu to the Apollo Autonomous Driving Project that can't or is not suitable to be distributed under Apache license. Directory structure: - docs/: documentations - src/: source code - lib/adv_trigger: source code of the adv_trigger library - lib/bcan: source code of the bcan library - tools/adv_trigger: source code of the adv_trigger user tool - kernel/include/uapi/linux: header files for writing user programs against the basa driver - kernel/drivers/baidu/basa: source code of the baidu sensor aggregation (basa) driver
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/baidu/build.sh
#!/bin/bash VERSION=$(cat .version | xargs) make clean make install make clean cd output ldconfig -n lib zip -y -r plat-sw-${VERSION}.zip * rm -r bin include lib kernel
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/baidu/.version
3.0.1
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/baidu/license.txt
* To use and redistribute any files here and under, you MUST agree to the following licensing terms. * ======= Licensing terms for all binary files (kernel driver module, library, user space applications) and kernel driver headers: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Copyright (C) 2016 Baidu.com, Inc. All Rights Reserved ======== Licensing terms for all user space source code: Copyright 2017 The Apollo Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
apollo_public_repos/apollo-contrib/baidu
apollo_public_repos/apollo-contrib/baidu/docs/Baidu_CAN_APIs.txt
version 3.0.0.1: The APIs below are meant to be generic and are not tied to any specific CAN hardware. However some of the APIs are specific to Baidu CAN (specifically noted below) and are exposed to advanced users. ====================================================== 1. CAN CHANNEL ACCESS: ====================================================== 1.1) int bcan_open(uint32_t dev_index, uint32_t flags, uint64_t tx_timeout, uint64_t rx_timeout, bcan_hdl_t *hdl) This call will return a logical handle 'hdl' to a physical CAN interface. The CAN channel is identified by 'dev_index' which should correspond to /dev/zcan_pio# (this dev entry name might change in future but should be completely transparent to user). 'tx_timeout' is the timeout in ms for bcan_send(). Set to 0 for no timeout. 'rx_timeout' is the timeout in ms for bcan_recv(). Set to 0 for no timeout. 'flags' is TBD. Return value: 0 on success, error code (see Section 5) on failure. 1.2) int bcan_close(bcan_hdl_t hdl) This call will close the logical handle 'hdl'. Return value: 0 on success, error code (see Section 5) on failure. 1.3) int bcan_start(bcan_hdl_t hdl) This call will initialize the channel and put it in a state ready for transmitting and receiving CAN frames. For Baidu CAN: This will put the card in 'NORMAL' mode. Return value: 0 on success, error code (see Section 5) on failure. 1.4) int bcan_stop(bcan_hdl_t hdl) This call will stop any data from being received or transmitted on this channel. Error counter and status registers will be reset. For Baidu CAN: This will put it in CONFIGURATION mode. Initial state after reset. Error counter and Status registers are reset. Cannot receive or transmit messages. Reads from the RX FIFO and writes to TX FIFO and HPB are ok. Return value: 0 on success, error code (see Section 5) on failure. 1.5) const char* bcan_get_libversion(void) This call return current libbcan version as a string. ====================================================== 2. CHANNEL CONFIGURATION ====================================================== 2.1) int bcan_set_baudrate(bcan_hdl_t hdl, uint32_t rate) Specify 'rate' using one of the below supported values (defined in bcan.h). For e.g. BCAN_BAUDRATE_500K means 500Kbps. BCAN_BAUDRATE_150K BCAN_BAUDRATE_250K BCAN_BAUDRATE_500K BCAN_BAUDRATE_1M Return value: 0 on success, error code (see Section 5) on failure. 2.2) int bcan_get_baudrate(bcan_hdl_t hdl, uint32_t *rate) This call will return the current baudrate in Kbps via 'rate'. Return value: 0 on success, error code (see Section 5) on failure. 2.3) int bcan_set_loopback(bcan_hdl_t hdl) This API will cause all messages sent on Tx to be received on Rx. This is effectively a self-test mode. Note all CAN devices may not support this mode. Return value: 0 on success, error code (see Section 5) on failure. 2.4) int bcan_unset_loopback(bcan_hdl_t hdl) This call will stop the loopback mode and will return the channel to normal operational mode. Return value: 0 on success, error code (see Section 5) on failure. ====================================================== 3. DATA PATH ====================================================== typedef struct bcan_msg { uint32_t bcan_msg_id; // source CAN node id uint8_t bcan_msg_rsv[3]; // reserved for future uint8_t bcan_msg_datalen; // message data length uint8_t bcan_msg_data[8]; // message data struct timeval bcan_msg_timestamp; } bcan_msg_t; 3.1) int bcan_recv(bcan_hdl_t hdl, bcan_msg_t *buf, uint32_t num_msg) This call will return with either the requested number of messages 'num_msg' or the number of available messages in the RX FIFO, which ever is smaller. If Rx FIFO is empty this function will block until at least one message is received. The 'rx_timeout' value specified in bcan_open() will be enforced by this call. Caller is responsible for making sure 'buf' contains enough space for the requested number of messages. 'num_msg' should not exceed BCAN_MAX_RX_MSG. On success this call will return the number of messages received. A error code (see Section 5) is returned on failure. 3.2) int bcan_send(bcan_hdl_t hdl, bcan_msg_t *buf, uint32_t num_msg) 'num_msg' is the number of CAN messages to be sent. 'num_msg' should not exceed BCAN_MAX_TX_MSG. The 'tx_timeout' specified in bcan_open() will be enforced by this call. Return value: On success this call will return the number of messages transmitted. Note that success does not mean message was put on the bus, it simply means message has been enqueued in the Tx FIFO. A error code (see Section 5) is returned on failure. 3.3) int bcan_send_hi_pri(bcan_hdl_t hdl, bcan_msg_t *buf); Baidu CAN specific. Only 1 high priority message can be sent at a time. 'tx_timeout' specified in bcan_open() does not apply to this call. Instead this call will return immediately with either success or failure. Return value: On success this call will return the number of messages transmitted which is 1. A error code (see Section 5) is returned on failure. ====================================================== 4. DIAGNOSTIC: ====================================================== Baidu CAN specific. 4.1) int bcan_get_status(bcan_hdl_t hdl) This call will return the overall status of the channel hardware. A error code (defined in section 5) is returned on error. The following macros are available to retrieve specific fields in the Status register, 'value' is the return value from bcan_get_status(). BCAN_GET_FIFO_STATUS(value) -> returns Acceptance filter status, Tx FIFO and High Priority Buffer status. BCAN_GET_ERR_STATUS(value) -> returns error active, error passive or bus off state. BCAN_GET_BUS_STATUS(value) -> returns Busy or Idle BCAN_GET_MODE_STATUS(value) -> returns Normal, Sleep, Loopback, Configuration 4.2) int bcan_get_err_counter(bcan_hdl_t hdl, uint8_t *rx_err_counter, uint8_t *tx_err_counter) After this call 'rx_err_counter' and 'tx_err_counter' will contain the respective values from the Error Count register. These values are a indicator of the health of the CAN controller and bus. Return value: 0 on success, error code (see Section 5) on failure. ====================================================== 5. Version & Build Info ====================================================== 5.1) const char *bcan_get_libversion(void) Return bcan library version; e.g., "3.0.0.1". ====================================================== 6. Error codes ====================================================== 6.1) const char *bcan_get_err_msg(int err_code); Return error message corresponding to the given error code. 6.2) List of error code; all values below are negative. - BCAN_HDL_INVALID Handle is not valid. - BCAN_DEV_INVALID Device is not in a suitable state for this operation. For e.g. calling bcan_send() without calling bcan_start(). - BCAN_DEV_ERR Device has entered a error state. For e.g. bcan_send() can fail if device has entered 'Bus Off' state. - BCAN_DEV_BUSY Device is busy, re-try after some time. For e.g. setting loopback mode when device is actively transmitting or receiving in normal mode. - BCAN_NOT_SUPPORTED Operation not supported - BCAN_NOT_IMPLEMENTED Operation not implemented. - BCAN_PARAM_INVALID One or more of the input parameters (other than the handle) is not valid. - BCAN_NO_BUFFERS Either a hardware or software buffer is not available for this operation. For e.g. bcan_send() could fail if Tx hardware/software resources are all occupied. - BCAN_ERR Catch-all error
0
apollo_public_repos/apollo-contrib/baidu/src/tools
apollo_public_repos/apollo-contrib/baidu/src/tools/bcan/Makefile
# # Makefile for bcan tools # BAIDUROOT=../../.. CC=gcc CFLAGS=-Wall -march=native -O2 -pipe -static LIB_PATH=../../lib/bcan LIB=$(LIB_PATH)/libadv_bcan.a INC=-I$(BAIDUROOT)/src/kernel/include/uapi -I$(LIB_PATH) LDFLAGS=-L$(LIB_PATH) -ladv_bcan -lpthread CAN_APP_SRC=can_app.c CAN_APP=can_app RADAR_APP_SRC=radar_can_app.c RADAR_APP=radar_can_app .PHONY:all all: $(CAN_APP) $(RADAR_APP) $(CAN_APP): $(CAN_APP_SRC) $(LIB) $(CC) $(CFLAGS) $(INC) -o $(CAN_APP) $(CAN_APP_SRC) $(LDFLAGS) $(RADAR_APP): $(RADAR_APP_SRC) $(LIB) $(CC) $(CFLAGS) $(INC) -o $(RADAR_APP) $(RADAR_APP_SRC) $(LDFLAGS) $(LIB): $(MAKE) -C $(LIB_PATH) .PHONY:install install: all mkdir -p $(BAIDUROOT)/output/bin cp $(CAN_APP) $(BAIDUROOT)/output/bin/ cp $(RADAR_APP) $(BAIDUROOT)/output/bin/ .PHONY:clean clean: rm -f $(CAN_APP) $(RADAR_APP)
0
apollo_public_repos/apollo-contrib/baidu/src/tools
apollo_public_repos/apollo-contrib/baidu/src/tools/bcan/radar_can_app.c
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <getopt.h> #include <unistd.h> #include <string.h> #include <signal.h> #include "bcan.h" #define VERSION "3.0.0.1" #define SHOW_STATS_SEC 300 /* 300s == 5 minutes */ uint64_t gnum_msg = 12; uint64_t gto = 100; /* rx timeout in ms */ int g_err = 0; int baudrate = 1; uint32_t g_rx_id = 1; int print_stats = 0; const char *g_baudrate_desc[BCAN_BAUDRATE_NUM] = { "1Mbps", "500kbps", "250kbps", "150kbps", }; void *rx_func(void *arg); void print_usage(char *name); void print_status(bcan_hdl_t hdl, int id); int configure(bcan_hdl_t *hdl, int channel_id); void do_sigalrm(int sig); struct timespec stats_time_start = {0, 0}; struct timespec stats_time_last = {0, 0}; uint64_t num_msg_last = 0; static int g_keep_running = 1; static void int_handler() { g_keep_running = 0; printf("Program interrupted.\n"); } int main(int argc, char **argv) { bcan_hdl_t hdl; pthread_t rx_thr; struct sigaction sa; extern char *optarg; int c; printf("software version: %s, libbcan version: %s\n", VERSION, bcan_get_libversion()); memset(&sa, 0, sizeof (struct sigaction)); sa.sa_handler = int_handler; sigaction(SIGINT, &sa, NULL); while ((c= getopt(argc, argv, "hb:n:t:d:")) != EOF) { switch (c) { case '?': case 'h': print_usage(argv[0]); return 0; case 'n': gnum_msg = (uint64_t)strtol(optarg, NULL, 10); break; case 'b': baudrate = optarg[0] - '0'; break; case 't': gto = strtol(optarg, NULL, 10); break; case 'd': g_rx_id = optarg[0] - '0'; break; default: printf("wrong arguments\n"); print_usage(argv[0]); return -1; } } if (baudrate < 0 || baudrate >= BCAN_BAUDRATE_NUM) { printf("buadrate setting is wrong, set default baudrate to 500kbps."); baudrate = 1; } printf("baudrate = %s, rx_to = %" PRIu64 ", gnum_msg = %ld, " "rx_channel_id = %" PRIu32 "\n", g_baudrate_desc[baudrate], gto, (int64_t)gnum_msg, g_rx_id); if (configure(&hdl, g_rx_id)) { return -1; } if (pthread_create(&rx_thr, NULL, rx_func, (void *)hdl) != 0) { printf("rx_thr create failed\n"); goto err; } /* enable alarm signal */ if (signal(SIGALRM, do_sigalrm) == SIG_ERR) { printf("register sigalrm failed\n"); goto err; } clock_gettime(CLOCK_MONOTONIC, &stats_time_start); stats_time_last = stats_time_start; alarm(SHOW_STATS_SEC); /* every 5 minutes */ pthread_join(rx_thr, NULL); if (bcan_stop(hdl) != 0) { printf("bcan_stop failed\n"); } err: if (bcan_close(hdl) != 0) { printf("bcan_close failed\n"); } return g_err; } void do_sigalrm(int UNUSED(sig)) { print_stats = 1; alarm(SHOW_STATS_SEC); } /* return time diffrence in second */ static long timespec_diff(struct timespec *start, struct timespec *end) { return (1000000000L * (end->tv_sec - start->tv_sec) + (end->tv_nsec - end->tv_nsec)) / 1000000000L; } static void print_statistics(uint64_t num_msg) { struct timespec stats_time_now = {0, 0}; long timediff_sec_last; long timediff_sec; clock_gettime(CLOCK_MONOTONIC, &stats_time_now); timediff_sec = timespec_diff(&stats_time_start, &stats_time_now); timediff_sec_last = timespec_diff(&stats_time_last, &stats_time_now); if (timediff_sec != 0 && timediff_sec_last != 0) { printf("\n******statistics: total_num_msg=%lu, " "avg# msgs/sec=%0.3f, last msgs/sec=%lu******\n\n", num_msg, ((double)num_msg)/timediff_sec, (num_msg - num_msg_last)/timediff_sec_last); stats_time_last = stats_time_now; num_msg_last = num_msg; } } int configure(bcan_hdl_t *hdl, int channel_id) { int rtn; rtn = bcan_open(channel_id, 0, gto, gto, hdl); if (rtn != 0) { printf("bcan_open failed for channel %d: %s (%d)\n", channel_id, bcan_get_err_msg(rtn), rtn); goto err1; } printf("bcan_open success for channel %d\n", channel_id); rtn = bcan_set_baudrate(*hdl, baudrate); if (rtn != 0) { printf("bcan_set_baudrate failed for channel %d: %s (%d)\n", channel_id, bcan_get_err_msg(rtn), rtn); goto err; } printf("bcan_set_baudrate %s success\n", g_baudrate_desc[baudrate]); rtn = bcan_start(*hdl); if (rtn != 0) { printf("bcan_start failed for channel %d: %s (%d)\n", channel_id, bcan_get_err_msg(rtn), rtn); goto err; } printf("bcan_start success\n"); return 0; err: rtn = bcan_close(*hdl); if (rtn != 0) { printf("bcan_close failed for channel %d: %s (%d)\n", channel_id, bcan_get_err_msg(rtn), rtn); } err1: return -1; } #define STATS_PRINT_NUM 1000 void *rx_func(void *arg) { bcan_hdl_t hdl = (bcan_hdl_t)arg; int j, tmp_num; uint64_t num_msg = 0; uint8_t tx_radiate = 0; bcan_msg_t *buf; bcan_msg_t tmp_buf; buf = malloc(sizeof(bcan_msg_t) * 1024 * 1024); if (!buf) { perror("malloc"); goto err; } while (g_keep_running) { if (!tx_radiate && (num_msg == 10)) { tmp_buf.bcan_msg_datalen = 8; tmp_buf.bcan_msg_id = 0x4f1; tmp_buf.bcan_msg_data[0] = 0; tmp_buf.bcan_msg_data[1] = 0; tmp_buf.bcan_msg_data[2] = 0; tmp_buf.bcan_msg_data[3] = 0; tmp_buf.bcan_msg_data[4] = 0; tmp_buf.bcan_msg_data[5] = 0; tmp_buf.bcan_msg_data[6] = 0xBF; tmp_buf.bcan_msg_data[7] = 0; tx_radiate = 1; if ((tmp_num = bcan_send_hi_pri(hdl, &tmp_buf)) < 0) { printf("TX RADIATE send failed %d\n", tmp_num); g_err = 1; goto err; } printf("TX RADIATE send success %d\n", tmp_num); continue; } if ((tmp_num = bcan_recv(hdl, buf, 1)) < 0) { printf("bcan_recv failed: %s (%d). total msg recvd %d\n", bcan_get_err_msg(tmp_num), tmp_num, (int)num_msg); print_status(hdl, g_rx_id); g_err = 1; goto err; } printf("\tbcan_recv %lu: msg_id 0x%x, datalen %d " "bytes, TS: %ld.%.6ld, data:\n", num_msg, buf->bcan_msg_id, buf->bcan_msg_datalen, buf->bcan_msg_timestamp.tv_sec, buf->bcan_msg_timestamp.tv_usec); printf("\t\t"); for (j = 0; j < buf->bcan_msg_datalen; j++) { printf("0x%x ", buf->bcan_msg_data[j]); } printf("\n"); num_msg++; if (print_stats != 0) { print_statistics(num_msg); print_stats = 0; } if (num_msg >= gnum_msg) { break; } } err: print_statistics(num_msg); print_status(hdl, g_rx_id); if (g_err) { printf("TEST FAILED\n"); } else { printf("TEST PASSED\n"); } if (buf) { free(buf); } pthread_exit(NULL); } void print_status(bcan_hdl_t hdl, int id) { int status; uint8_t rx_err, tx_err; if ((status = bcan_get_status(hdl)) < 0) { printf("%s: channel %d, bcan_get_status() error: %s (%d)\n", __func__, id, bcan_get_err_msg(status), status); } else { printf("Channel %d: status reg 0x%x\n", id, status); } if ((status = bcan_get_err_counter(hdl, &rx_err, &tx_err)) < 0) { printf("%s: channel %d, bcan_get_err_counter() error: %s (%d)\n", __func__, id, bcan_get_err_msg(status), status); } else { printf("Channel %d: rx_err_counter %d, tx_err_counter %d\n", id, rx_err, tx_err); } } void print_usage(char *name) { printf("Usage: %s -d < > -n < > -t < > -b < > -v\n" "\t-d -> specify Rx channel id. e.g. -d 1 (Rx on 1)\n" "\t-n -> specify number of messages to be received. (-1 for ever)\n" "\t-t -> specify Rx timeout value in ms (decimal)\n" "\t-b -> specify baudrate " "(0 -> 1Mbps, 1 -> 500Kbps, 2 -> 250Kbps, 3 -> 150Kbps)\n", name); }
0
apollo_public_repos/apollo-contrib/baidu/src/tools
apollo_public_repos/apollo-contrib/baidu/src/tools/bcan/can_app.c
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <getopt.h> #include <unistd.h> #include <string.h> #include <signal.h> #include "bcan.h" #define VERSION "3.0.0.1" #define RX_THREAD_WAIT_MS 10 /* in ms */ #define TEST_STD_FRAME_ID 0x72 #define TEST_EXT_FRAME_ID 0x18ff84a9 #define TEST_DATA_LEN 8 int gnum_msg = 9; int is_loopback = 0; uint64_t g_txto = 10; /* tx timeout in ms */ uint64_t g_rxto = 100; /* rx timeout in ms */ uint64_t g_val = 0xAB; int g_err = 0; uint32_t g_tx_id = 0; uint32_t g_rx_id = 1; int g_debug = 0; int g_ext_frame = 0; void *tx_func(void *arg); void *rx_func(void *arg); void print_usage(char *name); void print_status(bcan_hdl_t hdl, int id, const char *prefix); int configure(bcan_hdl_t *hdl, int channel_id); pthread_mutex_t plock; static int g_num_sent = 0; static int g_num_recv = 0; static int g_tx_running = 0; static int g_rx_running = 0; static int tx_err = 0; static int rx_err = 0; #define xprintf(...) \ pthread_mutex_lock(&plock); \ printf(__VA_ARGS__); \ pthread_mutex_unlock(&plock); static void int_handler() { g_tx_running = 0; printf("Program interrupted.\n"); } int main(int argc, char **argv) { bcan_hdl_t hdl, hdl2; pthread_t tx_thr1, rx_thr1; struct sigaction sa; extern char *optarg; int num; int c; printf("software version: %s, libbcan version: %s\n", VERSION, bcan_get_libversion()); memset(&sa, 0, sizeof (struct sigaction)); sa.sa_handler = int_handler; sigaction(SIGINT, &sa, NULL); while ((c= getopt(argc, argv, "hln:t:d:eD")) != EOF) { switch (c) { case '?': case 'h': print_usage(argv[0]); return 0; case 'l': is_loopback = 1; break; case 'n': gnum_msg = strtol(optarg, NULL, 10); if (gnum_msg > BCAN_MAX_TX_MSG) { printf("wrong value specified in -n option: " "exceed BCAN_MAX_TX_MSG %d\n", BCAN_MAX_TX_MSG); return -1; } break; case 't': g_txto = strtol(optarg, NULL, 10); break; case 'd': g_tx_id = optarg[0] - '0'; g_rx_id = optarg[1] - '0'; break; case 'D': g_debug = 1; break; case 'e': g_ext_frame = 1; break; default: printf("unsupported argument\n"); print_usage(argv[0]); return -1; } } if (is_loopback) { g_rx_id = g_tx_id; } num = (gnum_msg <= 0) ? 1 : gnum_msg; g_rxto = g_txto * num + RX_THREAD_WAIT_MS; printf("is_loopback = %d, baudrate = 500kbps, tx_to = %" PRIu64 "ms, " "gnum_msg = %" PRId32 ", tx_channel_id = %" PRIu32 ", rx_channel_id = %" PRIu32 "\n", is_loopback, g_txto, gnum_msg, g_tx_id, g_rx_id); if (configure(&hdl, g_tx_id)) { printf("configure Tx channel %" PRIu32 " failed.\n", g_tx_id); return -1; } if (!is_loopback && configure(&hdl2, g_rx_id)) { bcan_close(hdl); printf("configure Rx channel %" PRIu32 " failed.\n", g_rx_id); return -1; } if (pthread_create(&rx_thr1, NULL, rx_func, ((is_loopback) ? (void *)hdl : (void *)hdl2)) != 0) { printf("rx_thr create failed\n"); goto err; } if (pthread_create(&tx_thr1, NULL, tx_func, (void *)hdl) != 0) { printf("tx_thr create failed\n"); goto err; } pthread_join(tx_thr1, NULL); pthread_join(rx_thr1, NULL); if (bcan_stop(hdl) != 0) { printf("bcan_stop hdl failed\n"); } if (!is_loopback && (bcan_stop(hdl2) != 0)) { printf("bcan_stop hdl2 failed\n"); } if (g_err) { printf("TEST FAILED\n"); } else { printf("TEST PASSED\n"); } err: if (bcan_close(hdl) != 0) { printf("bcan_close hdl failed\n"); } if (!is_loopback && (bcan_close(hdl2) != 0)) { printf("bcan_close hdl2 failed\n"); } return tx_err + rx_err; } int configure(bcan_hdl_t *hdl, int channel_id) { int rtn; rtn = bcan_open(channel_id, 0, g_txto, g_rxto, hdl); if (rtn != 0) { printf("bcan_open failed for channel %d: %s (%d)\n", channel_id, bcan_get_err_msg(rtn), rtn); goto err1; } printf("bcan_open success for channel %d\n", channel_id); rtn = bcan_set_baudrate(*hdl, BCAN_BAUDRATE_500K); if (rtn != 0) { printf("bcan_set_baudrate failed for channel %d: %s (%d)\n", channel_id, bcan_get_err_msg(rtn), rtn); goto err; } printf("bcan_set_baudrate 500kbps success\n"); rtn = bcan_start(*hdl); if (rtn != 0) { printf("bcan_start failed for channel %d: %s (%d)\n", channel_id, bcan_get_err_msg(rtn), rtn); goto err; } printf("bcan_start success\n"); if (is_loopback) { rtn = bcan_set_loopback(*hdl); if (rtn != 0) { printf("bcan_set_loopback failed for channel %d: %s (%d)\n", channel_id, bcan_get_err_msg(rtn), rtn); goto err; } printf("bcan_set_loopback success\n"); } return 0; err: rtn = bcan_close(*hdl); if (rtn != 0) { printf("bcan_close failed for channel %d: %s (%d)\n", channel_id, bcan_get_err_msg(rtn), rtn); } err1: return -1; } static void check_messages(bcan_msg_t *buf, int num) { bcan_msg_t *msg; uint32_t msgid; uint8_t tmp_val; int i, j; if (g_ext_frame) { msgid = TEST_EXT_FRAME_ID | BCAN_EXTENDED_FRAME; } else { msgid = TEST_STD_FRAME_ID; } tmp_val = g_val + ((g_num_recv - num) * TEST_DATA_LEN); pthread_mutex_lock(&plock); for (i = 0; i < num; i++) { msg = buf + i; printf("\tbcan_recv: start_of_msg %d\n", i + 1); printf("\tbcan_recv: msg_id 0x%x", msg->bcan_msg_id); if (msg->bcan_msg_id != msgid) { printf("[ERR]"); g_err = 1; } printf(", datalen %d bytes, TS: %ld.%06ld, data:\n", msg->bcan_msg_datalen, msg->bcan_msg_timestamp.tv_sec, msg->bcan_msg_timestamp.tv_usec); printf("\t\t"); for (j = 0; j < msg->bcan_msg_datalen; j++) { printf("0x%02x ", msg->bcan_msg_data[j]); if (msg->bcan_msg_data[j] != tmp_val++) { printf("[ERR] "); g_err = 1; } if (msg->bcan_msg_data[j] == 0xFF) { tmp_val = 0; } } printf("\n\tbcan_recv: end_of_msg %d\n", i + 1); } pthread_mutex_unlock(&plock); } void *tx_func(void *arg) { bcan_hdl_t hdl = (bcan_hdl_t)arg; int i, j, num_msg, c; uint8_t tmp_val; uint32_t msgid; bcan_msg_t *buf, *msg; struct timespec ts; buf = malloc(sizeof(bcan_msg_t) * 1024 * 1024); if (!buf) { perror("malloc"); goto err; } tmp_val = g_val; if (g_ext_frame) { msgid = TEST_EXT_FRAME_ID | BCAN_EXTENDED_FRAME; } else { msgid = TEST_STD_FRAME_ID; } while (!g_rx_running) { usleep(1000); } // Wait a little bit to make sure RX runs before TX does. If TX runs // first, the message transmitted may be received by driver before // RX actually runs and then RX won't receive anything and times-out. // Sleep of 10ms is not bullet-proof (in making sure RX runs first) // in theory, but it will be extremely rare for TX to race ahead of RX // after the sleep. usleep(RX_THREAD_WAIT_MS * 1000); xprintf("tx thread started, transmitting %" PRId32 " messages, data starts with 0x%x\n", gnum_msg, tmp_val); num_msg = (gnum_msg <= 0) ? 1: gnum_msg; g_tx_running = 1; while (g_tx_running) { msg = buf; for (i = 0; i < num_msg; i++, msg++) { msg->bcan_msg_id = msgid; msg->bcan_msg_datalen = TEST_DATA_LEN; for (j = 0 ; j < msg->bcan_msg_datalen; j++) { msg->bcan_msg_data[j] = tmp_val++; } if (tmp_val == 0xFF) { tmp_val = 0; } } if ((c = bcan_send(hdl, buf, num_msg)) < 0) { xprintf("bcan_send failed: %s (%d), total msg sent %d\n", bcan_get_err_msg(c), c, g_num_sent); ++tx_err; goto err; } clock_gettime(CLOCK_REALTIME, &ts); g_num_sent += c; xprintf("bcan_send: sent %d msg, total msg sent %d, TS: %ld.%06ld\n", c, g_num_sent, ts.tv_sec, ts.tv_nsec / 1000); if (c < num_msg) { xprintf("bcan_send: not enough msg sent, expect %d\n", num_msg); g_tx_running = 0; } if ((gnum_msg > 0) && (g_num_sent >= gnum_msg)) { g_tx_running = 0; } } err: print_status(hdl, g_tx_id, "bcan_send"); if (buf) { free(buf); } pthread_exit(NULL); } void *rx_func(void *arg) { bcan_hdl_t hdl = (bcan_hdl_t)arg; int c, num_msg; bcan_msg_t *buf; buf = malloc(sizeof(bcan_msg_t) * 1024 * 1024); if (!buf) { perror("malloc"); goto err; } xprintf("rx thread started, to receive %" PRId32 " msgs\n", gnum_msg); num_msg = (gnum_msg <= 0) ? 1 : gnum_msg; g_rx_running = 1; while (1) { if ((gnum_msg > 0) && (g_num_recv == gnum_msg)) { break; } if ((c = bcan_recv(hdl, buf, num_msg)) < 0) { if (gnum_msg <= 0) { if (!g_tx_running && !g_debug) { goto err; } } else { xprintf("bcan_recv failed: %s (%d). total msg recvd %d\n", bcan_get_err_msg(c), c, g_num_recv); ++rx_err; g_err = 1; if (!g_debug) { goto err; } } continue; } g_num_recv += c; xprintf("bcan_recv: recvd %d msg, total msg recvd %d\n", c, g_num_recv); check_messages(buf, c); if (c < num_msg) { xprintf("bcan_recv: not enough msg recvd, expect %d\n", num_msg); num_msg -= c; } else { num_msg = (gnum_msg <= 0) ? 1 : gnum_msg; } } err: g_rx_running = 0; print_status(hdl, g_rx_id, "bcan_recv"); if (buf) { free(buf); } pthread_exit(NULL); } void print_status(bcan_hdl_t hdl, int id, const char *prefix) { int status; uint8_t rx_err, tx_err; pthread_mutex_lock(&plock); if ((status = bcan_get_status(hdl)) < 0) { printf("%s: channel %d, bcan_get_status() error: %s (%d)\n", prefix, id, bcan_get_err_msg(status), status); } else { printf("%s: channel %d, status reg 0x%x\n", prefix, id, status); } if ((status = bcan_get_err_counter(hdl, &rx_err, &tx_err)) < 0) { printf("%s: channel %d, bcan_get_err_counter() error: %s (%d)\n", prefix, id, bcan_get_err_msg(status), status); } else { printf("%s: channel %d, rx_err_counter %d, tx_err_counter %d\n", prefix, id, rx_err, tx_err); } pthread_mutex_unlock(&plock); } void print_usage(char *name) { printf("Usage: %s -l -d < > -n < > -t < > -e -v\n" "\t-l -> Loopback mode\n" "\t-d -> Tx and Rx channel id. e.g. -d 10 (Tx on 1 and Rx on 0)\n" "\t-n -> Number of messages to be transmitted (Maximum %d)\n" "\t-t -> Tx timeout value in ms\n" "\t-e -> Use extended frames\n", name, BCAN_MAX_TX_MSG); }
0
apollo_public_repos/apollo-contrib/baidu/src/tools
apollo_public_repos/apollo-contrib/baidu/src/tools/adv_trigger/Makefile
# # Makefile for adv_trigger tool # BAIDUROOT=../../.. CC=gcc CFLAGS=-Wall -march=native -O2 -pipe -static LIB_PATH=../../lib/adv_trigger LIB=$(LIB_PATH)/libadv_trigger.a INC=$(BAIDUROOT)/src/kernel/include/uapi SRC=adv_trigger.c OBJ=adv_trigger .PHONY:all all: $(OBJ) $(OBJ): $(SRC) $(LIB) $(CC) $(CFLAGS) -I$(INC) -I$(LIB_PATH) -o $(OBJ) -L$(LIB_PATH) $(SRC) -ladv_trigger $(LIB): $(MAKE) -C $(LIB_PATH) .PHONY:install install: all mkdir -p $(BAIDUROOT)/output/bin cp $(OBJ) $(BAIDUROOT)/output/bin/ .PHONY:clean clean: rm -f $(OBJ)
0
apollo_public_repos/apollo-contrib/baidu/src/tools
apollo_public_repos/apollo-contrib/baidu/src/tools/adv_trigger/adv_trigger.c
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include "linux/zynq_api.h" #include "adv_trigger.h" #define VERSION "3.0.0.1" static int check_status() { struct adv_trigger_status s; zynq_trigger_t *t; char video_name[16]; int i, j; int ret; if ((ret = adv_trigger_get_status(&s))) { return ret; } printf("\n"); for (i = 0; i < ZYNQ_TRIGGER_DEV_NUM; ++i) { if (s.status[i].zdev_name[0] == '\0') { continue; } printf("%s:\n", s.status[i].zdev_name); printf(" GPS: %s, PPS: %s\n", (s.status[i].flags & FLAG_GPS_VALID) ? "Locked" : "No", (s.status[i].flags & FLAG_PPS_VALID) ? "OK" : "No"); for (j = 0; j < ZYNQ_FPD_TRIG_NUM; j++) { t = &s.status[i].fpd_triggers[j]; if (t->vnum < 0) { continue; } sprintf(video_name, "video%d ", t->vnum); printf("%6d: FPS %2d, %s %s%s%s\n", t->id, t->fps, (t->enabled) ? " Enabled" : "Disabled", (t->internal) ? "internal " : "", video_name, t->name); } } return 0; } int main(int argc, char * const argv[]) { int opt; char *dev_path = NULL; int enable_trigger = 1; int internal = 0; int fps = 0; int ret; printf("software version: %s, adv_trigger lib version: %s\n", VERSION, adv_trigger_version()); while ((opt = getopt(argc, argv, "deishf:v")) != -1) { switch (opt) { case 'd': /* disable trigger */ enable_trigger = 0; break; case 'e': /* enable trigger */ enable_trigger = 1; break; case 'i': internal = 1; break; case 's': return check_status(); case 'f': /* fps value is in decimal */ fps = atoi(optarg); if (fps < 0) { printf("adv_trigger: invalid fps %d, " "please run 'adv_trigger -h' for help.\n", fps); return -1; } break; case 'h': printf("Usage: %s [options] [<video_path>]\n", argv[0]); printf("\t[<video_path>]: video device file path. All " "video devices are operated if not specified.\n"); printf("\t[-d]: disable trigger\n"); printf("\t[-e]: enable trigger\n"); printf("\t[-i]: use internal FPGA PPS\n"); printf("\t[-s]: trigger status\n"); printf("\t[-f <FPS>]: specify FPS (frame-per-second)\n" "\t Valid FPS (USB): 0 ~ 30 (default 30)\n" "\t Valid FPS (FPD-Link): 0 ~ 20 (default 10)\n" "\t (0 sets FPS to the default value)\n"); printf("\t[-h]: this message\n"); return 0; case 'v': return 0; default: printf("adv_trigger: bad parameter\n"); return -1; } } if (optind < argc) { dev_path = argv[optind]; } if (enable_trigger) { ret = adv_trigger_enable(dev_path, fps, internal); } else { ret = adv_trigger_disable(dev_path); } return ret; }
0
apollo_public_repos/apollo-contrib/baidu/src/lib
apollo_public_repos/apollo-contrib/baidu/src/lib/bcan/bcan_lib.c
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <syslog.h> #include <unistd.h> #include <string.h> #include <sys/ioctl.h> #include <sys/stat.h> #include "linux/zynq_api.h" #include "bcan.h" #ifdef DEBUG #define BLOG_DBG(s...) syslog(LOG_DEBUG, s) #else #define BLOG_DBG(s...) do {} while (0) #endif #define BLOG_ERR(s...) syslog(LOG_ERR, s) typedef struct bcan_ihdl { int dev_index; int dev_state; int fd; uint32_t baudrate; uint32_t tx_to; uint32_t rx_to; } bcan_ihdl_t; const char *bcan_get_libversion(void) { return LIB_VER; } const char *bcan_get_err_msg(int err_code) { switch (err_code) { case BCAN_PARAM_INVALID: return "invalid parameter"; case BCAN_HDL_INVALID: return "invalid bcan handle"; case BCAN_DEV_INVALID: return "invalid bcan device"; case BCAN_DEV_ERR: return "bcan device error"; case BCAN_DEV_BUSY: return "bcan device busy"; case BCAN_TIMEOUT: return "bcan timeout"; case BCAN_FAIL: return "bcan operation failed"; case BCAN_NOT_SUPPORTED: return "bcan operation not supported"; case BCAN_NOT_IMPLEMENTED: return "bcan operation not implemented"; case BCAN_INVALID: return "bcan invalid error"; case BCAN_NO_BUFFERS: return "failed to allocate bcan buffers"; case BCAN_ERR: return "generic bcan error, check error log"; case BCAN_OK: return "OK"; /* 0 */ case BCAN_PARTIAL_OK: return "bcan IO partial completion"; default: return "undefined error code"; } } /* * Check if transition from current state to proposed state is valid. * Also sanity check for handle. */ static int bcan_check_state(bcan_ihdl_t *ahdl, int pstate) { bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; int cstate, err = BCAN_OK; if (!hdl) { return (BCAN_HDL_INVALID); } cstate = hdl->dev_state; switch (pstate) { case BCAN_DEV_OPEN: if (cstate != BCAN_DEV_UNINIT) { err = BCAN_DEV_INVALID; } break; case BCAN_DEV_BAUD_SET: case BCAN_DEV_LOOPBACK: if (!(cstate & BCAN_DEV_OPEN)) { err = BCAN_DEV_INVALID; } break; case BCAN_DEV_START: if (!(cstate & BCAN_DEV_BAUD_SET)) { err = BCAN_DEV_INVALID; } break; case BCAN_DEV_ACTIVE: case BCAN_DEV_STOP: if (!(cstate & BCAN_DEV_START)) { err = BCAN_DEV_INVALID; } break; case BCAN_DEV_CLOSE: if (!(cstate & BCAN_DEV_OPEN)) { err = BCAN_DEV_INVALID; } break; default: break; } BLOG_DBG("%s: dev_index %d, cstate %d, pstate %d, err %d\n", __func__, hdl->dev_index, cstate, pstate, err); return (err); } int bcan_open(uint32_t dev_index, uint32_t UNUSED(flags), uint64_t tx_to, uint64_t rx_to, bcan_hdl_t *ahdl) { char dev_path[256]; int fd, ret; bcan_ihdl_t *hdl; snprintf(dev_path, sizeof(dev_path), "/dev/%s%u", ZYNQ_DEV_NAME_CAN, dev_index); if ((fd = open(dev_path, O_RDWR)) == -1) { BLOG_ERR("%s open() failure: %s\n", dev_path, strerror(errno)); ret = BCAN_PARAM_INVALID; return ret; } BLOG_DBG("%s open() success. fd %d\n", dev_path, fd); hdl = (bcan_ihdl_t *)malloc(sizeof(bcan_ihdl_t)); if (!hdl) { BLOG_ERR("malloc() failure: %s\n", strerror(errno)); ret = BCAN_NO_BUFFERS; goto err; } if (ioctl(fd, ZYNQ_IOC_CAN_TX_TIMEOUT_SET, tx_to) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_TX_TIMEOUT %ld failed\n", __func__, dev_index, tx_to); ret = BCAN_PARAM_INVALID; goto err; } if (ioctl(fd, ZYNQ_IOC_CAN_RX_TIMEOUT_SET, rx_to) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_RX_TIMEOUT %ld failed\n", __func__, dev_index, rx_to); ret = BCAN_PARAM_INVALID; goto err; } hdl->dev_state = BCAN_DEV_OPEN; hdl->dev_index = dev_index; hdl->fd = fd; *ahdl = (uintptr_t)(const void *)hdl; return BCAN_OK; err: if (hdl) { free(hdl); } close(fd); return ret; } int bcan_close(bcan_hdl_t ahdl) { int ret; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; if ((ret = bcan_check_state(hdl, BCAN_DEV_CLOSE)) != BCAN_OK) { goto err; } BLOG_DBG("%s: dev_index %d, dev_state %d, fd %d\n", __func__, hdl->dev_index, hdl->dev_state, hdl->fd); close(hdl->fd); hdl->dev_state = BCAN_DEV_CLOSE; free(hdl); err: return ret; } int bcan_set_baudrate(bcan_hdl_t ahdl, uint32_t rate) { int ret = BCAN_OK; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; if ((ret = bcan_check_state(hdl, BCAN_DEV_BAUD_SET)) != BCAN_OK) { goto err; } if (ioctl(hdl->fd, ZYNQ_IOC_CAN_BAUDRATE_SET, rate) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_SET_BAUDRATE failed\n", __func__, hdl->dev_index); ret = BCAN_ERR; goto err; } hdl->dev_state |= BCAN_DEV_BAUD_SET; hdl->baudrate = rate; err: return ret; } int bcan_get_baudrate(bcan_hdl_t ahdl, uint32_t *rate) { int ret = BCAN_OK; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; if (ioctl(hdl->fd, ZYNQ_IOC_CAN_BAUDRATE_GET, rate) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_GET_BAUDRATE failed\n", __func__, hdl->dev_index); ret = BCAN_ERR; goto err1; } if (hdl->baudrate != *rate) { BLOG_ERR("%s: dev_index %d, baudrate %d and cached rate %d " "disagree\n", __func__, hdl->dev_index, *rate, hdl->baudrate); } err1: return ret; } int bcan_set_loopback(bcan_hdl_t ahdl) { int ret = BCAN_OK; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; if ((ret = bcan_check_state(hdl, BCAN_DEV_LOOPBACK)) != BCAN_OK) { goto err; } if (ioctl(hdl->fd, ZYNQ_IOC_CAN_LOOPBACK_SET, NULL) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_SET_LOOPBACK failed\n", __func__, hdl->dev_index); ret = BCAN_ERR; goto err; } hdl->dev_state &= ~BCAN_DEV_NORMAL; hdl->dev_state |= BCAN_DEV_LOOPBACK; err: return ret; } int bcan_unset_loopback(bcan_hdl_t ahdl) { int ret = BCAN_OK; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; if ((ret = bcan_check_state(hdl, -1)) != BCAN_OK) { goto err; } if (ioctl(hdl->fd, ZYNQ_IOC_CAN_LOOPBACK_UNSET, NULL) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_UNSET_LOOPBACK failed\n", __func__, hdl->dev_index); ret = BCAN_ERR; goto err; } hdl->dev_state &= ~BCAN_DEV_LOOPBACK; hdl->dev_state |= BCAN_DEV_NORMAL; err: return ret; } int bcan_recv(bcan_hdl_t ahdl, bcan_msg_t *buf, uint32_t num_msg) { int i, j, ret = BCAN_OK; bcan_msg_t *lbuf; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; ioc_bcan_msg_t ioc_hdl; ioc_hdl.ioc_msgs = buf; ioc_hdl.ioc_msg_num = num_msg; if ((num_msg == 0) || (num_msg > BCAN_MAX_RX_MSG)) { ret = BCAN_PARAM_INVALID; goto err; } if ((ret = bcan_check_state(hdl, BCAN_DEV_ACTIVE)) != BCAN_OK) { goto err; } /* * If this is the first recv after handle open then set rx_clear so * stale data can be flushed by the driver */ if (!(hdl->dev_state & BCAN_DEV_RECVD)) { hdl->dev_state |= BCAN_DEV_RECVD; ioc_hdl.ioc_msg_rx_clear = 1; } else { ioc_hdl.ioc_msg_rx_clear = 0; } if (ioctl(hdl->fd, ZYNQ_IOC_CAN_RECV, &ioc_hdl) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_RECV failed. msg_err %d\n", __func__, hdl->dev_index, ioc_hdl.ioc_msg_err); ret = BCAN_ERR; goto err; } else { BLOG_DBG("%s: dev_index %d, IOC_BCAN_RECV success. msg_num_done %d. " "msg_err %d addr %p\n", __func__, hdl->dev_index, ioc_hdl.ioc_msg_num_done, ioc_hdl.ioc_msg_err, buf); for (i = 0, lbuf = buf; i < (int)ioc_hdl.ioc_msg_num_done; i++, lbuf++) { BLOG_DBG("bcan_recv: start_of_msg %d\n", i + 1); BLOG_DBG("bcan_recv: msg_id 0x%x, datalen %d bytes, data:\n", lbuf->bcan_msg_id, lbuf->bcan_msg_datalen); for (j = 0; j < (buf + i)->bcan_msg_datalen; j++) { BLOG_DBG("0x%x\n", lbuf->bcan_msg_data[j]); } BLOG_DBG("bcan_recv: end_of_msg %d\n", i + 1); } } if (ioc_hdl.ioc_msg_num_done > 0) { return ioc_hdl.ioc_msg_num_done; } else { return ioc_hdl.ioc_msg_err; } err: return ret; } int bcan_send(bcan_hdl_t ahdl, bcan_msg_t *buf, uint32_t num_msg) { int i, j, ret = BCAN_OK; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; ioc_bcan_msg_t ioc_hdl; ioc_hdl.ioc_msgs = buf; ioc_hdl.ioc_msg_num = num_msg; if ((num_msg == 0) || (num_msg > BCAN_MAX_TX_MSG)) { ret = BCAN_PARAM_INVALID; goto err; } if ((ret = bcan_check_state(hdl, BCAN_DEV_ACTIVE)) != BCAN_OK) { goto err; } for (i = 0; i < (int)ioc_hdl.ioc_msg_num; i++) { BLOG_DBG("bcan_send: start_of_msg %d\n", i + 1); BLOG_DBG("bcan_send: msg_id 0x%x, datalen %d bytes, data:\n", (buf + i)->bcan_msg_id, (buf + i)->bcan_msg_datalen); for (j = 0; j < (buf + i)->bcan_msg_datalen; j++) { BLOG_DBG("0x%x\n", (buf + i)->bcan_msg_data[j]); } BLOG_DBG("bcan_send: end_of_msg %d\n", i + 1); } if (ioctl(hdl->fd, ZYNQ_IOC_CAN_SEND, &ioc_hdl) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_SEND failed. msg_err %d\n", __func__, hdl->dev_index, ioc_hdl.ioc_msg_err); ret = BCAN_ERR; goto err; } else { BLOG_DBG("%s: dev_index %d, IOC_BCAN_SEND success. msg_num_done %d\n", __func__, hdl->dev_index, ioc_hdl.ioc_msg_num_done); } if (ioc_hdl.ioc_msg_num_done > 0) { return ioc_hdl.ioc_msg_num_done; } else { return ioc_hdl.ioc_msg_err; } err: return ret; } int bcan_send_hi_pri(bcan_hdl_t ahdl, bcan_msg_t *buf) { int j, ret = BCAN_OK; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; ioc_bcan_msg_t ioc_hdl; if ((ret = bcan_check_state(hdl, BCAN_DEV_ACTIVE)) != BCAN_OK) { goto err; } ioc_hdl.ioc_msgs = buf; ioc_hdl.ioc_msg_num = 1; BLOG_DBG("%s: start_of_msg\n", __func__); BLOG_DBG("%s: msg_id 0x%x, datalen %d bytes, data:\n", __func__, buf->bcan_msg_id, buf->bcan_msg_datalen); for (j = 0; j < buf->bcan_msg_datalen; j++) { BLOG_DBG("0x%x\n", buf->bcan_msg_data[j]); } BLOG_DBG("%s: end_of_msg\n", __func__); if (ioctl(hdl->fd, ZYNQ_IOC_CAN_SEND_HIPRI, &ioc_hdl) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_SEND_HIPRI failed. msg_err %d\n", __func__, hdl->dev_index, ioc_hdl.ioc_msg_err); ret = BCAN_ERR; goto err; } else { BLOG_DBG("%s: dev_index %d, IOC_BCAN_SEND_HIPRI success. " "msg_num_done %d\n", __func__, hdl->dev_index, ioc_hdl.ioc_msg_num_done); } if (ioc_hdl.ioc_msg_num_done == 1) return (1); else return (ioc_hdl.ioc_msg_err); err: return ret; } int bcan_start(bcan_hdl_t ahdl) { bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; int ret = BCAN_OK; if ((ret = bcan_check_state(hdl, BCAN_DEV_START)) != BCAN_OK) { goto err; } if (ioctl(hdl->fd, ZYNQ_IOC_CAN_DEV_START, NULL) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_START failed\n", __func__, hdl->dev_index); ret = BCAN_ERR; goto err; } hdl->dev_state |= BCAN_DEV_START; err: return ret; } int bcan_stop(bcan_hdl_t ahdl) { int ret = BCAN_OK; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; if ((ret = bcan_check_state(hdl, BCAN_DEV_STOP)) != BCAN_OK) { goto err; } if (ioctl(hdl->fd, ZYNQ_IOC_CAN_DEV_STOP, NULL) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_STOP failed\n", __func__, hdl->dev_index); goto err; } hdl->dev_state |= BCAN_DEV_STOP; hdl->dev_state &= ~BCAN_DEV_START; err: return ret; } int bcan_get_status(bcan_hdl_t ahdl) { ioc_bcan_status_err_t st_err; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; int ret = BCAN_OK; if ((ret = bcan_check_state(hdl, -1)) != BCAN_OK) { goto err; } if (ioctl(hdl->fd, ZYNQ_IOC_CAN_GET_STATUS_ERR, &st_err) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_GET_STATUS_ERR failed\n", __func__, hdl->dev_index); ret = BCAN_ERR; goto err; } return ((int)st_err.bcan_status); err: return ret; } int bcan_get_err_counter(bcan_hdl_t ahdl, uint8_t *rx_err, uint8_t *tx_err) { ioc_bcan_status_err_t st_err; bcan_ihdl_t *hdl = (bcan_ihdl_t *)ahdl; int ret = BCAN_OK; if ((ret = bcan_check_state(hdl, -1)) != BCAN_OK) goto err; if (ioctl(hdl->fd, ZYNQ_IOC_CAN_GET_STATUS_ERR, &st_err) == -1) { BLOG_ERR("%s: dev_index %d, IOC_BCAN_GET_STATUS_ERR failed\n", __func__, hdl->dev_index); ret = BCAN_ERR; goto err; } *tx_err = (st_err.bcan_err_count & 0xFF); *rx_err = (st_err.bcan_err_count & 0xFFFF) >> 8; err: return ret; }
0
apollo_public_repos/apollo-contrib/baidu/src/lib
apollo_public_repos/apollo-contrib/baidu/src/lib/bcan/Makefile
# # Makefile for Baidu CAN library # BAIDUROOT=../../.. VERSION=3.0.0.2 SONAME=libadv_bcan.so.1 CC=gcc CFLAGS=-Wall -march=native -O2 -pipe -DLIB_VER='"$(VERSION)"' SOFLAGS=-fPIC -shared -Wl,-soname,$(SONAME) AR=ar INC=$(BAIDUROOT)/src/kernel/include/uapi SRC=bcan_lib.c OBJ=bcan_lib.o HDR=bcan.h LIB=libadv_bcan.a LIBSO=libadv_bcan.so.$(VERSION) .PHONY:all all: $(LIB) $(LIBSO) $(LIB): $(SRC) $(CC) $(CFLAGS) -c -o $(OBJ) -I$(INC) $(SRC) $(AR) rcs $(LIB) $(OBJ) $(LIBSO): $(CC) $(CFLAGS) $(SOFLAGS) -o $(LIBSO) -I$(INC) $(SRC) .PHONY:install install: all mkdir -p $(BAIDUROOT)/output/lib $(BAIDUROOT)/output/include cp $(LIB) $(BAIDUROOT)/output/lib/ cp $(LIBSO) $(BAIDUROOT)/output/lib/ cp $(HDR) $(BAIDUROOT)/output/include/ .PHONY:Clean clean: rm -f *.o $(LIB) $(LIBSO)
0
apollo_public_repos/apollo-contrib/baidu/src/lib
apollo_public_repos/apollo-contrib/baidu/src/lib/bcan/bcan.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef BCAN_H #define BCAN_H #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include <sys/ioctl.h> /* bcan_msg_t and bcan_err_code definitions. */ #include "linux/bcan_defs.h" #ifdef __cplusplus extern "C" { #endif #ifdef __GNUC__ #define UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) #else #define UNUSED(x) UNUSED_ ## x #endif #define BCAN_MAX_TX_MSG 256 #define BCAN_MAX_RX_MSG 256 /* Channel states */ #define BCAN_DEV_UNINIT -1 #define BCAN_DEV_OPEN (1 << 0) #define BCAN_DEV_CLOSE (1 << 1) #define BCAN_DEV_BAUD_SET (1 << 2) #define BCAN_DEV_NORMAL (1 << 3) #define BCAN_DEV_LOOPBACK (1 << 4) #define BCAN_DEV_CONFIG (1 << 5) #define BCAN_DEV_START (1 << 6) #define BCAN_DEV_STOP (1 << 7) #define BCAN_DEV_ACTIVE (1 << 8) #define BCAN_DEV_RECVD (1 << 9) typedef uint64_t bcan_hdl_t; enum bcan_baudrate_val { BCAN_BAUDRATE_1M, BCAN_BAUDRATE_500K, BCAN_BAUDRATE_250K, BCAN_BAUDRATE_150K, BCAN_BAUDRATE_NUM }; /* Returns bcan library version. */ const char *bcan_get_libversion(void); /* Returns error message corresponding to the given error code. */ const char *bcan_get_err_msg(int err_code); int bcan_open(uint32_t dev_index, uint32_t flags, uint64_t tx_to, uint64_t rx_to, bcan_hdl_t *hdl); int bcan_close(bcan_hdl_t hdl); int bcan_start(bcan_hdl_t hdl); int bcan_stop(bcan_hdl_t hdl); int bcan_set_loopback(bcan_hdl_t hdl); int bcan_unset_loopback(bcan_hdl_t hdl); int bcan_set_baudrate(bcan_hdl_t hdl, uint32_t rate); int bcan_get_baudrate(bcan_hdl_t hdl, uint32_t *rate); int bcan_recv(bcan_hdl_t hdl, bcan_msg_t *buf, uint32_t num_msg); int bcan_send(bcan_hdl_t hdl, bcan_msg_t *buf, uint32_t num_msg); int bcan_send_hi_pri(bcan_hdl_t hdl, bcan_msg_t *buf); int bcan_get_status(bcan_hdl_t hdl); int bcan_get_err_counter(bcan_hdl_t hdl, uint8_t *rx_err, uint8_t *tx_err); #ifdef __cplusplus } #endif #endif /* BCAN_H */
0
apollo_public_repos/apollo-contrib/baidu/src/lib
apollo_public_repos/apollo-contrib/baidu/src/lib/adv_trigger/Makefile
# # Makefile for adv_trigger library # BAIDUROOT=../../.. VERSION=3.0.0.1 SONAME=libadv_trigger.so.1 CC=gcc CFLAGS=-Wall -Wno-unused-result -march=native -O2 -pipe -DLIB_VER='"$(VERSION)"' SOFLAGS=-fPIC -shared -Wl,-soname,$(SONAME) AR=ar INC=$(BAIDUROOT)/src/kernel/include/uapi SRC=adv_trigger_ctl.c OBJ=adv_trigger_ctl.o HDR=adv_trigger.h LIB=libadv_trigger.a LIBSO=libadv_trigger.so.$(VERSION) .PHONY:all all: $(LIB) $(LIBSO) $(LIB): $(SRC) $(CC) $(CFLAGS) -c -o $(OBJ) -I$(INC) $(SRC) $(AR) rcs $(LIB) $(OBJ) $(LIBSO): $(CC) $(CFLAGS) $(SOFLAGS) -o $(LIBSO) -I$(INC) $(SRC) .PHONY:install install: all mkdir -p $(BAIDUROOT)/output/lib $(BAIDUROOT)/output/include cp $(LIB) $(BAIDUROOT)/output/lib/ cp $(LIBSO) $(BAIDUROOT)/output/lib/ cp $(HDR) $(BAIDUROOT)/output/include/ .PHONY:Clean clean: rm -f *.o $(LIB) $(LIBSO)
0
apollo_public_repos/apollo-contrib/baidu/src/lib
apollo_public_repos/apollo-contrib/baidu/src/lib/adv_trigger/adv_trigger_ctl.c
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <termios.h> #include <unistd.h> #include <string.h> #include <dirent.h> #include <syslog.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/file.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/videodev2.h> #include "adv_trigger.h" enum camera_type { CAMERA_TYPE_ALL = 0, CAMERA_TYPE_FPD }; struct adv_trigger { const char *video_path; enum camera_type type; int vnum; int index; /* index of the trigger */ int zdev_index; /* index of the trigger dev */ int fpd_num; /* number of fpd-link cameras */ int vfd; int zfd[ZYNQ_TRIGGER_DEV_NUM]; }; #define DRIVER_NAME_BASA "basa" #define TRIGGER_DEV_PATH "/dev/zynq_trigger" #define SYSFS_VIDEO "video" #define SYSFS_VIDEO_PATH "/sys/class/video4linux" #define SYSFS_VIDEO_DEV_DRV "device/driver" #define PATH_LEN 128 #define adv_plat_log_fn(s...) syslog(LOG_ERR, s) const char *adv_trigger_version(void) { return LIB_VER; } static int adv_trigger_device_type(const char *driver) { if (!strcmp(driver, DRIVER_NAME_BASA)) { return CAMERA_TYPE_FPD; } else { adv_plat_log_fn("%s: unknown camera driver: %s\n", LIB_NAME, driver); return -1; } } static int adv_trigger_scan_video(struct adv_trigger *at, char *video_name) { char path[PATH_LEN]; char driver[PATH_LEN]; char *p; int type; int ret; /* Get the driver and video device type */ (void) snprintf(path, PATH_LEN, "%s/%s/%s", SYSFS_VIDEO_PATH, video_name, SYSFS_VIDEO_DEV_DRV); memset(driver, 0, sizeof(driver)); ret = readlink(path, driver, sizeof(driver) - 1); if (ret < 0) { adv_plat_log_fn("%s: failed to read link %s! %s\n", LIB_NAME, path, strerror(errno)); return -1; } p = strrchr(driver, '/'); if (p) { p++; } else { p = driver; } type = adv_trigger_device_type(p); switch (type) { case CAMERA_TYPE_FPD: at->fpd_num++; break; default: break; } return 0; } /* * Scan the sysfs to get video device information */ static int adv_trigger_scan_sysfs(struct adv_trigger *at) { char *cwd; DIR *dp; struct dirent *ent; struct stat st; int ret = 0; dp = opendir(SYSFS_VIDEO_PATH); if (!dp) { adv_plat_log_fn("%s: failed to open dir %s! %s\n", LIB_NAME, SYSFS_VIDEO_PATH, strerror(errno)); return -1; } cwd = getcwd(NULL, 0); if (chdir(SYSFS_VIDEO_PATH)) { adv_plat_log_fn("%s: failed to change dir to %s! %s\n", LIB_NAME, SYSFS_VIDEO_PATH, strerror(errno)); (void) closedir(dp); return -1; } while ((ent = readdir(dp))) { lstat(ent->d_name, &st); if (S_ISLNK(st.st_mode)) { if ((ret = adv_trigger_scan_video(at, ent->d_name))) { break; } } } if (cwd) { chdir(cwd); free(cwd); } (void) closedir(dp); return ret; } static void adv_trigger_fini(struct adv_trigger *at) { int i; for (i = 0; i < ZYNQ_TRIGGER_DEV_NUM; i++) { if (at->zfd[i] < 0) { continue; } (void) close(at->zfd[i]); } if (at->vfd >= 0) { (void) close(at->vfd); } } static void adv_trigger_params_init(struct adv_trigger *at) { int i; memset(at, 0, sizeof(struct adv_trigger)); for (i = 0; i < ZYNQ_TRIGGER_DEV_NUM; i++) { at->zfd[i] = -1; } } static int adv_trigger_vdev_init(struct adv_trigger *at, const char *video_path) { struct v4l2_capability caps; struct stat st; char path[PATH_LEN] = { 0 }; const char *video_name; int fd; at->video_path = video_path; at->type = CAMERA_TYPE_ALL; at->vnum = -1; at->vfd = -1; if (video_path == NULL) { return 0; } fd = open(video_path, O_RDWR); if (fd < 0) { adv_plat_log_fn("%s: failed to open device %s! %s\n", LIB_NAME, video_path, strerror(errno)); return -1; } if (ioctl(fd, VIDIOC_QUERYCAP, &caps)) { adv_plat_log_fn("%s: failed to query capability of %s! " "%s\n", LIB_NAME, video_path, strerror(errno)); close(fd); return -1; } at->type = adv_trigger_device_type((const char *)caps.driver); if (at->type < 0) { adv_plat_log_fn( "%s: unsupported device %s %s driver %s\n", LIB_NAME, video_path, (const char *)caps.card, (const char *)caps.driver); close(fd); return -1; } at->vfd = fd; lstat(video_path, &st); if (S_ISLNK(st.st_mode)) { if (readlink(video_path, path, sizeof(path) - 1) < 0) { adv_plat_log_fn("%s: failed to read link %s! %s\n", LIB_NAME, video_path, strerror(errno)); return -1; } video_path = path; } video_name = strrchr(video_path, '/'); if (video_name) { video_name++; } else { video_name = video_path; } if (sscanf(video_name, SYSFS_VIDEO "%d", &at->vnum) != 1) { adv_plat_log_fn("%s: failed to read video number %s! %s\n", LIB_NAME, video_name, strerror(errno)); return -1; } return 0; } static int adv_trigger_zdev_init(struct adv_trigger *at) { char zdev_path[32]; int fd; int zfd; int i; zfd = -1; for (i = ZYNQ_TRIGGER_DEV_NUM - 1; i >= 0; i--) { (void) snprintf(zdev_path, sizeof(zdev_path), "%s%d", TRIGGER_DEV_PATH, i); fd = open(zdev_path, O_RDWR); if (fd >= 0) { at->zfd[i] = fd; zfd = fd; } } return zfd; } static int adv_trigger_init(struct adv_trigger *at, const char *video_path) { adv_trigger_params_init(at); /* * Read the video device information */ if (adv_trigger_vdev_init(at, video_path)) { return -1; } if (at->type == CAMERA_TYPE_FPD) { /* Nothing to do for FPD-link camera */ return 0; } /* * Open all trigger devices and save the file descriptors */ if (adv_trigger_zdev_init(at) < 0) { goto init_fail; } if (adv_trigger_scan_sysfs(at)) { goto init_fail; } return 0; init_fail: adv_trigger_fini(at); return -1; } static int adv_trigger_enable_fpd(struct adv_trigger *at, unsigned char fps, unsigned char internal) { zynq_trigger_t trigger[1] = {{ 0 }}; trigger->fps = fps; trigger->internal = internal; if (ioctl(at->vfd, ZYNQ_IOC_TRIGGER_ENABLE_ONE, trigger)) { adv_plat_log_fn("%s: failed to enable trigger for %s! %s\n", LIB_NAME, at->video_path, strerror(errno)); return -1; } adv_plat_log_fn("%s: trigger enabled for %s, fps = %d%s\n", LIB_NAME, at->video_path, trigger->fps, (trigger->internal) ? ", internal PPS" : ""); return 0; } static int adv_trigger_enable_all(struct adv_trigger *at, unsigned char fps, unsigned char internal) { zynq_trigger_t trigger[1] = {{ 0 }}; int i; int ret = -1; trigger->fps = fps; trigger->internal = internal; for (i = 0; i < ZYNQ_TRIGGER_DEV_NUM; i++) { if (at->zfd[i] < 0) { continue; } if ((ret = ioctl(at->zfd[i], ZYNQ_IOC_TRIGGER_ENABLE, trigger))) { break; } } if (ret) { adv_plat_log_fn("%s: failed to enable all triggers! %s\n", LIB_NAME, strerror(errno)); return -1; } adv_plat_log_fn("%s: all trigger enabled, fps = %d%s\n", LIB_NAME, trigger->fps, (trigger->internal) ? ", internal PPS" : ""); return 0; } static int adv_trigger_disable_fpd(struct adv_trigger *at) { if (ioctl(at->vfd, ZYNQ_IOC_TRIGGER_DISABLE_ONE)) { adv_plat_log_fn("%s: failed to disable trigger for %s! %s\n", LIB_NAME, at->video_path, strerror(errno)); return -1; } adv_plat_log_fn("%s: trigger disabled for %s\n", LIB_NAME, at->video_path); return 0; } static int adv_trigger_disable_all(struct adv_trigger *at) { int i; int ret = -1; /* * Disable all triggers */ for (i = 0; i < ZYNQ_TRIGGER_DEV_NUM; i++) { if (at->zfd[i] < 0) { continue; } if ((ret = ioctl(at->zfd[i], ZYNQ_IOC_TRIGGER_DISABLE, NULL))) { break; } } if (ret) { adv_plat_log_fn("%s: failed to disable all triggers! %s\n", LIB_NAME, strerror(errno)); return -1; } adv_plat_log_fn("%s: all trigger disabled\n", LIB_NAME); return 0; } int adv_trigger_enable(const char *video_path, unsigned char fps, unsigned char internal) { struct adv_trigger at; int ret; ret = adv_trigger_init(&at, video_path); if (ret) { return ret; } switch (at.type) { case CAMERA_TYPE_FPD: ret = adv_trigger_enable_fpd(&at, fps, internal); break; default: ret = adv_trigger_enable_all(&at, fps, internal); break; } adv_trigger_fini(&at); return ret; } int adv_trigger_disable(const char *video_path) { struct adv_trigger at; int ret; ret = adv_trigger_init(&at, video_path); if (ret) { return ret; } switch (at.type) { case CAMERA_TYPE_FPD: ret = adv_trigger_disable_fpd(&at); break; default: ret = adv_trigger_disable_all(&at); break; } adv_trigger_fini(&at); return ret; } int adv_trigger_get_status(struct adv_trigger_status *s) { struct adv_trigger at; zynq_trigger_t *t; int result; int i, j; int ret; memset(s, 0, sizeof(struct adv_trigger_status)); for (i = 0; i < ZYNQ_TRIGGER_DEV_NUM; i++) { for (j = 0; j < ZYNQ_FPD_TRIG_NUM; j++) { t = &s->status[i].fpd_triggers[j]; t->vnum = -1; } } ret = adv_trigger_init(&at, NULL); if (ret) { return ret; } for (i = 0; i < ZYNQ_TRIGGER_DEV_NUM; i++) { if (at.zfd[i] < 0) { s->status[i].zdev_name[0] = '\0'; continue; } ret = ioctl(at.zfd[i], ZYNQ_IOC_TRIGGER_DEV_NAME, s->status[i].zdev_name); if (ret) { adv_plat_log_fn(LIB_NAME ": failed to get trigger device name on %s%d! %s\n", TRIGGER_DEV_PATH, i, strerror(errno)); break; } ret = ioctl(at.zfd[i], ZYNQ_IOC_TRIGGER_STATUS_GPS, &result); if (ret) { adv_plat_log_fn(LIB_NAME ": failed to get GPS status on %s%d! %s\n", TRIGGER_DEV_PATH, i, strerror(errno)); break; } if (result) { s->status[i].flags |= FLAG_GPS_VALID; } ret = ioctl(at.zfd[i], ZYNQ_IOC_TRIGGER_STATUS_PPS, &result); if (ret) { adv_plat_log_fn(LIB_NAME ": failed to get PPS status on %s%d! %s\n", TRIGGER_DEV_PATH, i, strerror(errno)); break; } if (result) { s->status[i].flags |= FLAG_PPS_VALID; } if (at.fpd_num > 0) { ret = ioctl(at.zfd[i], ZYNQ_IOC_TRIGGER_STATUS, s->status[i].fpd_triggers); if (ret) { adv_plat_log_fn(LIB_NAME ": failed to get " "FPD-link trigger status on %s%d! %s\n", TRIGGER_DEV_PATH, i, strerror(errno)); break; } } } adv_trigger_fini(&at); return ret; } static int adv_trigger_delay_fpd(struct adv_trigger *at, int action, unsigned int *trigger_delay, unsigned int *exp_time) { zynq_trigger_delay_t delay_arg; int status; int ret = 0; delay_arg.vnum = at->vnum; /* Set delay */ if (action == 1) { delay_arg.trigger_delay = *trigger_delay; status = ioctl(at->vfd, ZYNQ_IOC_TRIGGER_DELAY_SET, &delay_arg); if (status == 0) { adv_plat_log_fn("%s: video%d SET trigger_delay=%uus\n", LIB_NAME, delay_arg.vnum, delay_arg.trigger_delay); } else { adv_plat_log_fn("%s: video%d " "SET trigger delay failed! %s\n", LIB_NAME, delay_arg.vnum, strerror(errno)); ret = -1; } } /* Get delay and exposure time */ status = ioctl(at->vfd, ZYNQ_IOC_TRIGGER_DELAY_GET, &delay_arg); if (status == 0) { adv_plat_log_fn("%s: video%d GET trigger_delay=%uus, " "exp_time=%uus\n", LIB_NAME, delay_arg.vnum, delay_arg.trigger_delay, delay_arg.exposure_time); *trigger_delay = delay_arg.trigger_delay; *exp_time = delay_arg.exposure_time; } else { adv_plat_log_fn("%s: video%d GET trigger delay failed! %s\n", LIB_NAME, delay_arg.vnum, strerror(errno)); ret = -1; } return ret; } int adv_trigger_delay_ctl(const char *video_path, int action, unsigned int *trigger_delay, unsigned int *exp_time) { struct adv_trigger at; int ret = 0; adv_trigger_params_init(&at); if (adv_trigger_vdev_init(&at, video_path)) { return -1; } switch (at.type) { case CAMERA_TYPE_FPD: ret = adv_trigger_delay_fpd(&at, action, trigger_delay, exp_time); break; default: adv_plat_log_fn("%s: invalid video path\n", LIB_NAME); ret = -1; break; } adv_trigger_fini(&at); return ret; }
0
apollo_public_repos/apollo-contrib/baidu/src/lib
apollo_public_repos/apollo-contrib/baidu/src/lib/adv_trigger/adv_trigger.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef ADV_TRIGGER_H #define ADV_TRIGGER_H #ifdef __cplusplus extern "C" { #endif #include "linux/zynq_api.h" #define LIB_NAME "adv_trigger" /* * @brief Main functions to control hardware triggers. * * @param video_path: path of the video device file, e.g. /dev/video0. * When NULL, all triggers are enabled/disabled. * @param fps: FPS (frame-per-second) for the specified video device (camera). * The supported values are: 1 ~ 30. * All other values set FPS to the default value 30. * @param internal: source of the PPS. * 0: use GPS generated PPS; * 1: use FPGA internal PPS. * * @return: * 0: success; * non-0: there is an error. */ int adv_trigger_enable(const char *video_path, unsigned char fps, unsigned char internal); int adv_trigger_disable(const char *video_path); int adv_trigger_delay_ctl(const char *video_path, int action, unsigned int *trigger_delay, unsigned int *exp_time); #define FLAG_GPS_VALID (1 << 0) #define FLAG_PPS_VALID (1 << 1) /* FPGA board trigger status. */ struct adv_trigger_status { struct { int flags; char zdev_name[ZYNQ_DEV_NAME_LEN]; zynq_trigger_t fpd_triggers[ZYNQ_FPD_TRIG_NUM]; } status[ZYNQ_TRIGGER_DEV_NUM]; }; /* * @brief Gets the status of all triggers. * * @param status: pointer to the struct adv_zynq_status. * * @return: * 0: successful; * non-0: there is an error. */ int adv_trigger_get_status(struct adv_trigger_status *status); const char *adv_trigger_version(void); #ifdef __cplusplus } #endif #endif /* ADV_TRIGGER_H */
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_gps.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/module.h> #include <linux/kobject.h> #include <linux/delay.h> #include <linux/time.h> #include <linux/hrtimer.h> #include <linux/kthread.h> #include "basa.h" #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 11, 0) #include <linux/sched.h> #else #include <uapi/linux/sched/types.h> #endif static zynq_dev_t *zynq_gps_master_dev = NULL; static struct task_struct *zynq_gps_taskp = NULL; static struct completion zynq_gps_wait; static int zynq_gps_valid_once = 0; /* * GPS sync time interval in seconds: 0 to disable; default 60. */ static unsigned int zynq_gps_sync_time = ZYNQ_GPS_SYNC_TIME_DEFAULT; static unsigned int zynq_gps_smooth_step = ZYNQ_GPS_SMOOTH_STEP_DEFAULT; static unsigned int zynq_gps_smooth_max = 1000; /* ms */ static unsigned int zynq_gps_checksum = 0; /* * We define two water marks for GPS/SYS time gap examination (usec per sec). */ static unsigned int zynq_gps_high_factor = 100000; static unsigned int zynq_gps_low_factor = 100; static int zynq_get_gps_time(zynq_dev_t *zdev, u32 *gps_val) { spin_lock(&zdev->zdev_lock); gps_val[0] = zynq_g_reg_read(zdev, ZYNQ_G_NTP_LO); if (gps_val[0] == -1) { spin_unlock(&zdev->zdev_lock); zynq_err("%d %s: Failed to read GPS time\n", zdev->zdev_inst, __FUNCTION__); return -1; } if (!(gps_val[0] & ZYNQ_GPS_TIME_VALID)) { if (ZYNQ_CAP(zdev, GPS_SMOOTH) && !zynq_gps_valid_once) { u32 val = zynq_g_reg_read(zdev, ZYNQ_G_GPS_LAST_TIME_LO); zynq_trace(ZYNQ_TRACE_PROBE, "%d %s: gps_last_time_lo=0x%x\n", zdev->zdev_inst, __FUNCTION__, val); if (val & ZYNQ_GPS_TIME_VALID) { zynq_gps_valid_once = 1; } else { val = zynq_g_reg_read(zdev, ZYNQ_G_GPS_STATUS); if (val & ZYNQ_GPS_INIT_SET) { zynq_gps_valid_once = 1; } } } if (ZYNQ_CAP(zdev, GPS_SMOOTH) && zynq_gps_valid_once) { zynq_trace(ZYNQ_TRACE_PROBE, "%d %s: GPS time is not valid, " "FPGA internal time is used\n", zdev->zdev_inst, __FUNCTION__); } else { spin_unlock(&zdev->zdev_lock); zynq_err("%d %s: GPS time is not valid\n", zdev->zdev_inst, __FUNCTION__); return -1; } } else if (!zynq_gps_valid_once) { zynq_gps_valid_once = 1; } gps_val[1] = zynq_g_reg_read(zdev, ZYNQ_G_NTP_HI); gps_val[2] = zynq_g_reg_read(zdev, ZYNQ_G_NTP_DATE); spin_unlock(&zdev->zdev_lock); zynq_trace(ZYNQ_TRACE_PROBE, "%d %s: gps_ddmmyy=0x%x, gps_hhmmss=0x%x, gps_msusns_valid=0x%x\n", zdev->zdev_inst, __FUNCTION__, gps_val[2], gps_val[1], gps_val[0]); return 0; } static int zynq_get_gprmc(zynq_dev_t *zdev, u32 *gprmc_val) { /* 'CAFE': GPS is connected but not locked */ u32 inval_gprmc = 0x45464143; /* 'DEAD': GPS is not connected */ u32 dead_gprmc = 0x44414544; int i; spin_lock(&zdev->zdev_lock); gprmc_val[0] = ntohl(zynq_g_reg_read(zdev, ZYNQ_G_GPRMC)); if (gprmc_val[0] == -1 || gprmc_val[0] == dead_gprmc) { spin_unlock(&zdev->zdev_lock); zynq_err("%d %s: GPS is not connected\n", zdev->zdev_inst, __FUNCTION__); return -1; } if (gprmc_val[0] == inval_gprmc) { spin_unlock(&zdev->zdev_lock); zynq_err("%d %s: GPS is not locked\n", zdev->zdev_inst, __FUNCTION__); return -1; } for (i = 1; i < ZYNQ_GPS_GPRMC_VAL_SZ/4; i++) { gprmc_val[i] = ntohl(zynq_g_reg_read(zdev, ZYNQ_G_GPRMC)); } spin_unlock(&zdev->zdev_lock); return 0; } /* * convert the GPS time from FPGA registers to "struct timespec" */ #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE static void zynq_gps_time_ts(u32 *gps_val, struct timespec *ts) #else static void zynq_gps_time_ts(u32 *gps_val, struct timespec64 *ts) #endif { ts->tv_sec = mktime(2000 + (gps_val[2] & 0xff), (gps_val[2] & 0xff00) >> 8, (gps_val[2] & 0xff0000) >> 16, (gps_val[1] & 0xff0000) >> 16, (gps_val[1] & 0xff00) >> 8, gps_val[1] & 0xff); ts->tv_nsec = ((gps_val[0] & 0xfe) << 2) + ((gps_val[0] >> 8) & 0xfff) * NSEC_PER_USEC + ((gps_val[0] >> 20) & 0xfff) * NSEC_PER_MSEC; } #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE static int zynq_gps_ts_check(zynq_dev_t *zdev, struct timespec *ts) #else static int zynq_gps_ts_check(zynq_dev_t *zdev, struct timespec64 *ts) #endif { u32 gps_val[3]; #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE struct timespec ts_sys; #else struct timespec64 ts_sys; #endif int diff; int delay; int thresh; if (zdev->zdev_gps_cnt & 0x1) { #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE ktime_get_real_ts(&ts_sys); #else ktime_get_real_ts64(&ts_sys); #endif if (zynq_get_gps_time(zdev, gps_val)) { return -1; } } else { if (zynq_get_gps_time(zdev, gps_val)) { return -1; } #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE ktime_get_real_ts(&ts_sys); #else ktime_get_real_ts64(&ts_sys); #endif } zynq_gps_time_ts(gps_val, ts); /* check the gap between system time and gps time in usec */ diff = (ts_sys.tv_sec - ts->tv_sec) * USEC_PER_SEC + (ts_sys.tv_nsec - ts->tv_nsec) / NSEC_PER_USEC; if (zdev->zdev_gps_ts_first.tv_sec) { zdev->zdev_sys_drift += diff; } zynq_trace(ZYNQ_TRACE_GPS, "%d SYS time: %lld.%09ld, %s time: %lld.%09ld, %dus\n", zdev->zdev_inst, (s64)ts_sys.tv_sec, ts_sys.tv_nsec, (gps_val[0] & ZYNQ_GPS_TIME_VALID) ? "GPS" : "FPGA", (s64)ts->tv_sec, ts->tv_nsec, diff); if (zdev->zdev_gps_smoothing) { return 0; } /* * Check the validity of the GPS time. * * When the gap between the system time and gps time is more than * the low water mark, the system time sync is still performed * while a warning is issued. * * When the gap is more than the high water mark, we'll fail the * system time sync. */ /* If it is the first sync, bypass the time check */ if (!zdev->zdev_gps_ts.tv_sec && !zdev->zdev_gps_ts.tv_nsec) { return 0; } /* Firstly find the delay since the last successful sync in seconds */ delay = ts->tv_sec - zdev->zdev_gps_ts.tv_sec; if (delay < 0) { zynq_err("%d WARNING! SYS time: %lld.%09ld, %s time: %lld.%09ld, " "Last sync time: %lld.%09ld, abnormal time jump.\n", zdev->zdev_inst, (s64)ts_sys.tv_sec, ts_sys.tv_nsec, (gps_val[0] & ZYNQ_GPS_TIME_VALID) ? "GPS" : "FPGA", (s64)ts->tv_sec, ts->tv_nsec, zdev->zdev_gps_ts.tv_sec, zdev->zdev_gps_ts.tv_nsec); return 0; } /* Check the high water mark in usec */ thresh = zynq_gps_high_factor * delay; if ((diff > thresh) || (diff < -thresh)) { zynq_err("%d WARNING! SYS time: %lld.%09ld, %s time: %lld.%09ld, " "gap %dus exceeds high threshold %dus.\n", zdev->zdev_inst, (s64)ts_sys.tv_sec, ts_sys.tv_nsec, (gps_val[0] & ZYNQ_GPS_TIME_VALID) ? "GPS" : "FPGA", (s64)ts->tv_sec, ts->tv_nsec, diff, thresh); return 0; } /* Check the low water mark in usec */ thresh = zynq_gps_low_factor * delay; if ((diff > thresh) || (diff < -thresh)) { zynq_err("%d WARNING! SYS time: %lld.%09ld, %s time: %lld.%09ld, " "gap %dus exceeds low threshold %dus.\n", zdev->zdev_inst, (s64)ts_sys.tv_sec, ts_sys.tv_nsec, (gps_val[0] & ZYNQ_GPS_TIME_VALID) ? "GPS" : "FPGA", (s64)ts->tv_sec, ts->tv_nsec, diff, thresh); } return 0; } static int zynq_do_gps_sync(zynq_dev_t *zdev) { #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE struct timespec ts; #else struct timespec64 ts; #endif int ret; /* get current GPS time */ if ((ret = zynq_gps_ts_check(zdev, &ts))) { return ret; } /* update system time */ #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE if ((ret = do_settimeofday(&ts))) { #else if ((ret = do_settimeofday64(&ts))) { #endif zynq_err("%d %s: failed to set system time. GPS sync aborted\n", zdev->zdev_inst, __FUNCTION__); return ret; } if (!zdev->zdev_gps_ts_first.tv_sec) { zdev->zdev_gps_ts_first = ts; } zdev->zdev_gps_ts = ts; zdev->zdev_gps_cnt++; return 0; } /* * GPS sync thread: sync system time to GPS time periodically per * zynq_gps_sync_time seconds. (Note, we can't use a hrtimer to * do this as there are side effects to do do_settimeofday() via * a hrtimer per my testing.) */ static int zynq_gps_sync_thread(void *arg) { zynq_dev_t *zdev; unsigned int delay_time; long result; while (!kthread_should_stop()) { zdev = zynq_gps_master_dev; /* sync system time to GPS time */ (void) zynq_do_gps_sync(zdev); /* * Wait for specified zynq_gps_sync_time seconds. We can't * simply call msleep() here as this will cause driver * unloading to wait. */ if (zdev->zdev_gps_smoothing) { delay_time = ZYNQ_GPS_SYNC_TIME_SMOOTH; } else { delay_time = zynq_gps_sync_time; } if (delay_time == 0) { delay_time = ZYNQ_GPS_SYNC_TIME_MAX; } result = wait_for_completion_interruptible_timeout( &zynq_gps_wait, msecs_to_jiffies(delay_time * 1000)); if (ZYNQ_CAP(zdev, GPS_SMOOTH)) { u32 status; spin_lock(&zdev->zdev_lock); status = zynq_g_reg_read(zdev, ZYNQ_G_GPS_STATUS); zynq_trace(ZYNQ_TRACE_PROBE, "%d %s: gps_status=0x%x\n", zdev->zdev_inst, __FUNCTION__, status); if (status & ZYNQ_GPS_SMOOTH_IN_PROGRESS) { zdev->zdev_gps_smoothing = 2; } else if (zdev->zdev_gps_smoothing) { zdev->zdev_gps_smoothing--; } spin_unlock(&zdev->zdev_lock); } if (result > 0) { /* Restart the completion wait */ reinit_completion(&zynq_gps_wait); } else if (result != 0) { /* Interrupted or module is being unloaded */ break; } } return 0; } /* * create the GPS sync thread and schedule it with the second highest priority * that is lower than the watchdog (99) and higher than the interrupts (50). */ static void zynq_gps_thread_init(zynq_dev_t *zdev) { struct sched_param param = { .sched_priority = 60 }; init_completion(&zynq_gps_wait); zynq_gps_taskp = kthread_run(zynq_gps_sync_thread, NULL, "zynq_gps_sync_thread"); /* set the thread scheduling class as SCHED_FIFO */ sched_setscheduler(zynq_gps_taskp, SCHED_FIFO, &param); } /* * destroy the GPS sync thread */ static void zynq_gps_thread_fini(zynq_dev_t *zdev) { complete(&zynq_gps_wait); if (zynq_gps_taskp) { kthread_stop(zynq_gps_taskp); } } static int zynq_gps_init_fpga_time(zynq_dev_t *zdev) { #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE struct timespec ts = { 0 }; #else struct timespec64 ts = { 0 }; #endif struct tm t; u32 gps_val[3]; u32 val; if (!ZYNQ_CAP(zdev, FPGA_TIME_INIT)) { zynq_err("%d %s: " "FPGA time init is not supported on this device\n", zdev->zdev_inst, __FUNCTION__); return -EPERM; } (void) zynq_get_gps_time(zdev, gps_val); spin_lock(&zdev->zdev_lock); if (zynq_gps_valid_once) { spin_unlock(&zdev->zdev_lock); /* GPS time valid once, do nothing */ zynq_err("%d %s: FPGA time already initialized\n", zdev->zdev_inst, __FUNCTION__); return -EAGAIN; } /* Get the current system time */ #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE ktime_get_real_ts(&ts); #else ktime_get_real_ts64(&ts); #endif zynq_log("%d %s: init FPGA time with SYS time: %lld.%09ld\n", zdev->zdev_inst, __FUNCTION__, (s64)ts.tv_sec, ts.tv_nsec); /* Get the broken-down time from the Epoch time */ #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE time_to_tm(ts.tv_sec, 0, &t); #else time64_to_tm(ts.tv_sec, 0, &t); #endif /* Update the FPGA initial time */ val = zynq_g_reg_read(zdev, ZYNQ_G_GPS_CONFIG_2); val = SET_BITS(ZYNQ_GPS_TIME_DAY, val, t.tm_mday) | SET_BITS(ZYNQ_GPS_TIME_MON, val, t.tm_mon + 1) | SET_BITS(ZYNQ_GPS_TIME_YEAR, val, t.tm_year - 100) | SET_BITS(ZYNQ_GPS_PPS_LOCK_DELAY, val, 0x20); zynq_g_reg_write(zdev, ZYNQ_G_GPS_CONFIG_2, val); val = SET_BITS(ZYNQ_GPS_TIME_SEC, 0, t.tm_sec) | SET_BITS(ZYNQ_GPS_TIME_MIN, 0, t.tm_min) | SET_BITS(ZYNQ_GPS_TIME_HOUR, 0, t.tm_hour); zynq_g_reg_write(zdev, ZYNQ_G_GPS_TIME_HI_INIT, val); val = SET_BITS(ZYNQ_GPS_TIME_NSEC, 0, (ts.tv_nsec % NSEC_PER_USEC) >> 3) | SET_BITS(ZYNQ_GPS_TIME_USEC, 0, (ts.tv_nsec / NSEC_PER_USEC) % USEC_PER_MSEC) | SET_BITS(ZYNQ_GPS_TIME_MSEC, 0, ts.tv_nsec / NSEC_PER_MSEC); val |= ZYNQ_GPS_TIME_VALID; zynq_g_reg_write(zdev, ZYNQ_G_GPS_TIME_LO_INIT, val); spin_unlock(&zdev->zdev_lock); return 0; } static void zynq_gps_config(zynq_dev_t *zdev) { u32 step; u32 val; if (!ZYNQ_CAP(zdev, GPS_SMOOTH)) { /* GPS time sync smoothing is not supported for MoonRover */ return; } spin_lock(&zdev->zdev_lock); val = zynq_g_reg_read(zdev, ZYNQ_G_GPS_CONFIG); if (zynq_gps_smooth_max == 0) { val |= ZYNQ_GPS_DISABLE_SMOOTH; } else { if (zynq_gps_smooth_step < ZYNQ_GPS_SMOOTH_STEP_MIN) { step = 0xFFFF; } else if (zynq_gps_smooth_step > ZYNQ_GPS_SMOOTH_STEP_MAX) { step = 1; } else { step = USEC_PER_SEC / zynq_gps_smooth_step - 1; } val = SET_BITS(ZYNQ_GPS_ADJ_STEP, val, step); val = SET_BITS(ZYNQ_GPS_MAX_TOLERANCE, val, zynq_gps_smooth_max); val &= ~ZYNQ_GPS_DISABLE_SMOOTH; } val &= ~ZYNQ_GPS_LOOPBACK_EN; zynq_g_reg_write(zdev, ZYNQ_G_GPS_CONFIG, val); zynq_trace(ZYNQ_TRACE_PROBE, "%d %s: gps_config=0x%x\n", zdev->zdev_inst, __FUNCTION__, val); val = zynq_g_reg_read(zdev, ZYNQ_G_GPS_CONFIG_2); if (zynq_gps_checksum) { val |= ZYNQ_GPS_CHECKSUM_CHECK; } else { val &= ~ZYNQ_GPS_CHECKSUM_CHECK; } if (ZDEV_PL_VER(zdev) > 0x200) val = val | SET_BITS(ZYNQ_GPS_PPS_LOCK_DELAY, val, 0x20); zynq_g_reg_write(zdev, ZYNQ_G_GPS_CONFIG_2, val); spin_unlock(&zdev->zdev_lock); } static u32 zynq_gps_status(zynq_dev_t *zdev) { u32 status; status = zynq_g_reg_read(zdev, ZYNQ_G_STATUS); zynq_log("%d PPS is %s, GPS %s locked\n", zdev->zdev_inst, (status & ZYNQ_STATUS_PPS_LOCKED) ? "ON" : "OFF", (status & ZYNQ_STATUS_GPS_LOCKED) ? "is" : "is NOT"); return status; } void zynq_gps_init(zynq_dev_t *zdev) { if (zynq_fwupdate_param) { return; } spin_lock(&zynq_gps_lock); if (zynq_gps_master_dev != NULL) { spin_unlock(&zynq_gps_lock); return; } zynq_trace(ZYNQ_TRACE_PROBE, "%d %s: GPS master device set\n", zdev->zdev_inst, __FUNCTION__); zynq_gps_master_dev = zdev; spin_unlock(&zynq_gps_lock); zynq_gps_config(zdev); zynq_gps_status(zdev); zynq_gps_thread_init(zdev); } void zynq_gps_fini(zynq_dev_t *zdev) { spin_lock(&zynq_gps_lock); if (zdev != zynq_gps_master_dev) { spin_unlock(&zynq_gps_lock); return; } zynq_gps_master_dev = NULL; spin_unlock(&zynq_gps_lock); zynq_gps_thread_fini(zdev); } void zynq_gps_pps_changed(zynq_dev_t *zdev) { u32 status; /* notify the waiting thread */ complete(&zdev->zdev_gpspps_event_comp); status = zynq_gps_status(zdev); if (!(status & ZYNQ_STATUS_GPS_LOCKED)) { ZYNQ_STATS_LOGX(zdev, DEV_STATS_GPS_UNLOCK, 1, 0); } if (ZYNQ_CAP(zdev, GPS_SMOOTH) && (status & ZYNQ_STATUS_GPS_LOCKED)) { spin_lock(&zynq_gps_lock); if (zdev != zynq_gps_master_dev) { spin_unlock(&zynq_gps_lock); return; } spin_unlock(&zynq_gps_lock); zynq_gps_config(zdev); spin_lock(&zdev->zdev_lock); status = zynq_g_reg_read(zdev, ZYNQ_G_GPS_STATUS); spin_unlock(&zdev->zdev_lock); zynq_trace(ZYNQ_TRACE_PROBE, "%d %s: gps_status=0x%x\n", zdev->zdev_inst, __FUNCTION__, status); if (status & ZYNQ_GPS_SMOOTH_IN_PROGRESS) { complete(&zynq_gps_wait); } } } /* * GPS support ioctls */ #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) static int zynq_gps_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg) #else static long zynq_gps_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) #endif { zynq_dev_t *zdev = filp->private_data; int err = 0; switch (cmd) { case ZYNQ_IOC_GPS_GET: { u32 gps_val[3]; if (zynq_get_gps_time(zdev, gps_val)) { err = -EAGAIN; break; } if (copy_to_user((void __user *)arg, gps_val, ZYNQ_GPS_VAL_SZ)) { err = -EFAULT; break; } return 0; } case ZYNQ_IOC_GPS_GPRMC_GET: { u8 gprmc_buf[ZYNQ_GPS_GPRMC_VAL_SZ + 1]; u32 *gprmc_val = (u32 *)gprmc_buf; if (zynq_get_gprmc(zdev, gprmc_val)) { err = -EAGAIN; break; } gprmc_buf[ZYNQ_GPS_GPRMC_VAL_SZ] = '\0'; if (copy_to_user((void __user *)arg, gprmc_val, ZYNQ_GPS_GPRMC_VAL_SZ)) { err = -EFAULT; break; } zynq_trace(ZYNQ_TRACE_PROBE, "%d %s: GPRMC data: %s\n", zdev->zdev_inst, __FUNCTION__, (char *)gprmc_val); return 0; } case ZYNQ_IOC_GPS_SYNC: spin_lock(&zynq_gps_lock); if (zdev != zynq_gps_master_dev) { spin_unlock(&zynq_gps_lock); zynq_err("%d %s: it's not the GPS master device " "for GPS/SYS time sync support\n", zdev->zdev_inst, __FUNCTION__); err = -EPERM; break; } spin_unlock(&zynq_gps_lock); if (zynq_do_gps_sync(zdev)) { err = -EAGAIN; } break; case ZYNQ_IOC_GPS_FPGA_INIT: spin_lock(&zynq_gps_lock); if (zdev != zynq_gps_master_dev) { spin_unlock(&zynq_gps_lock); zynq_err("%d %s: it's not the GPS master device " "for FPGA time init support\n", zdev->zdev_inst, __FUNCTION__); err = -EPERM; break; } spin_unlock(&zynq_gps_lock); err = zynq_gps_init_fpga_time(zdev); break; default: err = -EINVAL; break; } zynq_trace(ZYNQ_TRACE_PROBE, "%d %s: error = %d\n", zdev->zdev_inst, __FUNCTION__, err); return err; } static int zynq_gps_open(struct inode *inode, struct file *filp) { zynq_dev_t *zdev; zdev = container_of(inode->i_cdev, zynq_dev_t, zdev_cdev_gps); filp->private_data = zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d %s done.", zdev->zdev_inst, __FUNCTION__); return 0; } static int zynq_gps_release(struct inode *inode, struct file *filp) { return 0; } struct file_operations zynq_gps_fops = { .owner = THIS_MODULE, #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) .ioctl = zynq_gps_ioctl, #else .unlocked_ioctl = zynq_gps_ioctl, #endif .open = zynq_gps_open, .release = zynq_gps_release }; module_param_named(gpssynctime, zynq_gps_sync_time, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(gpssynctime, "GPS sync interval in seconds"); module_param_named(gpssmoothstep, zynq_gps_smooth_step, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(gpssmoothstep, "GPS sync smoothing step length in usec"); module_param_named(gpssmoothmax, zynq_gps_smooth_max, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(gpssmoothmax, "GPS sync smoothing max tolerance in msec"); module_param_named(gpschecksum, zynq_gps_checksum, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(gpschecksum, "GPRMC checksum validation"); module_param_named(gpshifactor, zynq_gps_high_factor, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(gpshifactor, "high water mark factor for GPS time check"); module_param_named(gpslofactor, zynq_gps_low_factor, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(gpslofactor, "low water mark factor for GPS time check");
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_video.h
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _BASA_VIDEO_H_ #define _BASA_VIDEO_H_ #include <linux/videodev2.h> #include <media/v4l2-device.h> #include <media/v4l2-dev.h> #include <media/v4l2-ctrls.h> #include <media/videobuf2-core.h> #include <media/videobuf2-v4l2.h> #define ZVIDEO_VBUF_MIN_NUM 4 /* Video frame default parameters */ #define ZVIDEO_IMAGE_WIDTH 1920 #define ZVIDEO_IMAGE_HEIGHT 1080 #define ZVIDEO_EM_DATA_LINES 2 #define ZVIDEO_EM_STATS_LINES 2 #define ZVIDEO_WIDTH ZVIDEO_IMAGE_WIDTH #define ZVIDEO_HEIGHT (ZVIDEO_IMAGE_HEIGHT + \ ZVIDEO_EM_DATA_LINES + ZVIDEO_EM_STATS_LINES) #define ZVIDEO_EXT_META_DATA_BYTES 32 #define ZVIDEO_BYTES_PER_PIXEL_YUV 2 #define ZVIDEO_BYTES_PER_PIXEL_RGB 3 #define ZVIDEO_BYTES_PER_LINE(f) \ (ZVIDEO_BYTES_PER_PIXEL_ ## f * ZVIDEO_IMAGE_WIDTH) #define ZVIDEO_IMAGE_BYTES(f) \ (ZVIDEO_BYTES_PER_LINE(f) * ZVIDEO_IMAGE_HEIGHT) #define ZVIDEO_BYTES(f) \ (ZVIDEO_BYTES_PER_LINE(f) * ZVIDEO_HEIGHT + \ ZVIDEO_EXT_META_DATA_BYTES) #define T_ROW(llp, pck) \ div_u64((u64)(llp) * USEC_PER_SEC, (pck)) #define T_FRAME(fll, llp, pck) \ mul_u64_u32_div((u64)(llp) * USEC_PER_SEC, (fll), (pck)) #define ZVIDEO_STATE_STREAMING 0x01 #define ZVIDEO_STATE_LINK_CHANGE 0x10 #define ZVIDEO_STATE_CAM_FAULT 0x40 #define ZVIDEO_STATE_CHAN_FAULT 0x80 #define ZVIDEO_LINK_CHANGE_DELAY 1000 /* msec */ struct zynq_dev; typedef struct zynq_video_buffer { struct vb2_v4l2_buffer vbuf; struct list_head list; u32 offset; unsigned char *addr; unsigned long size; } zynq_video_buffer_t; typedef struct zynq_video { int index; zynq_cam_caps_t caps; u8 __iomem *reg_base; struct zynq_dev *zdev; struct zynq_chan *zchan; struct v4l2_device v4l2_dev; struct video_device vdev; struct v4l2_ctrl_handler ctrl_handler; struct v4l2_pix_format format; struct vb2_queue queue; struct list_head buf_list; struct list_head pending_list; struct mutex mlock; /* Lock for main serialization */ struct mutex slock; /* Lock for vb queue streaming */ spinlock_t qlock; /* Lock for driver owned queues */ spinlock_t rlock; /* lock for rx proc and reset */ unsigned char *dev_cfg; unsigned int meta_header_lines; unsigned int meta_footer_lines; unsigned int state; unsigned int input; unsigned int sequence; unsigned int buf_total; /* Total buf num in buf_list */ unsigned int buf_avail; /* Available buf num in buf_list */ unsigned int fps; unsigned int t_row; unsigned int t_first; unsigned int t_middle; unsigned int t_last; unsigned int frame_interval; unsigned int frame_usec_max; unsigned int frame_err_cnt; unsigned int last_exp_time; unsigned int last_trig_delay; unsigned int last_meta_cnt; unsigned int last_trig_cnt; struct timeval last_tv_intr; struct timeval tv_intr; unsigned long ts_link_change; zynq_stats_t stats[VIDEO_STATS_NUM]; char prefix[ZYNQ_LOG_PREFIX_LEN]; void (*read_em_data)(struct zynq_video *, void *); } zynq_video_t; extern void zvideo_rx_proc(zynq_video_t *zvideo); extern void zvideo_err_proc(zynq_video_t *zvideo, int ch_err_status); extern int zvideo_init(zynq_video_t *zvideo); extern void zvideo_fini(zynq_video_t *zvideo); extern int zvideo_register_vdev(zynq_video_t *zvideo); extern void zvideo_unregister_vdev(zynq_video_t *zvideo); extern void zvideo_link_change(zynq_video_t *zvideo); extern void zvideo_get_timestamp(struct timeval *tv); extern void zvideo_watchdog(zynq_video_t *zvideo); extern struct v4l2_pix_format zvideo_formats[]; extern unsigned int zynq_video_buf_num; extern unsigned int zynq_video_zero_copy; extern unsigned int zynq_video_ts_type; extern int zynq_video_flash_16; extern int zynq_video_pin_swap; #endif /* _BASA_VIDEO_H_ */
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_regs.h
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _BASA_REGS_H_ #define _BASA_REGS_H_ /* Sensor FPGA device IDs */ #define PCI_VENDOR_ID_BAIDU 0x1D22 #define PCI_DEVICE_ID_MOONROVER 0x2083 #define ZYNQ_DRV_NAME "basa" #define ZYNQ_MOD_VER "3.0.0.5" /* * The system clock accuracy is within 30 ppm. * That is, the system time can drift up to 30 microseconds per second. */ #define ZYNQ_SYS_TIME_DRIFT 30 #define ZYNQ_GPS_SYNC_TIME_MAX (100*24*3600) /* 100 days */ #define ZYNQ_GPS_SYNC_TIME_SMOOTH 1 /* 1 second */ #define ZYNQ_GPS_SYNC_TIME_DEFAULT 10 /* 10 seconds */ #define ZYNQ_GPS_SMOOTH_STEP_DEFAULT 1000 /* 1 ms */ #define ZYNQ_GPS_SMOOTH_STEP_MIN 16 /* 16 us */ #define ZYNQ_GPS_SMOOTH_STEP_MAX 500000 /* 500 ms */ /* * Maximum number of device nodes created. */ #define ZYNQ_MINOR_COUNT 22 /* Video and CAN channel mappings */ #define ZYNQ_DMA_CHAN_NUM_MR 16 #define ZYNQ_VIDEO_MAP_MR 0x001F #define ZYNQ_CAN_MAP_MR 0x3C00 #define ZYNQ_INT_PER_CHAN 1 #define ZYNQ_INT_PER_CARD 16 #define ZYNQ_I2C_BUS_NUM 4 #define GET_BITS(bits, reg_val) \ (((reg_val) >> bits ## _OFFSET) & bits ## _MASK) #define SET_BITS(bits, reg_val, data) \ (((reg_val) & ~(bits ## _MASK << bits ## _OFFSET)) | \ (((data) & bits ## _MASK) << bits ## _OFFSET)) /* * Global registers: BAR0 0x0000 - 0x01FF */ #define ZYNQ_G_VERSION 0x000 #define ZYNQ_VER_ARM_MAJOR(x) (((x) >> 24) & 0xF) #define ZYNQ_VER_ARM_MINOR(x) (((x) >> 16) & 0xF) #define ZYNQ_VER_PL_MAJOR(x) (((x) >> 8) & 0xF) #define ZYNQ_VER_PL_MINOR(x) ((x) & 0xF) #define ZYNQ_FW_IMAGE_TYPE(x) (((x) >> 12) & 0xF) #define ZYNQ_G_SCRATCH 0x004 #define ZYNQ_G_STATUS 0x008 #define ZYNQ_STATUS_BUS_MASTER_DISABLE (1 << 0) #define ZYNQ_STATUS_TRIGGER_ALARM (1 << 16) #define ZYNQ_STATUS_PPS_ALARM (1 << 17) #define ZYNQ_STATUS_GPS_LOCKED (1 << 18) #define ZYNQ_STATUS_PPS_LOCKED (1 << 19) #define ZYNQ_G_CONFIG 0x020 #define ZYNQ_CONFIG_FW_UPLOAD (1 << 0) #define ZYNQ_CONFIG_FW_UPLOAD_MAGIC 0x00000BCD /* FLASH update: bit2:1, 00 and 11 are invalid values */ #define ZYNQ_CONFIG_FW_UPDATE_QSPI (1 << 1) #define ZYNQ_CONFIG_FW_UPDATE_MMC (1 << 2) #define ZYNQ_CONFIG_FW_UPDATE_SPI (1 << 3) #define ZYNQ_CONFIG_GPS_ERR_EN (1 << 12) #define ZYNQ_CONFIG_TRIGGER_ONE (1 << 16) #define ZYNQ_CONFIG_GPS_SW (1 << 17) #define ZYNQ_CONFIG_TRIGGER (1 << 18) #define ZYNQ_CONFIG_TRIGGER_MASK 0x00070000 #define ZYNQ_CONFIG_PS_TXHP_EN (1 << 24) #define ZYNQ_CONFIG_PS_TXLP_EN (1 << 25) #define ZYNQ_G_RESET 0x024 #define ZYNQ_GLOBAL_RESET (1 << 0) #define ZYNQ_I2C_RESET (1 << 4) #define ZYNQ_G_INTR_STATUS_TX 0x100 #define ZYNQ_G_INTR_MASK_TX 0x104 #define ZYNQ_G_INTR_UNMASK_TX 0x108 #define ZYNQ_INTR_CH_TX(ch) (1 << (ch)) #define ZYNQ_INTR_CH_TX_ERR(ch) (1 << ((ch) + 16)) #define ZYNQ_INTR_CH_TX_ALL(ch) \ (ZYNQ_INTR_CH_TX(ch) | ZYNQ_INTR_CH_TX_ERR(ch)) #define ZYNQ_INTR_TX_ALL 0xFFFFFFFF #define ZYNQ_G_INTR_STATUS_RX 0x110 #define ZYNQ_G_INTR_MASK_RX 0x114 #define ZYNQ_G_INTR_UNMASK_RX 0x118 #define ZYNQ_INTR_CH_RX(ch) (1 << (ch)) #define ZYNQ_INTR_CH_RX_ERR(ch) (1 << ((ch) + 16)) #define ZYNQ_INTR_CH_RX_ALL(ch) \ (ZYNQ_INTR_CH_RX(ch) | ZYNQ_INTR_CH_RX_ERR(ch)) #define ZYNQ_INTR_RX_ALL 0xFFFFFFFF #define ZYNQ_G_PS_INTR_STATUS 0x120 #define ZYNQ_G_PS_INTR_MASK 0x124 #define ZYNQ_PS_INTR_FWUPLOAD_GRANT (1 << 0) #define ZYNQ_PS_INTR_FWUPDATE_DONE (1 << 1) #define ZYNQ_PS_INTR_GPS_PPS_CHG (1 << 4) #define ZYNQ_PS_INTR_GPS_PPS 0x10 #define ZYNQ_PS_INTR_FW 0x3 #define ZYNQ_PS_INTR_ALL 0x13 #define ZYNQ_G_DEBUG_CFG0 0x1D0 #define ZYNQ_G_DEBUG_CFG1 0x1D4 #define ZYNQ_G_DEBUG_CFG2 0x1D8 #define ZYNQ_G_DEBUG_CFG3 0x1DC #define ZYNQ_G_DEBUG_STA0 0x1E0 #define ZYNQ_G_DEBUG_STA1 0x1E4 #define ZYNQ_G_DEBUG_STA2 0x1E8 #define ZYNQ_G_DEBUG_STA3 0x1EC #define ZYNQ_G_DEBUG_CNT_CFG 0x1F0 #define ZYNQ_G_DEBUG_CNT0 0x1F4 #define ZYNQ_G_DEBUG_CNT1 0x1F8 #define ZYNQ_G_DEBUG_CNT2 0x1FC /* * Per DMA Channel Control and Status Regsters: * BAR0 0x1000 - 0x1FFFF * Channel Offset: 0x100 * N */ #define ZYNQ_CHAN_REG_MIN 0x1000 #define ZYNQ_CHAN_REG_MAX 0x1FFF #define ZYNQ_CHAN_REG_OFFSET 0x100 #define ZYNQ_CH_TX_HEAD_HI 0x1000 #define ZYNQ_CH_TX_HEAD_LO 0x1004 #define ZYNQ_CH_TX_TAIL_HI 0x1008 #define ZYNQ_CH_TX_TAIL_LO 0x100C #define ZYNQ_CH_TX_RING_SZ 0x1010 #define ZYNQ_CH_DMA_CONTROL 0x1020 #define ZYNQ_CH_DMA_RD_START (1 << 0) #define ZYNQ_CH_DMA_RD_STOP (1 << 1) #define ZYNQ_CH_DMA_WR_START (1 << 4) #define ZYNQ_CH_DMA_WR_STOP (1 << 5) #define ZYNQ_CH_DMA_STATUS 0x1024 #define ZYNQ_CH_DMA_RD_BUSY (1 << 0) #define ZYNQ_CH_DMA_WR_BUSY (1 << 4) #define ZYNQ_CH_DMA_RD_BUF_FULL (1 << 8) #define ZYNQ_CH_DMA_WR_STATE_OFFSET 4 #define ZYNQ_CH_DMA_WR_STATE_MASK 0xF #define ZYNQ_CH_DMA_READY 0x5 #define ZYNQ_CH_RX_PDT_HI 0x1040 #define ZYNQ_CH_RX_PDT_LO 0x1044 #define ZYNQ_CH_RX_PDT_SZ 0x1048 #define ZYNQ_CH_RX_TAIL 0x1050 #define ZYNQ_CH_RX_HEAD 0x1054 #define ZYNQ_CH_RX_BUF_FULL (1 << 0) #define ZYNQ_CH_WR_TABLE_CONFIG 0x104C #define ZYNQ_CH_WR_LAST_PT_SZ_MASK 0xFFF #define ZYNQ_CH_DMA_CONFIG 0x1058 #define ZYNQ_CH_DMA_RX_EN (1 << 0) #define ZYNQ_CH_DMA_TX_EN (1 << 2) #define ZYNQ_CH_DMA_EN (ZYNQ_CH_DMA_RX_EN | ZYNQ_CH_DMA_TX_EN) #define ZYNQ_CH_DMA_FRAME_BUF_ALIGN (1 << 4) #define ZYNQ_CH_DMA_CAN_HWTS (1 << 5) #define ZYNQ_CH_DMA_FRAME_SZ_OFFSET 8 #define ZYNQ_CH_DMA_FRAME_SZ_MASK 0xFFFFFF00 #define ZYNQ_CH_RESET 0x105C #define ZYNQ_CH_RESET_EN (1 << 0) #define ZYNQ_CH_DMA_RESET_EN (1 << 1) #define ZYNQ_CH_ERR_STATUS 0x1080 #define ZYNQ_CH_ERR_CAN_BUSOFF (1 << 0) #define ZYNQ_CH_ERR_CAN_STATERR (1 << 1) #define ZYNQ_CH_ERR_CAN_RX_IPOVERFLOW (1 << 2) #define ZYNQ_CH_ERR_CAN_RX_USROVERFLOW (1 << 3) #define ZYNQ_CH_ERR_CAN_TX_TIMEOUT (1 << 4) #define ZYNQ_CH_ERR_CAN_TX_LPFIFOFULL (1 << 5) #define ZYNQ_CH_ERR_CAN_RX_FIFOFULL (1 << 6) #define ZYNQ_CH_ERR_CAN_TX_HPFIFOFULL (1 << 7) #define ZYNQ_CH_ERR_CAN_CRC_ERR (1 << 8) #define ZYNQ_CH_ERR_CAN_FRAME_ERR (1 << 9) #define ZYNQ_CH_ERR_CAN_STUFF_ERR (1 << 10) #define ZYNQ_CH_ERR_CAN_BIT_ERR (1 << 11) #define ZYNQ_CH_ERR_CAN_ACK_ERR (1 << 12) #define ZYNQ_CH_ERR_CAM_TRIGGER (1 << 13) #define ZYNQ_CH_ERR_CAM_LINK_CHANGE (1 << 14) #define ZYNQ_CH_ERR_DMA_RX_BUF_FULL (1 << 24) #define ZYNQ_CH_ERR_DMA_RX_FIFO_FULL (1 << 25) #define ZYNQ_CH_ERR_MASK_TX 0x1088 #define ZYNQ_CH_ERR_MASK_TX_DEFAULT 0xFF0001EC #define ZYNQ_CH_ERR_MASK_RX 0x108C #define ZYNQ_CH_ERR_MASK_RX_DEFAULT 0xFE0010B0 /* * Device global config and status regsters: * BAR0 0x2000 - 0x2FFF */ #define ZYNQ_G_CAM_TRIG_CFG 0x2000 #define ZYNQ_G_CAM_FPS_DRIFT_OFFSET 4 #define ZYNQ_G_CAM_FPS_DRIFT_MASK 0x1F #define ZYNQ_G_CAM_DELAY_UPDATE_OFFSET 0 #define ZYNQ_G_CAM_DELAY_UPDATE_MASK 0xF /* Needs to read LO first, then HI and Day */ #define ZYNQ_G_NTP_LO 0x2040 #define ZYNQ_G_NTP_HI 0x2044 #define ZYNQ_G_NTP_DATE 0x2048 /* 64 bytes: 16 4-byte read */ #define ZYNQ_G_GPRMC 0x204C #define ZYNQ_G_I2C_CONTROL_0 0x2080 #define ZYNQ_I2C_ADDR_OFFSET 0 #define ZYNQ_I2C_ADDR_MASK 0xFF #define ZYNQ_I2C_ID_OFFSET 8 #define ZYNQ_I2C_ID_MASK 0x7F #define ZYNQ_I2C_DATA_OFFSET 16 #define ZYNQ_I2C_DATA_MASK 0xFF #define ZYNQ_I2C_CMD_READ (1 << 24) #define ZYNQ_I2C_ADDR_16 (1 << 25) #define ZYNQ_I2C_CMD_ERR (1 << 30) /* read only bit */ #define ZYNQ_I2C_CMD_BUSY (1 << 31) /* read only bit */ #define ZYNQ_G_I2C_CONFIG_0 0x2084 #define ZYNQ_I2C_ADDR_HI_OFFSET 0 #define ZYNQ_I2C_ADDR_HI_MASK 0xFF #define ZYNQ_G_I2C_CONTROL_1 0x2088 #define ZYNQ_G_I2C_CONFIG_1 0x208C #define ZYNQ_G_I2C_CONTROL_2 0x2090 #define ZYNQ_G_I2C_CONFIG_2 0x2094 #define ZYNQ_G_I2C_CONTROL_3 0x2098 #define ZYNQ_G_I2C_CONFIG_3 0x209C #define ZYNQ_G_GPS_CONFIG 0x2100 #define ZYNQ_GPS_ADJ_STEP_OFFSET 0 #define ZYNQ_GPS_ADJ_STEP_MASK 0xFFFF #define ZYNQ_GPS_MAX_TOLERANCE_OFFSET 16 #define ZYNQ_GPS_MAX_TOLERANCE_MASK 0xFFF #define ZYNQ_GPS_LOOPBACK_EN (1 << 28) #define ZYNQ_GPS_DISABLE_SMOOTH (1 << 30) #define ZYNQ_GPS_USE_LOCAL_ONLY (1 << 31) #define ZYNQ_G_GPS_TIME_LO_INIT 0x2104 #define ZYNQ_GPS_TIME_VALID (1 << 0) #define ZYNQ_GPS_TIME_NSEC_OFFSET 1 #define ZYNQ_GPS_TIME_NSEC_MASK 0x7F #define ZYNQ_GPS_TIME_USEC_OFFSET 8 #define ZYNQ_GPS_TIME_USEC_MASK 0xFFF #define ZYNQ_GPS_TIME_MSEC_OFFSET 20 #define ZYNQ_GPS_TIME_MSEC_MASK 0xFFF #define ZYNQ_G_GPS_TIME_HI_INIT 0x2108 #define ZYNQ_GPS_TIME_SEC_OFFSET 0 #define ZYNQ_GPS_TIME_SEC_MASK 0xFF #define ZYNQ_GPS_TIME_MIN_OFFSET 8 #define ZYNQ_GPS_TIME_MIN_MASK 0xFF #define ZYNQ_GPS_TIME_HOUR_OFFSET 16 #define ZYNQ_GPS_TIME_HOUR_MASK 0xFF #define ZYNQ_G_GPS_CONFIG_2 0x210C #define ZYNQ_GPS_TIME_YEAR_OFFSET 0 #define ZYNQ_GPS_TIME_YEAR_MASK 0xFF #define ZYNQ_GPS_TIME_MON_OFFSET 8 #define ZYNQ_GPS_TIME_MON_MASK 0xFF #define ZYNQ_GPS_TIME_DAY_OFFSET 16 #define ZYNQ_GPS_TIME_DAY_MASK 0xFF #define ZYNQ_GPS_PPS_LOCK_DELAY_OFFSET 24 #define ZYNQ_GPS_PPS_LOCK_DELAY_MASK 0x7F #define ZYNQ_GPS_CHECKSUM_CHECK (1 << 31) #define ZYNQ_G_GPS_STATUS 0x2110 #define ZYNQ_GPS_INIT_SET (1 << 29) #define ZYNQ_GPS_SMOOTH_IN_PROGRESS (1 << 30) #define ZYNQ_GPS_LOCAL_SYNC_DONE (1 << 31) #define ZYNQ_G_GPS_LAST_TIME_LO 0x2118 #define ZYNQ_G_GPS_LAST_TIME_HI 0x211C #define ZYNQ_G_GPS_LAST_TIME_DATE 0x2120 /* * Camera Per Channel Registers: * BAR0 0x3000 - 0x3FFF * Channel Offset: 0x100 * N */ #define ZYNQ_CAM_REG_MIN 0x3000 #define ZYNQ_CAM_REG_MAX 0x3FFF #define ZYNQ_CAM_REG_OFFSET 0x100 #define ZYNQ_CAM_CONFIG 0x3000 #define ZYNQ_CAM_EN (1 << 0) #define ZYNQ_CAM_TEST_PATTERN_OFFSET 1 #define ZYNQ_CAM_TEST_PATTERN_MASK 0x3 #define ZYNQ_CAM_RGB_YUV_SEL (1 << 3) #define ZYNQ_CAM_COLOR_SWAP (1 << 4) #define ZYNQ_CAM_TIMESTAMP_RCV (1 << 5) #define ZYNQ_CAM_SENSOR_RESET (1 << 6) #define ZYNQ_CAM_POWER_DOWN (1 << 7) #define ZYNQ_CAM_FOOTER_OFFSET 8 #define ZYNQ_CAM_FOOTER_MASK 0xF #define ZYNQ_CAM_HEADER_OFFSET 12 #define ZYNQ_CAM_HEADER_MASK 0xF #define ZYNQ_CAM_PIN_SWAP (1 << 20) #define ZYNQ_CAM_TRIGGER 0x3004 #define ZYNQ_CAM_TRIG_DELAY_OFFSET 0 #define ZYNQ_CAM_TRIG_DELAY_MASK 0x1FFFF #define ZYNQ_CAM_TRIG_POLARITY_LOW (1 << 20) #define ZYNQ_CAM_TRIG_FPS_OFFSET 24 #define ZYNQ_CAM_TRIG_FPS_MASK 0x1F #define ZYNQ_CAM_STATUS 0x3020 #define ZYNQ_CAM_FPD_UNLOCK (1 << 0) #define ZYNQ_CAM_FPD_BIST_FAIL (1 << 2) #define ZYNQ_CAM_FPD_RESET (1 << 3) #define ZYNQ_CAM_FPD_PWDN (1 << 4) #define ZYNQ_CAM_RGB_TPG_ERR (1 << 5) #define ZYNQ_CAM_YUV_TPG_ERR (1 << 6) #define ZYNQ_CAM_FIFO_FULL (1 << 7) /* * Xilinx CAN IP Per Channel Registers: * BAR2 0x0000 - 0x0FFF * Channel Offset: 0x200 * N */ #define ZCAN_IP_OFFSET 0x200 /* Software Reset Register */ #define ZCAN_IP_SRR 0x000 #define ZCAN_IP_SRR_SRST (1 << 0) /* Softweare reset bit */ #define ZCAN_IP_SRR_CEN (1 << 1) /* CAN enable bit */ /* Mode Select Register */ #define ZCAN_IP_MSR 0x004 #define ZCAN_IP_MSR_NORMAL 0x0 #define ZCAN_IP_MSR_SLEEP 0x1 #define ZCAN_IP_MSR_LOOPBACK 0x2 /* Baud Rate Prescaler Register */ #define ZCAN_IP_BRPR 0x008 #define ZCAN_IP_BRPR_1M 0x000 #define ZCAN_IP_BRPR_500K 0x001 #define ZCAN_IP_BRPR_250K 0x003 #define ZCAN_IP_BRPR_125K 0x007 /* Bit Timing Register */ #define ZCAN_IP_BTR 0x00C #define ZCAN_IP_BTR_DEFAULT 0xA3 /* Error Counter Register */ #define ZCAN_IP_ECR 0x010 /* Error Status Register */ #define ZCAN_IP_ESR 0x014 /* Status Register */ #define ZCAN_IP_SR 0x018 /* Interrupt Status Register */ #define ZCAN_IP_ISR 0x01C /* Interrupt Enable Register */ #define ZCAN_IP_IER 0x020 /* Interrupt Clear Register */ #define ZCAN_IP_ICR 0x024 #define ZCAN_IP_INTR_ARBLST (1 << 0) /* Arbitration Lost */ #define ZCAN_IP_INTR_TXOK (1 << 1) /* Tx OK */ #define ZCAN_IP_INTR_TXFULL (1 << 2) /* Tx FIFO full */ #define ZCAN_IP_INTR_TXBFULL (1 << 3) /* High priority Tx FIFO full */ #define ZCAN_IP_INTR_RXOK (1 << 4) /* Rx OK */ #define ZCAN_IP_INTR_RXUFLW (1 << 5) /* Rx FIFO underflow */ #define ZCAN_IP_INTR_RXOFLW (1 << 6) /* Rx FIFO overflow */ #define ZCAN_IP_INTR_RXNEMP (1 << 7) /* Rx FIFO not empty */ #define ZCAN_IP_INTR_ERROR (1 << 8) /* error interrupt */ #define ZCAN_IP_INTR_BUSOFF (1 << 9) /* Bus Off interrupt */ #define ZCAN_IP_INTR_SLEEP (1 << 10) /* sleep interrupt */ #define ZCAN_IP_INTR_WAKEUP (1 << 11) /* wakeup interrupt */ #define ZCAN_IP_INTR_ALL 0x352 /* Acceptance Filtering registers: Filter Mask/Filter ID */ #define ZCAN_IP_AFR 0x060 #define ZCAN_IP_AFR_UAF1 (1 << 0) /* use acceptance filter number 1 */ #define ZCAN_IP_AFR_UAF2 (1 << 1) /* use acceptance filter number 2 */ #define ZCAN_IP_AFR_UAF3 (1 << 2) /* use acceptance filter number 3 */ #define ZCAN_IP_AFR_UAF4 (1 << 3) /* use acceptance filter number 4 */ #define ZCAN_IP_AFR_NONE 0 #define ZCAN_IP_AFMR_1 0x064 #define ZCAN_IP_AFIR_1 0x068 #define ZCAN_IP_AFMR_2 0x06C #define ZCAN_IP_AFIR_2 0x070 #define ZCAN_IP_AFMR_3 0x074 #define ZCAN_IP_AFIR_3 0x078 #define ZCAN_IP_AFMR_4 0x07C #define ZCAN_IP_AFIR_4 0x080 #define ZCAN_IP_AF_ERTR (1 < 0) /* extended msg: Remote Tx Request */ #define ZCAN_IP_AF_EID 0x7FFFE /* extended message ID[17:0] */ #define ZCAN_IP_AF_IDE (1 << 19) /* indentifier extension bit */ #define ZCAN_IP_AF_SRTR (1 << 20) /* standard msg: Remote Tx Request */ #define ZCAN_IP_AF_SID 0xFFE00000 /* standard message ID[28:18] */ /* TXFIFO/TXHPB/RXFIFO message storage register */ #define ZCAN_IP_TXFIFO_ID 0x100 #define ZCAN_IP_TXFIFO_DLC 0x104 #define ZCAN_IP_TXFIFO_DW1 0x108 #define ZCAN_IP_TXFIFO_DW2 0x10C #define ZCAN_IP_TXHPB_ID 0x110 #define ZCAN_IP_TXHPB_DLC 0x114 #define ZCAN_IP_TXHPB_DW1 0x118 #define ZCAN_IP_TXHPB_DW2 0x11C #define ZCAN_IP_RXFIFO_ID 0x120 #define ZCAN_IP_RXFIFO_DLC 0x124 #define ZCAN_IP_RXFIFO_DW1 0x128 #define ZCAN_IP_RXFIFO_DW2 0x12C #define ZCAN_IP_PIO_STATUS 0x130 #define ZCAN_IP_PIO_RX_READY (1 << 0) #define ZCAN_IP_PIO_TX_FULL (1 << 1) #define ZCAN_IP_PIO_TX_HI_FULL (1 << 2) /* Debug registers */ #define ZCAN_IP_CFG0 0x134 #define ZCAN_IP_DBG_CNT0 0x180 #define ZCAN_IP_DBG_CNT1 0x184 #endif /* _BASA_REGS_H_ */
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_reg.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "basa.h" /* * Register access support ioctls */ #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) static int zynq_reg_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg) #else static long zynq_reg_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) #endif { zynq_dev_t *zdev = filp->private_data; ioc_zynq_reg_acc_t reg_acc; ioc_zynq_i2c_acc_t i2c_acc; int err = 0; switch (cmd) { case ZYNQ_IOC_REG_READ: if (copy_from_user(&reg_acc, (void __user *)arg, sizeof(ioc_zynq_reg_acc_t))) { zynq_err("%d ZYNQ_IOC_REG_READ: copy_from_user " "failed\n", zdev->zdev_inst); err = -EFAULT; break; } if (reg_acc.reg_bar == 0) { reg_acc.reg_data = zynq_g_reg_read(zdev, reg_acc.reg_offset); } else if (reg_acc.reg_bar == 2) { reg_acc.reg_data = zynq_bar2_reg_read(zdev, reg_acc.reg_offset); } else { zynq_err("%d ZYNQ_IOC_REG_READ: wrong BAR number " "%d\n", zdev->zdev_inst, reg_acc.reg_bar); err = -EINVAL; break; } zynq_trace(ZYNQ_TRACE_REG, "zynq %d ZYNQ_IOC_REG_READ: " "reg_bar=%d, reg_offset=0x%x, reg_data=0x%x\n", zdev->zdev_inst, reg_acc.reg_bar, reg_acc.reg_offset, reg_acc.reg_data); if (copy_to_user((void __user *)arg, &reg_acc, sizeof(ioc_zynq_reg_acc_t))) { zynq_err("%d ZYNQ_IOC_REG_READ: copy_to_user " "failed\n", zdev->zdev_inst); err = -EFAULT; } break; case ZYNQ_IOC_REG_WRITE: if (copy_from_user(&reg_acc, (void __user *)arg, sizeof(ioc_zynq_reg_acc_t))) { zynq_err("%d ZYNQ_IOC_REG_WRITE: copy_from_user " "failed\n", zdev->zdev_inst); err = -EFAULT; break; } if (reg_acc.reg_bar == 0) { zynq_g_reg_write(zdev, reg_acc.reg_offset, reg_acc.reg_data); } else if (reg_acc.reg_bar == 2) { zynq_bar2_reg_write(zdev, reg_acc.reg_offset, reg_acc.reg_data); } else { zynq_err("%d ZYNQ_IOC_REG_WRITE: wrong BAR number " "%d\n", zdev->zdev_inst, reg_acc.reg_bar); err = -EINVAL; break; } zynq_trace(ZYNQ_TRACE_REG, "zynq %d ZYNQ_IOC_REG_WRITE: " "reg_bar=%d, reg_offset=0x%x, reg_data=0x%x\n", zdev->zdev_inst, reg_acc.reg_bar, reg_acc.reg_offset, reg_acc.reg_data); break; case ZYNQ_IOC_REG_I2C_READ: if (copy_from_user(&i2c_acc, (void __user *)arg, sizeof(ioc_zynq_i2c_acc_t))) { zynq_err("%d ZYNQ_IOC_REG_I2C_READ: copy_from_user " "failed\n", zdev->zdev_inst); err = -EFAULT; break; } err = zdev_i2c_read(zdev, &i2c_acc); if (err) { break; } if (copy_to_user((void __user *)arg, &i2c_acc, sizeof(ioc_zynq_i2c_acc_t))) { zynq_err("%d ZYNQ_IOC_REG_I2C_READ: copy_to_user " "failed\n", zdev->zdev_inst); err = -EFAULT; } break; case ZYNQ_IOC_REG_I2C_WRITE: if (copy_from_user(&i2c_acc, (void __user *)arg, sizeof(ioc_zynq_i2c_acc_t))) { zynq_err("%d ZYNQ_IOC_REG_I2C_WRITE: copy_from_user " "failed\n", zdev->zdev_inst); err = -EFAULT; break; } err = zdev_i2c_write(zdev, &i2c_acc); break; case ZYNQ_IOC_REG_GPSPPS_EVENT_WAIT: /* wait for the event notification */ err = wait_for_completion_interruptible( &zdev->zdev_gpspps_event_comp); reinit_completion(&zdev->zdev_gpspps_event_comp); break; case ZYNQ_IOC_STATS_GET: { ioc_zynq_stats_t *ps; zynq_chan_t *zchan; zynq_can_t *zcan; zynq_video_t *zvideo; int i, j, s; ps = kmalloc(sizeof(ioc_zynq_stats_t), GFP_KERNEL); if (!ps) { zynq_err("%d ZYNQ_IOC_STATS_GET: " "failed to alloc buffer\n", zdev->zdev_inst); err = -EFAULT; break; } if (copy_from_user(ps, (void __user *)arg, sizeof(ioc_zynq_stats_t))) { kfree(ps); zynq_err("%d ZYNQ_IOC_STATS_GET: copy_from_user " "failed\n", zdev->zdev_inst); err = -EFAULT; break; } /* Initialize the data */ for (i = 0; i <= ZYNQ_CHAN_MAX; i++) { ps->chs[i].type = ZYNQ_CHAN_INVAL; ps->chs[i].devnum = 0; for (j = 0; j < ZYNQ_STATS_MAX; j++) { ps->chs[i].stats[j] = (unsigned long)-1; } } /* Save the global stats at the additional channel */ for (j = 0; j < DEV_STATS_NUM; j++) { ps->chs[ZYNQ_CHAN_MAX].stats[j] = zdev->stats[j].cnt; } /* Save the per-channel stats */ ASSERT(zdev->zdev_chan_cnt <= ZYNQ_CHAN_MAX); zchan = zdev->zdev_chans; for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: zcan = (zynq_can_t *)zchan->zchan_dev; ps->chs[i].type = zchan->zchan_type; ps->chs[i].devnum = zdev->zdev_can_num_start + zcan->zcan_ip_num; for (s = 0, j = 0; (s < CHAN_STATS_NUM) && (j < ZYNQ_STATS_MAX); s++, j++) { ps->chs[i].stats[j] = zchan->stats[s].cnt; } for (s = 0; (s < CAN_STATS_NUM) && (j < ZYNQ_STATS_MAX); s++, j++) { ps->chs[i].stats[j] = zcan->stats[s].cnt; } break; case ZYNQ_CHAN_VIDEO: zvideo = (zynq_video_t *)zchan->zchan_dev; if (!zvideo->caps.link_up) { break; } ps->chs[i].type = zchan->zchan_type; ps->chs[i].devnum = zvideo->vdev.num; for (s = 0, j = 0; (s < CHAN_STATS_NUM) && (j < ZYNQ_STATS_MAX); s++, j++) { ps->chs[i].stats[j] = zchan->stats[s].cnt; } for (s = 0; (s < VIDEO_STATS_NUM) && (j < ZYNQ_STATS_MAX); s++, j++) { ps->chs[i].stats[j] = zvideo->stats[s].cnt; } break; default: break; } } if (copy_to_user((void __user *)arg, ps, sizeof(ioc_zynq_stats_t))) { zynq_err("%d ZYNQ_IOC_STATS_GET: copy_to_user " "failed\n", zdev->zdev_inst); err = -EFAULT; } kfree(ps); break; } default: err = -EINVAL; break; } zynq_trace(ZYNQ_TRACE_PROBE, "%d %s done: cmd=0x%x, error=%d\n", zdev->zdev_inst, __FUNCTION__, cmd, err); return err; } static int zynq_reg_open(struct inode *inode, struct file *filp) { zynq_dev_t *zdev; zdev = container_of(inode->i_cdev, zynq_dev_t, zdev_cdev_reg); filp->private_data = zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d %s done\n", zdev->zdev_inst, __FUNCTION__); return 0; } static int zynq_reg_release(struct inode *inode, struct file *filp) { return 0; } struct file_operations zynq_reg_fops = { .owner = THIS_MODULE, #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) .ioctl = zynq_reg_ioctl, #else .unlocked_ioctl = zynq_reg_ioctl, #endif .open = zynq_reg_open, .release = zynq_reg_release };
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_fwupdate.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/ktime.h> #include <linux/delay.h> #include "basa.h" /* firmware update registers via PS channel */ #define ZYNQ_PS_DATA_1 0x910 #define ZYNQ_PS_DATA_2 0x914 #define ZYNQ_PS_DATA_3 0x918 #define ZYNQ_PS_DATA_4 0x91C #define ZYNQ_PS_PIO_STATUS 0x930 #define ZYNQ_PS_PIO_TX_FULL (1 << 2) #define ZYNQ_PS_PIO_TX_RETRIES 50 /* n * 200us = 10ms */ #define ZYNQ_PS_WAIT_GRANT_RETRIES 5000 /* n * 200us = 1s */ #define ZYNQ_PS_WAIT_FWUPDATE_RETRIES 600 /* n * 200ms = 2m */ #define ZYNQ_FW_TIMEOUT 1000 /* 1 second: in mili-seonds */ #define ZYNQ_FW_TYPE_MMC 1 #define ZYNQ_FW_TYPE_QSPI 2 #define ZYNQ_FW_TYPE_SPI 3 /* * In firmware updating mode, only channel 0 is enabled to perform in-field * FPGA image upate by interacting with FPGA ARM OS: * - S/W requests FPGA ARM OS for image data transfer by writing * ZYNQ_CONFIG_FW_UPLOAD then ZYNQ_FONCIG_FW_UPLOAD_MAGIC in * ZYNQ_G_CONFIG register. * - S/W waits interrupt ZYNQ_PS_INTR_FWUPLOAD_GRANT to get grant from FPGA * ARM OS for image data transfer. * - S/W sends image data to FPGA in unit of 16 bytes: write ZYNQ_PS_DATA_* * registers in sequence (needs to make sure ZYNQ_PS_PIO_TX_FULL is not * set in register ZYNQ_PS_PIO_STATUS before sending next 16 bytes of data. * - S/W requests FPGA to update QSPI flash/eMMC flash or SPI flash image by * writing ZYNQ_G_CONFIG register with ZYNQ_CONFIG_FW_UPDATE_QSPI, * ZYNQ_CONFIG_FW_UPDATE_MMC or ZYNQ_CONFIG_FW_UPDATE_SPI. * - S/W waits interrupt ZYNQ_PS_INTR_FWUPDATE_DONE for FPGA ARM OS finishes * image update. * - Power cycle system and check FPGA image version from driver prints in * dmesg. */ static int zynq_fw_upload_start(zynq_dev_t *zdev) { u32 val32; int j = 0; val32 = zynq_g_reg_read(zdev, ZYNQ_G_CONFIG); if (val32 & ZYNQ_CONFIG_FW_UPLOAD) { zynq_err("%d %s failed: image upload pending.\n", zdev->zdev_inst, __FUNCTION__); return -EBUSY; } /* clear the interrupt status */ zynq_g_reg_write(zdev, ZYNQ_G_PS_INTR_STATUS, ZYNQ_PS_INTR_FWUPLOAD_GRANT | ZYNQ_PS_INTR_FWUPDATE_DONE); /* request for uploading */ zynq_g_reg_write(zdev, ZYNQ_G_CONFIG, ZYNQ_CONFIG_FW_UPLOAD); zynq_trace(ZYNQ_TRACE_FW, "%d %s: request uploading.\n", zdev->zdev_inst, __FUNCTION__); /* wait for 10ms then write the update magic number */ msleep(10); zynq_g_reg_write(zdev, ZYNQ_G_CONFIG, ZYNQ_CONFIG_FW_UPLOAD_MAGIC); zynq_trace(ZYNQ_TRACE_FW, "%d %s: magic for uploading.\n", zdev->zdev_inst, __FUNCTION__); /* wait for grant response from ARM OS */ while (!(zynq_g_reg_read(zdev, ZYNQ_G_PS_INTR_STATUS) & ZYNQ_PS_INTR_FWUPLOAD_GRANT)) { if (j++ > ZYNQ_PS_WAIT_GRANT_RETRIES) { zynq_err("%d %s failed: wait for upload grant " "timeout\n", zdev->zdev_inst, __FUNCTION__); return -EBUSY; } udelay(200); } zynq_g_reg_write(zdev, ZYNQ_G_CONFIG, 0); zynq_trace(ZYNQ_TRACE_FW, "%d %s: succeeded.\n", zdev->zdev_inst, __FUNCTION__); return 0; } static int zynq_fw_update(zynq_dev_t *zdev, int fw_type, int time_to_wait) { u32 val32, fw_enable; int j = 0; /* add some delay here to make sure the uploading is fully done */ msleep(1); if (fw_type == ZYNQ_FW_TYPE_MMC) { fw_enable = ZYNQ_CONFIG_FW_UPDATE_MMC; } else if (fw_type == ZYNQ_FW_TYPE_QSPI) { fw_enable = ZYNQ_CONFIG_FW_UPDATE_QSPI; } else if (fw_type == ZYNQ_FW_TYPE_SPI) { fw_enable = ZYNQ_CONFIG_FW_UPDATE_SPI; } else { return -EINVAL; } val32 = zynq_g_reg_read(zdev, ZYNQ_G_CONFIG); if (val32 & fw_enable) { zynq_err("%d %s failed: image update pending.\n", zdev->zdev_inst, __FUNCTION__); return -EBUSY; } /* clear the interrupt status */ zynq_g_reg_write(zdev, ZYNQ_G_PS_INTR_STATUS, ZYNQ_PS_INTR_FWUPLOAD_GRANT | ZYNQ_PS_INTR_FWUPDATE_DONE); /* request for updating */ zynq_g_reg_write(zdev, ZYNQ_G_CONFIG, fw_enable); zynq_trace(ZYNQ_TRACE_FW, "%d %s: request updating.\n", zdev->zdev_inst, __FUNCTION__); /* wait for updating response from ARM OS */ while (!(zynq_g_reg_read(zdev, ZYNQ_G_PS_INTR_STATUS) & ZYNQ_PS_INTR_FWUPDATE_DONE)) { if (j++ > time_to_wait * 5 * 2) { zynq_err("%d %s failed: wait for image updating " "timeout\n", zdev->zdev_inst, __FUNCTION__); return -EBUSY; } msleep(200); } zynq_g_reg_write(zdev, ZYNQ_G_CONFIG, 0); zynq_trace(ZYNQ_TRACE_FW, "%d %s: succeeded.\n", zdev->zdev_inst, __FUNCTION__); return 0; } /* * 16-byte data transfer from host to FPGA ARM OS. */ static int zynq_fw_tx_one(zynq_dev_t *zdev, u32 *fw_data, int wait) { int j = 0; /* poll status regsiter to see if the Tx FIFO is FULL */ if (wait) { while (zynq_bar2_reg_read(zdev, ZYNQ_PS_PIO_STATUS) & ZYNQ_PS_PIO_TX_FULL) { if (j++ > ZYNQ_PS_PIO_TX_RETRIES) { zynq_err("%d %s failed: Tx FIFO is FULL\n", zdev->zdev_inst, __FUNCTION__); return -ENOSPC; } udelay(200); } zynq_trace(ZYNQ_TRACE_FW, "%d %s: wait_time = %dus\n", zdev->zdev_inst, __FUNCTION__, j * 200); } else { if (zynq_bar2_reg_read(zdev, ZYNQ_PS_PIO_STATUS) & ZYNQ_PS_PIO_TX_FULL) { return -ENOSPC; } } zynq_bar2_reg_write(zdev, ZYNQ_PS_DATA_1, fw_data[0]); zynq_bar2_reg_write(zdev, ZYNQ_PS_DATA_2, fw_data[1]); zynq_bar2_reg_write(zdev, ZYNQ_PS_DATA_3, fw_data[2]); zynq_bar2_reg_write(zdev, ZYNQ_PS_DATA_4, fw_data[3]); zdev->zdev_fw_tx_cnt++; udelay(100); zynq_trace(ZYNQ_TRACE_FW, "%d %s: msg %u: fw_data[0]=0x%x, " "fw_data[1]=0x%x, fw_data[2]=0x%x, fw_data[3]=0x%x\n", zdev->zdev_inst, __FUNCTION__, zdev->zdev_fw_tx_cnt, fw_data[0], fw_data[1], fw_data[2], fw_data[3]); return 0; } static int zynq_fw_tx_user(zynq_dev_t *zdev, ioc_zynq_fw_upload_t *ioc_arg) { int tx_num = ioc_arg->ioc_zynq_fw_num; int tx_num_done = 0; u32 *fw_data, *fw_data_alloc = NULL; ktime_t ktime_end, ktime_now; int ret = 0; /* alloc memory and copy-in all the sending data */ fw_data_alloc = kmalloc(tx_num * ZYNQ_FW_MSG_SZ, GFP_KERNEL); if (fw_data_alloc == NULL) { return -ENOMEM; } fw_data = fw_data_alloc; if (copy_from_user(fw_data, (void __user *)ioc_arg->ioc_zynq_fw_data, tx_num * ZYNQ_FW_MSG_SZ)) { kfree(fw_data_alloc); return -EFAULT; } ktime_end = ktime_add_ns(ktime_get(), (u64)1000000 * ZYNQ_FW_TIMEOUT); /* send the msg one by one till finished or timeout */ while (tx_num) { ret = zynq_fw_tx_one(zdev, fw_data, 0); if (ret) { /* checking timeout */ ktime_now = ktime_get(); #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 10, 0) if (ktime_now.tv64 < ktime_end.tv64) { #else if (ktime_now < ktime_end) { #endif msleep(1); continue; } break; } tx_num_done++; fw_data += 4; /* 4 * sizeof(int) = 16 bytes */ tx_num--; } ioc_arg->ioc_zynq_fw_done = tx_num_done; kfree(fw_data_alloc); zynq_trace(ZYNQ_TRACE_FW, "%d %s done: tx_num=%d, tx_num_done=%d\n", zdev->zdev_inst, __FUNCTION__, ioc_arg->ioc_zynq_fw_num, tx_num_done); return ret; } #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) static int zynq_fw_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg) #else static long zynq_fw_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) #endif { zynq_dev_t *zdev = filp->private_data; int err = 0; char ioc_name[32]; zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d %s: cmd=0x%x, arg=0x%lx, " "zdev=0x%p\n", zdev->zdev_inst, __FUNCTION__, cmd, arg, zdev); switch (cmd) { case ZYNQ_IOC_FW_IMAGE_UPLOAD_START: sprintf(ioc_name, "ZYNQ_IOC_FW_IMAGE_UPLOAD_START"); err = zynq_fw_upload_start(zdev); break; case ZYNQ_IOC_FW_IMAGE_UPLOAD: { ioc_zynq_fw_upload_t ioc_zynq_fw_arg; sprintf(ioc_name, "ZYNQ_IOC_FW_IMAGE_UPLOAD"); if (copy_from_user(&ioc_zynq_fw_arg, (void __user *)arg, sizeof(ioc_zynq_fw_upload_t))) { err = -EFAULT; break; } if (ZDEV_IS_ERR(zdev)) { err = -EIO; break; } /* call the tx routine to upload the data */ if ((err = zynq_fw_tx_user(zdev, &ioc_zynq_fw_arg))) { break; } if (copy_to_user((void __user *) (&((ioc_zynq_fw_upload_t *)arg)->ioc_zynq_fw_done), &ioc_zynq_fw_arg.ioc_zynq_fw_done, 2 * sizeof(int))) { err = -EFAULT; } break; } case ZYNQ_IOC_FW_QSPI_UPDATE: sprintf(ioc_name, "ZYNQ_IOC_FW_QSPI_UPDATE"); err = zynq_fw_update(zdev, ZYNQ_FW_TYPE_QSPI, arg); break; case ZYNQ_IOC_FW_MMC_UPDATE: sprintf(ioc_name, "ZYNQ_IOC_FW_MMC_UPDATE"); err = zynq_fw_update(zdev, ZYNQ_FW_TYPE_MMC, arg); break; case ZYNQ_IOC_FW_SPI_UPDATE: sprintf(ioc_name, "ZYNQ_IOC_FW_SPI_UPDATE"); err = zynq_fw_update(zdev, ZYNQ_FW_TYPE_SPI, arg); break; case ZYNQ_IOC_FW_GET_VER: sprintf(ioc_name, "ZYNQ_IOC_FW_GET_VER"); if (copy_to_user((void __user *)(int *)arg, &zdev->zdev_version, sizeof(int))) { err = -EFAULT; } break; default: sprintf(ioc_name, "ZYNQ_IOC_FW_UNKNOWN"); err = -EINVAL; break; } zynq_trace(ZYNQ_TRACE_CAN_PIO, "zynq %d %s done: cmd=0x%x(%s), " "error=%d\n", zdev->zdev_inst, __FUNCTION__, cmd, ioc_name, err); return (err); } static int zynq_fw_open(struct inode *inode, struct file *filp) { zynq_dev_t *zdev; zdev = container_of(inode->i_cdev, zynq_dev_t, zdev_cdev_fw); if (atomic_read(&zdev->zdev_fw_opened)) { zynq_err("%s failed: device is opened already\n", __FUNCTION__); return (-EBUSY); } atomic_set(&zdev->zdev_fw_opened, 1); filp->private_data = zdev; zynq_trace(ZYNQ_TRACE_FW, "%s done.", __FUNCTION__); return (0); } static int zynq_fw_release(struct inode *inode, struct file *filp) { zynq_dev_t *zdev = filp->private_data; atomic_set(&zdev->zdev_fw_opened, 0); return (0); } struct file_operations zynq_fw_fops = { .owner = THIS_MODULE, #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) .ioctl = zynq_fw_ioctl, #else .unlocked_ioctl = zynq_fw_ioctl, #endif .open = zynq_fw_open, .release = zynq_fw_release };
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_intr.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "basa.h" /* channel ISR for handling Rx, Rx error, Tx and Tx error */ static irqreturn_t zynq_intr_chan(int irq, void *datap) { zynq_chan_t *zchan = datap; u32 ch = zchan->zchan_num; #ifdef ZYNQ_INTR_PROC_TASKLET tasklet_hi_schedule(&zchan->zdev->zdev_ta[ch]); #else zynq_chan_tasklet((unsigned long)zchan); #endif return IRQ_HANDLED; } static irqreturn_t zynq_intr_fwupdate(zynq_chan_t *zchan) { return IRQ_HANDLED; } /* ISR to handle all the channel interrupts */ static irqreturn_t zynq_intr(int irq, void *datap) { zynq_dev_t *zdev = datap; zynq_chan_t *zchan; zchan = zdev->zdev_chans; if (zynq_fwupdate_param) { return zynq_intr_fwupdate(zchan); } ZYNQ_STATS(zdev, DEV_STATS_INTR); #ifdef ZYNQ_INTR_PROC_TASKLET tasklet_hi_schedule(&zchan->zdev->zdev_ta[0]); #else zynq_tasklet((unsigned long)zdev); #endif return IRQ_HANDLED; } /* enable MSI */ static int zdev_enable_msi(zynq_dev_t *zdev) { int max_nvec = 1; int rc; /* * per channel interrupt is not supported for now * due to an FPGA issue */ msi_retry: #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 11, 0) rc = pci_enable_msi_exact(zdev->zdev_pdev, max_nvec); #else rc = pci_alloc_irq_vectors(zdev->zdev_pdev, max_nvec, max_nvec, PCI_IRQ_MSI); #endif if (rc < 0) { if (max_nvec == 1) { zynq_trace(ZYNQ_TRACE_PROBE, "%s: failed to enable MSI\n", __FUNCTION__); return rc; } zynq_trace(ZYNQ_TRACE_PROBE, "%s: failed to enable MSI nvec=%d, retry nvec=1\n", __FUNCTION__, max_nvec); max_nvec = 1; goto msi_retry; } zdev->zdev_msi_num = max_nvec; zdev->zdev_msi_vec = zdev->zdev_pdev->irq; zynq_trace(ZYNQ_TRACE_PROBE, "%s: enabled %d MSI(s).\n", __FUNCTION__, zdev->zdev_msi_num); return 0; } /* enable MSI-X */ static int zdev_enable_msix(zynq_dev_t *zdev) { int max_nvec; int rc; if (zynq_fwupdate_param) { max_nvec = 1; } else { max_nvec = zdev->zdev_chan_cnt; } zdev->zdev_msixp = kzalloc(sizeof(struct msix_entry) * max_nvec, GFP_KERNEL); if (zdev->zdev_msixp == NULL) { return -ENOMEM; } /* * We support 2 cases: * 1. One interrupt per DMA channel; * 2. One interrupt per device. */ msix_retry: #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 12, 0) rc = pci_enable_msix(zdev->zdev_pdev, zdev->zdev_msixp, max_nvec); #else rc = pci_enable_msix_range(zdev->zdev_pdev, zdev->zdev_msixp, max_nvec, max_nvec); #endif if (rc < 0) { zynq_trace(ZYNQ_TRACE_PROBE, "%s: failed to enable MSI-X nvec=%d\n", __FUNCTION__, max_nvec); kfree(zdev->zdev_msixp); zdev->zdev_msixp = NULL; return rc; } else if (rc > 0) { zynq_trace(ZYNQ_TRACE_PROBE, "%s: failed to enable MSI-X nvec=%d, retry nvec=1\n", __FUNCTION__, max_nvec); max_nvec = 1; goto msix_retry; } zdev->zdev_msix_num = max_nvec; zynq_trace(ZYNQ_TRACE_PROBE, "%s: enabled %d MSI-X(s).\n", __FUNCTION__, zdev->zdev_msix_num); return 0; } static int zdev_setup_msix(zynq_dev_t *zdev) { zynq_chan_t *zchan; int i = 0; int rc = 0; zchan = zdev->zdev_chans; if (zdev->zdev_msix_num == 1) { rc = request_irq(zdev->zdev_msixp[0].vector, zynq_intr, 0, ZYNQ_DRV_NAME, zdev); if (rc) { return (rc); } } else { for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { rc = request_irq(zdev->zdev_msixp[i].vector, zynq_intr_chan, 0, ZYNQ_DRV_NAME, zchan); if (rc) { goto msix_fail; } } } return 0; msix_fail: while (i) { i--; zchan--; free_irq(zdev->zdev_msixp[i].vector, zchan); } return rc; } static int zdev_setup_msi(zynq_dev_t *zdev) { zynq_chan_t *zchan; int i = 0; int rc = 0; zchan = zdev->zdev_chans; if (zdev->zdev_msi_num == 1) { rc = request_irq(zdev->zdev_msi_vec, zynq_intr, 0, ZYNQ_DRV_NAME, zdev); if (rc) { return (rc); } } else { for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { rc = request_irq(zdev->zdev_msi_vec + i, zynq_intr_chan, 0, ZYNQ_DRV_NAME, zchan); if (rc) { goto msi_fail; } } } return 0; msi_fail: while (i) { i--; zchan--; free_irq(zdev->zdev_msi_vec + i, zchan); } return rc; } #ifdef ZYNQ_INTR_PROC_TASKLET static void zdev_init_tasklet(zynq_dev_t *zdev) { zynq_chan_t *zchan; int intr_num; int i; /* legacy interrupt */ if (zdev->zdev_msixp == NULL && zdev->zdev_msi_num == 0) { tasklet_init(&zdev->zdev_ta[0], zynq_tasklet, (unsigned long)zdev); return; } if (zdev->zdev_msixp) { intr_num = zdev->zdev_msix_num; /* MSI-X */ } else { intr_num = zdev->zdev_msi_num; /* MSI */ } /* init tasklets according to the allocated interrupt number */ zchan = zdev->zdev_chans; if (intr_num == 1) { tasklet_init(&zdev->zdev_ta[0], zynq_tasklet, (unsigned long)zdev); } else { for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { tasklet_init(&zdev->zdev_ta[i], zynq_chan_tasklet, (unsigned long)zchan); } } } static void zdev_fini_tasklet(zynq_dev_t *zdev) { int intr_num; int i; /* legacy interrupt */ if (zdev->zdev_msixp == NULL && zdev->zdev_msi_num == 0) { tasklet_kill(&zdev->zdev_ta[0]); return; } if (zdev->zdev_msixp) { intr_num = zdev->zdev_msix_num; /* MSI-X */ } else { intr_num = zdev->zdev_msi_num; /* MSI */ } /* interrupt number per channal */ for (i = 0; i < intr_num; i++) { tasklet_kill(&zdev->zdev_ta[i]); } } #endif /* * Allocate and enabling interrupt: try MSI-X first, then MSI, last * is legacy inerrupt. * 16 MSI/MSI-X: * [15:0] per channel interrupts * 1 MSI/MSI-X/Legacy interrupt: * [0] per card interrupts for all the channels */ int zynq_alloc_irq(zynq_dev_t *zdev) { int rc; /* try MSI-X first */ if (zdev_enable_msix(zdev)) { /* failed, try MSI next */ (void) zdev_enable_msi(zdev); } #ifdef ZYNQ_INTR_PROC_TASKLET /* tasklets have to be initialized before requesting irqs */ zdev_init_tasklet(zdev); #endif if ((zdev->zdev_msixp == NULL) && (zdev->zdev_msi_num == 0)) { /* Both MSI-X and MSI failed: try legacy interrupt */ rc = request_irq(zdev->zdev_pdev->irq, zynq_intr, IRQF_SHARED, ZYNQ_DRV_NAME, zdev); if (rc) { return rc; } } else if (zdev->zdev_msixp) { /* MSI-X */ rc = zdev_setup_msix(zdev); if (rc) { pci_disable_msix(zdev->zdev_pdev); kfree(zdev->zdev_msixp); zdev->zdev_msixp = NULL; zdev->zdev_msix_num = 0; return rc; } } else { /* MSI */ rc = zdev_setup_msi(zdev); if (rc) { pci_disable_msi(zdev->zdev_pdev); zdev->zdev_msi_num = 0; return rc; } } zynq_trace(ZYNQ_TRACE_PROBE, "%s: succeeded.\n", __FUNCTION__); return 0; } /* * Disable and free interrupt */ void zynq_free_irq(zynq_dev_t *zdev) { zynq_chan_t *zchan; u32 vector; int i; zynq_trace(ZYNQ_TRACE_PROBE, "%s: enter\n", __FUNCTION__); if (zdev->zdev_msixp == NULL && zdev->zdev_msi_num == 0) { /* legacy interrupt */ free_irq(zdev->zdev_pdev->irq, zdev); } else if (zdev->zdev_msixp) { /* MSI-X */ if (zdev->zdev_msix_num == 1) { free_irq(zdev->zdev_msixp[0].vector, zdev); } else { zchan = zdev->zdev_chans; for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { vector = zdev->zdev_msixp[i].vector; free_irq(vector, zchan); } } pci_disable_msix(zdev->zdev_pdev); } else { /* MSI */ if (zdev->zdev_msi_num == 1) { free_irq(zdev->zdev_msi_vec, zdev); } else { zchan = zdev->zdev_chans; for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { vector = zdev->zdev_msi_vec + i; free_irq(vector, zchan); } } pci_disable_msi(zdev->zdev_pdev); } #ifdef ZYNQ_INTR_PROC_TASKLET /* kill the tasklets after irqs are freed */ zdev_fini_tasklet(zdev); #endif if (zdev->zdev_msixp) { kfree(zdev->zdev_msixp); zdev->zdev_msixp = NULL; zdev->zdev_msix_num = 0; } zdev->zdev_msi_num = 0; zynq_trace(ZYNQ_TRACE_PROBE, "%s: done\n", __FUNCTION__); }
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/Makefile
# # Makefile for Baidu Sensor Aggregation driver # BAIDUROOT=../../../../.. obj-m += basa.o basa-objs := basa_driver.o basa_intr.o \ basa_main.o basa_chan.o basa_sysfs.o basa_fwupdate.o \ basa_can.o basa_video.o basa_cam_hci.o basa_gps.o \ basa_trigger.o basa_i2c.o basa_reg.o ccflags-y := -I${PWD}/../../../include/uapi/ KERNEL_SOURCE ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) default: ${MAKE} -C ${KERNEL_SOURCE} M=${PWD} $(MAKE_OPTS) modules clean: ${MAKE} -C ${KERNEL_SOURCE} M=${PWD} clean rm -f *.o.ur-safe install: default mkdir -p $(BAIDUROOT)/output/kernel/drivers/baidu/basa mkdir -p $(BAIDUROOT)/output/include cp basa.ko $(BAIDUROOT)/output/kernel/drivers/baidu/basa/ cp -r ../../../include/uapi/linux $(BAIDUROOT)/output/include/
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_chan.h
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _BASA_CHAN_H_ #define _BASA_CHAN_H_ struct zynq_dev; #define ZCHAN_ERR_THROTTLE 100 /* msec */ #define ZYNQ_CHAN_INT_RX_INDEX 0 #define ZYNQ_CHAN_INT_RXERR_INDEX 1 #define ZYNQ_CHAN_INT_TX_INDEX 2 #define ZYNQ_CHAN_INT_TXERR_INDEX 3 #define ZYNQ_CHAN_INT_RXALL_INDEX 0 #define ZYNQ_CHAN_INT_TXALL_INDEX 1 #define ZYNQ_CHAN_PROC_TX (1<<0) #define ZYNQ_CHAN_PROC_TX_ERR (1<<1) #define ZYNQ_CHAN_PROC_RX (1<<2) #define ZYNQ_CHAN_PROC_RX_ERR (1<<3) #define ZCHAN_BUF_SIZE 4096 /* channel buffer structure */ typedef struct zchan_buf { void *zchan_bufp; /* buffer virtual address */ /* Keep the page structure for >=4K data buffer */ struct page *zchan_buf_page; /* used for >=4K buffer */ dma_addr_t zchan_buf_dma; /* buffer physical address */ } zchan_buf_t; #define ZCHAN_TX_ENTRIES_CAN 1024 /* Tx descriptor for DMA read channel */ typedef struct zchan_tx_desc { u32 reserved; u32 tx_len; /* tx data size in bytes */ u64 tx_addr; } zchan_tx_desc_t; /* Tx descriptor ring */ typedef struct zchan_tx_ring { struct zynq_chan *zchan; /* backlink to zynq chan */ spinlock_t zchan_tx_lock; /* tx lock */ /* virtual address of the descriptor ring */ zchan_tx_desc_t *zchan_tx_descp; /* physical address of the descriptor ring */ dma_addr_t zchan_tx_dma; u32 zchan_tx_size; /* size of the ring in bytes */ u32 zchan_tx_num; /* # of descriptors in the ring */ u32 zchan_tx_head; /* consumer index of the ring */ u32 zchan_tx_tail; /* producer index of the ring */ /* associated buffer array with zchan_tx_num entries */ u32 zchan_tx_bufsz; /* Tx buffer size */ zchan_buf_t *zchan_tx_bufp; } zchan_tx_ring_t; /* * For Rx, two level page tables are used to address large amount of data. * Driver sets up Page Directory Table (PDT), Page Table (PT) and allocates * Memory Pages (MP). We also provide Page Directory Table (PDT) start address * and number of valid entries to H/W. For PDT and each PT, valid entries are * in contiguous addresses. H/W will lookup PDT followed by PT to get memory * page address, and will send received data to corresponding memory pages. * After data transfer is done, H/W provides MP tail pointer to indicate valid * entries available for driver to process via interrupt, and driver will * update head pointer to indicate entries processed. H/W writes data to memory * pages starting from offset 0 in strictly increasing sequences. From number * of valid entries offset in memory pages, we can trace back table indices * in PDT and PT tables. */ /* page directory table size */ #define ZCHAN_RX_PDT_ENTRIES_CAN 1 /* 2M-byte Rx buffer */ /* page table size */ #define ZCHAN_RX_PT_SIZE 4096 /* don't change to other value */ /* page table entries: ZCHAN_RX_PT_SIZE/8 */ #define ZCHAN_RX_PT_ENTRIES 512 /* Rx page table structure */ typedef struct zchan_rx_pt { u64 *zchan_rx_pt; /* pt virtual address */ dma_addr_t zchan_rx_pt_dma; /* assocated buffer for each page table entry */ zchan_buf_t *zchan_rx_pt_bufp; u32 zchan_rx_pt_buf_num; /* number of buffers */ } zchan_rx_pt_t; /* Rx channel structure */ typedef struct zchan_rx_tbl { struct zynq_chan *zchan; /* backlink to zynq chan */ spinlock_t zchan_rx_lock; /* rx lock */ /* page directory table related */ u64 *zchan_rx_pdt; /* pdt virtual address */ dma_addr_t zchan_rx_pdt_dma; /* pdt physical address */ u32 zchan_rx_pdt_num; /* # of pt entries */ u32 zchan_rx_pdt_shift; /* page table related: buffer included */ zchan_rx_pt_t *zchan_rx_ptp; /* zchan_rx_pdt_num entries */ u32 zchan_rx_pt_entries; u32 zchan_rx_pt_mask; u32 zchan_rx_pt_shift; /* * size of Rx buffer space: * zchan_rx_pdt_num * ZCHAN_RX_PT_ENTRIES * zcan_rx_bufsz */ u32 zchan_rx_size; u32 zchan_rx_bufsz; /* Rx buffer size */ u32 zchan_rx_buf_mask; u32 zchan_rx_off; u32 zchan_rx_head; /* consumer offset */ u32 zchan_rx_tail; /* producer offset */ } zchan_rx_tbl_t; #define ZCHAN_WITHIN_RX_BUF(zchan_rx, rx_off1, rx_off2) \ ((rx_off1 & (~zchan_rx->zchan_rx_buf_mask)) == \ (rx_off2 & (~zchan_rx->zchan_rx_buf_mask))) #define ZCHAN_RX_BUF_OFFSET(zchan_rx, rx_off) \ (rx_off & zchan_rx->zchan_rx_buf_mask) #define ZCHAN_RX_PT_ENTRY(zchan_rx, rx_off) \ ((rx_off >> zchan_rx->zchan_rx_pt_shift) & \ zchan_rx->zchan_rx_pt_mask) #define ZCHAN_RX_PDT_ENTRY(zchan_rx, rx_off) \ ((rx_off >> zchan_rx->zchan_rx_pdt_shift) % \ zchan_rx->zchan_rx_pdt_num) #define ZCHAN_RX_FREE_SIZE(zchan_rx, head, tail) \ ((head > tail) ? (head - tail) : \ (zchan_rx->zchan_rx_size + head - tail)) #define ZCHAN_RX_USED_SIZE(zchan_rx, head, tail) \ ((tail >= head) ? (tail - head) : \ (zchan_rx->zchan_rx_size + tail - head)) #define ZYNQ_INST(zchan) (zchan->zdev->zdev_inst) /* * Zynq channel common structure: * each Zynq channel contains a DMA read channel and a DMA write channel. */ typedef struct zynq_chan { /* * Channel common definitions */ struct zynq_dev *zdev; /* backlink to zynq dev */ void *zchan_dev; /* channel specific device */ enum zynq_chan_type zchan_type; int zchan_num; spinlock_t zchan_lock; /* channel lock */ /* VA base for channel configuration and status registers. */ u8 __iomem *zchan_reg; /* DMA read channel */ zchan_tx_ring_t zchan_tx_ring; /* DMA write channel */ zchan_rx_tbl_t zchan_rx_tbl; /* Channel statistics */ zynq_stats_t stats[CHAN_STATS_NUM]; char prefix[ZYNQ_LOG_PREFIX_LEN]; struct completion watchdog_completion; struct task_struct *watchdog_taskp; unsigned int watchdog_interval; unsigned long ts_err[32]; } zynq_chan_t; extern void zchan_fini(zynq_chan_t *zchan); extern int zchan_init(zynq_chan_t *zchan); extern int zchan_tx_one_msg(zynq_chan_t *zchan, void *msg, u32 msgsz); extern void zchan_tx_done(zchan_tx_ring_t *zchan_tx); extern void zchan_rx_off2addr(zchan_rx_tbl_t *zchan_rx, u32 rx_off, void **virt_addr, void **phy_addr); extern void zchan_rx_start(zynq_chan_t *zchan); extern void zchan_rx_stop(zynq_chan_t *zchan); extern void *zchan_alloc_consistent(struct pci_dev *pdev, dma_addr_t *dmap, size_t sz); extern void zchan_free_consistent(struct pci_dev *pdev, void *ptr, dma_addr_t dma, size_t sz); extern void zchan_err_mask(zynq_chan_t *zchan, uint32_t ch_err); extern void zchan_watchdog_complete(zynq_chan_t *zchan); #endif /* _BASA_CHAN_H_ */
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_main.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/module.h> #include <linux/kobject.h> #include "basa.h" /* module parameters */ /* module tracing messages enabling */ unsigned int zynq_trace_param = 0; unsigned int zynq_bringup_param = 0; /* Firmware update enabling to update PL fabric image or PS OS image */ unsigned int zynq_fwupdate_param = 0; /* enabling debug register dump */ unsigned int zynq_dbg_reg_dump_param = 0; /* log interval in second for statistics log throttling */ unsigned int zynq_stats_log_interval = 1; /* driver global variables */ spinlock_t zynq_g_lock; spinlock_t zynq_gps_lock; static int zynq_instance = 0; static unsigned int zynq_can_count = 0; static struct zynq_dev *zynq_dev_list = NULL; static dev_t zynq_g_dev = 0; static int zynq_major = 0; static int zynq_minor = 0; static struct class *zynq_class = NULL; static struct kobject *zynq_kobject; static const char zdev_stats_label[DEV_STATS_NUM][ZYNQ_STATS_LABEL_LEN] = { "Interrupt", "Invalid interrupt", "GPS not locked" }; /* per channel interrupt clearing routine */ void zdev_clear_intr_ch(zynq_dev_t *zdev, int ch) { if (ch >= zdev->zdev_chan_cnt) { return; } zynq_g_reg_write(zdev, ZYNQ_G_INTR_STATUS_TX, ZYNQ_INTR_CH_TX_ALL(ch)); zynq_g_reg_write(zdev, ZYNQ_G_INTR_STATUS_RX, ZYNQ_INTR_CH_RX_ALL(ch)); } /* Clear all error interrupt */ static void zdev_clear_err_intr_all(zynq_dev_t *zdev) { zynq_chan_t *zchan; int i; zchan = zdev->zdev_chans; for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { zchan_reg_write(zchan, ZYNQ_CH_ERR_STATUS, zchan_reg_read(zchan, ZYNQ_CH_ERR_STATUS)); } } /* interrupt clearing routine */ static inline void zdev_clear_intr_all(zynq_dev_t *zdev) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_STATUS_TX, zynq_g_reg_read(zdev, ZYNQ_G_INTR_STATUS_TX)); zynq_g_reg_write(zdev, ZYNQ_G_INTR_STATUS_RX, zynq_g_reg_read(zdev, ZYNQ_G_INTR_STATUS_RX)); zynq_g_reg_write(zdev, ZYNQ_G_PS_INTR_STATUS, zynq_g_reg_read(zdev, ZYNQ_G_PS_INTR_STATUS)); } /* interrupt disable/enabling routines */ static inline void zdev_disable_intr_all(zynq_dev_t *zdev) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_MASK_TX, ZYNQ_INTR_TX_ALL); zynq_g_reg_write(zdev, ZYNQ_G_INTR_MASK_RX, ZYNQ_INTR_RX_ALL); zynq_g_reg_write(zdev, ZYNQ_G_PS_INTR_MASK, ZYNQ_PS_INTR_ALL); } static inline void zdev_enable_intr_all(zynq_dev_t *zdev) { int ch, intr_tx_all = 0, intr_rx_all = 0, intr_ps_all = 0; if (zynq_fwupdate_param) { intr_ps_all = ~ZYNQ_PS_INTR_FW; } else { for (ch = 0; ch < zdev->zdev_chan_cnt; ch++) { intr_tx_all |= ZYNQ_INTR_CH_TX_ALL(ch); intr_rx_all |= ZYNQ_INTR_CH_RX_ALL(ch); } intr_ps_all = ~ZYNQ_PS_INTR_GPS_PPS; } zynq_g_reg_write(zdev, ZYNQ_G_INTR_UNMASK_TX, intr_tx_all); zynq_g_reg_write(zdev, ZYNQ_G_INTR_UNMASK_RX, intr_rx_all); /* no unmask register for PS interrupt */ zynq_g_reg_write(zdev, ZYNQ_G_PS_INTR_MASK, intr_ps_all); } static inline void zdev_disable_intr_ch(zynq_dev_t *zdev, u32 ch) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_MASK_TX, ZYNQ_INTR_CH_TX_ALL(ch)); zynq_g_reg_write(zdev, ZYNQ_G_INTR_MASK_RX, ZYNQ_INTR_CH_RX_ALL(ch)); } static inline void zdev_enable_intr_ch(zynq_dev_t *zdev, u32 ch) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_UNMASK_TX, ZYNQ_INTR_CH_TX_ALL(ch)); zynq_g_reg_write(zdev, ZYNQ_G_INTR_UNMASK_RX, ZYNQ_INTR_CH_RX_ALL(ch)); } static inline void zdev_disable_intr_ch_rx_all(zynq_dev_t *zdev, u32 ch) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_MASK_RX, ZYNQ_INTR_CH_RX_ALL(ch)); } static inline void zdev_enable_intr_ch_rx_all(zynq_dev_t *zdev, u32 ch) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_UNMASK_RX, ZYNQ_INTR_CH_RX_ALL(ch)); } static inline void zdev_disable_intr_ch_tx_all(zynq_dev_t *zdev, u32 ch) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_MASK_TX, ZYNQ_INTR_CH_TX_ALL(ch)); } static inline void zdev_enable_intr_ch_tx_all(zynq_dev_t *zdev, u32 ch) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_UNMASK_TX, ZYNQ_INTR_CH_TX_ALL(ch)); } int zynq_stats_log(zynq_stats_t *stats, int count, int interval) { unsigned long log_interval; if (stats == NULL) { return 0; } stats->cnt += count; if ((zynq_trace_param & ZYNQ_TRACE_STATS) == 0) { log_interval = (interval >= 0) ? interval : (zynq_stats_log_interval * HZ); if ((unsigned long)(jiffies - stats->ts) < log_interval) { return 0; } } stats->ts = jiffies; return 1; } void zynq_chan_err_proc(zynq_chan_t *zchan) { int ch_err_status; ch_err_status = zchan_reg_read(zchan, ZYNQ_CH_ERR_STATUS); zynq_trace(ZYNQ_TRACE_INTR, "%d ch %d %s: err_status=0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, ch_err_status); if (ch_err_status == 0) { return; } switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: zcan_err_proc(zchan->zchan_dev, ch_err_status); break; case ZYNQ_CHAN_VIDEO: zvideo_err_proc(zchan->zchan_dev, ch_err_status); break; default: break; } zchan_err_mask(zchan, ch_err_status); /* clear the errors */ zchan_reg_write(zchan, ZYNQ_CH_ERR_STATUS, ch_err_status); } /* Rx process function on Rx interrupt */ void zynq_chan_rx_proc(zynq_chan_t *zchan) { switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: zcan_rx_proc(zchan->zchan_dev); break; case ZYNQ_CHAN_VIDEO: zvideo_rx_proc(zchan->zchan_dev); break; default: break; } } void zynq_chan_tx_proc(zynq_chan_t *zchan) { zynq_trace(ZYNQ_TRACE_INTR, "%d ch %d %s\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); /* no tx interrupt for camera and CAN pio mode */ if (zchan->zchan_type == ZYNQ_CHAN_VIDEO || (zchan->zchan_type == ZYNQ_CHAN_CAN && !zchan->zdev->zcan_tx_dma)) { return; } zchan_tx_done(&zchan->zchan_tx_ring); } void zynq_chan_proc(zynq_chan_t *zchan, int status) { if (status & ZYNQ_CHAN_PROC_TX) { zynq_chan_tx_proc(zchan); } if (status & ZYNQ_CHAN_PROC_RX) { zynq_chan_rx_proc(zchan); } if ((status & ZYNQ_CHAN_PROC_TX_ERR) || (status & ZYNQ_CHAN_PROC_RX_ERR)) { zynq_chan_err_proc(zchan); } } void zynq_chan_tasklet(unsigned long arg) { zynq_chan_t *zchan = (zynq_chan_t *)arg; zynq_dev_t *zdev = zchan->zdev; u32 rd_intr, wr_intr, ps_intr = 0, status = 0; u32 ch = zchan->zchan_num; rd_intr = zynq_g_reg_read(zdev, ZYNQ_G_INTR_STATUS_TX); wr_intr = zynq_g_reg_read(zdev, ZYNQ_G_INTR_STATUS_RX); if (ch == 0) { ps_intr = zynq_g_reg_read(zdev, ZYNQ_G_PS_INTR_STATUS); if (ps_intr & ZYNQ_PS_INTR_GPS_PPS_CHG) { zynq_gps_pps_changed(zdev); } } zynq_trace(ZYNQ_TRACE_INTR, "%d ch %d %s: rd_intr=0x%x, wr_intr=0x%x, ps_intr=0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, rd_intr, wr_intr, ps_intr); if (wr_intr & ZYNQ_INTR_CH_RX(ch)) { ZYNQ_STATS(zchan, CHAN_STATS_RX_INTR); status |= ZYNQ_CHAN_PROC_RX; } if (rd_intr & ZYNQ_INTR_CH_TX(ch)) { ZYNQ_STATS(zchan, CHAN_STATS_TX_INTR); status |= ZYNQ_CHAN_PROC_TX; } if (wr_intr & ZYNQ_INTR_CH_RX_ERR(ch)) { ZYNQ_STATS(zchan, CHAN_STATS_RX_ERR_INTR); status |= ZYNQ_CHAN_PROC_RX_ERR; } if (rd_intr & ZYNQ_INTR_CH_TX_ERR(ch)) { ZYNQ_STATS(zchan, CHAN_STATS_TX_ERR_INTR); status |= ZYNQ_CHAN_PROC_TX_ERR; } if (status) { zynq_chan_proc(zchan, status); } if (rd_intr) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_STATUS_TX, ZYNQ_INTR_CH_TX_ALL(ch)); } if (wr_intr) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_STATUS_RX, ZYNQ_INTR_CH_RX_ALL(ch)); } if (ps_intr) { zynq_g_reg_write(zdev, ZYNQ_G_PS_INTR_STATUS, ps_intr); } zynq_trace(ZYNQ_TRACE_INTR, "%d ch %d %s: rd_intr=0x%x, wr_intr=0x%x, ps_intr=0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zynq_g_reg_read(zdev, ZYNQ_G_INTR_STATUS_TX), zynq_g_reg_read(zdev, ZYNQ_G_INTR_STATUS_RX), zynq_g_reg_read(zdev, ZYNQ_G_PS_INTR_STATUS)); } void zynq_tasklet(unsigned long arg) { zynq_dev_t *zdev = (zynq_dev_t *)arg; u32 rd_intr, wr_intr, ps_intr; u32 ch, status; zynq_chan_t *zchan = zdev->zdev_chans; /* DMA read interrupts for Tx/Tx error notification */ rd_intr = zynq_g_reg_read(zdev, ZYNQ_G_INTR_STATUS_TX); /* DMA write interrupts for Rx/Rx error notification */ wr_intr = zynq_g_reg_read(zdev, ZYNQ_G_INTR_STATUS_RX); /* * interrupt from ARM core with PS image: currently H/W use it * for GPS/PPS state change notification and firmware image * update notification. */ ps_intr = zynq_g_reg_read(zdev, ZYNQ_G_PS_INTR_STATUS); zynq_trace(ZYNQ_TRACE_INTR, "%d %s: rd_intr=0x%x, wr_intr=0x%x, ps_intr=0x%x\n", zdev->zdev_inst, __FUNCTION__, rd_intr, wr_intr, ps_intr); if (!rd_intr && !wr_intr && !ps_intr) { ZYNQ_STATS(zdev, DEV_STATS_INTR_INVALID); return; } if (ps_intr & ZYNQ_PS_INTR_GPS_PPS_CHG) { zynq_gps_pps_changed(zdev); } for (ch = 0; ch < zdev->zdev_chan_cnt; ch++, zchan++) { status = 0; if (wr_intr & ZYNQ_INTR_CH_RX(ch)) { ZYNQ_STATS(zchan, CHAN_STATS_RX_INTR); status |= ZYNQ_CHAN_PROC_RX; } if (rd_intr & ZYNQ_INTR_CH_TX(ch)) { ZYNQ_STATS(zchan, CHAN_STATS_TX_INTR); status |= ZYNQ_CHAN_PROC_TX; } if (wr_intr & ZYNQ_INTR_CH_RX_ERR(ch)) { ZYNQ_STATS(zchan, CHAN_STATS_RX_ERR_INTR); status |= ZYNQ_CHAN_PROC_RX_ERR; } if (rd_intr & ZYNQ_INTR_CH_TX_ERR(ch)) { ZYNQ_STATS(zchan, CHAN_STATS_TX_ERR_INTR); status |= ZYNQ_CHAN_PROC_TX_ERR; } if (status) { zynq_chan_proc(zchan, status); } } if (rd_intr) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_STATUS_TX, rd_intr); } if (wr_intr) { zynq_g_reg_write(zdev, ZYNQ_G_INTR_STATUS_RX, wr_intr); } if (ps_intr) { zynq_g_reg_write(zdev, ZYNQ_G_PS_INTR_STATUS, ps_intr); } } static void zdev_stats_init(zynq_dev_t *zdev) { int i; for (i = 0; i < DEV_STATS_NUM; i++) { zdev->stats[i].label = zdev_stats_label[i]; } } /* * Allocate the driver structure and initialize the device specific * parameters and capabilities. */ static zynq_dev_t *zdev_alloc(unsigned short zdev_did) { zynq_dev_t *zdev; zynq_chan_t *zchan; zynq_video_t *zvideo; zynq_can_t *zcan; unsigned long chan_map; int i, v, c; zdev = zynq_zdev_init(zdev_did); if (zdev == NULL) { return NULL; } zchan = zdev->zdev_chans; zcan = zdev->zdev_cans; zvideo = zdev->zdev_videos; c = 0; v = 0; for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { zchan->zdev = zdev; zchan->zchan_num = i; zchan->zchan_tx_ring.zchan = zchan; zchan->zchan_rx_tbl.zchan = zchan; chan_map = 1 << i; if (zdev->zdev_can_map & chan_map) { zchan->zchan_type = ZYNQ_CHAN_CAN; zchan->zchan_dev = zcan; zcan->zdev = zdev; zcan->zchan = zchan; zcan->zcan_ip_num = c; zynq_trace(ZYNQ_TRACE_PROBE, "%d %s ch%d can%d\n", zdev->zdev_inst, __FUNCTION__, zchan->zchan_num, zcan->zcan_ip_num); c++; zcan++; } else if (zdev->zdev_video_map & chan_map) { zchan->zchan_type = ZYNQ_CHAN_VIDEO; zchan->zchan_dev = zvideo; zvideo->zdev = zdev; zvideo->zchan = zchan; zvideo->index = v; zynq_trace(ZYNQ_TRACE_PROBE, "%d %s ch%d video%d\n", zdev->zdev_inst, __FUNCTION__, zchan->zchan_num, zvideo->index); v++; zvideo++; } else { continue; } } ASSERT(c == zdev->zdev_can_cnt); ASSERT(v == zdev->zdev_video_cnt); return zdev; } /* * create /dev/<devname> */ dev_t zynq_create_cdev(void *drvdata, struct cdev *cdev, struct file_operations *fops, char *devname) { int err; dev_t dev; struct device *devicep; dev = MKDEV(zynq_major, zynq_minor++); devicep = device_create(zynq_class, NULL, dev, drvdata, devname); if (devicep == NULL) { zynq_err("%s failed to create device /dev/%s\n", __FUNCTION__, devname); return 0; } cdev_init(cdev, fops); err = cdev_add(cdev, dev, 1); if (err) { zynq_err("%s failed to add cdev for /dev/%s\n", __FUNCTION__, devname); device_destroy(zynq_class, dev); return 0; } zynq_trace(ZYNQ_TRACE_PROBE, "%s created device /dev/%s\n", __FUNCTION__, devname); return dev; } void zynq_destroy_cdev(dev_t dev, struct cdev *cdev) { cdev_del(cdev); device_destroy(zynq_class, dev); } /* * Device probe and driver initialization */ static int zynq_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { zynq_dev_t *zdev; zynq_chan_t *zchan; u64 bar_start; u32 bar_len; int i, err; zdev = zdev_alloc(pdev->device); if (zdev == NULL) { zynq_err("%s failed to alloc zdev.\n", __FUNCTION__); return -ENOMEM; } spin_lock_init(&zdev->zdev_lock); spin_lock_init(&zdev->zdev_i2c_lock); spin_lock(&zynq_g_lock); zdev->zdev_inst = zynq_instance; zdev->zdev_can_num_start = zynq_can_count; zynq_can_count += zdev->zdev_can_cnt; zynq_instance++; spin_unlock(&zynq_g_lock); zdev->zdev_pdev = pdev; pci_read_config_word(pdev, PCI_VENDOR_ID, &zdev->zdev_vid); pci_read_config_word(pdev, PCI_DEVICE_ID, &zdev->zdev_did); /* enable I/O and MMIO access */ if ((err = pci_enable_device(pdev))) { zynq_err("%s failed to enable pci device %d\n", __FUNCTION__, err); goto err_enable_pci; } /* BAR0: Global and per channal configuration */ bar_start = pci_resource_start(pdev, 0); bar_len = pci_resource_len(pdev, 0); zdev->zdev_bar0 = ioremap(bar_start, bar_len); zdev->zdev_bar0_len = bar_len; if (!zdev->zdev_bar0) { zynq_err("%s ioremap failed for BAR0\n", __FUNCTION__); err = -EFAULT; goto err_ioremap_bar0; } zynq_trace(ZYNQ_TRACE_PROBE, "%s map bar0: bar_start=0x%llx, " "bar_len=%d, bar_va=0x%p\n", __FUNCTION__, bar_start, bar_len, zdev->zdev_bar0); zdev->zdev_version = zynq_g_reg_read(zdev, ZYNQ_G_VERSION); if (zdev->zdev_version == (unsigned int)-1) { zynq_err("%s Bar0 register access error, invalid version=-1, " "please try rebooting ...\n", __FUNCTION__); err = -EFAULT; goto err_ioremap_bar2; } /* BAR2: CAN IP registers */ bar_start = pci_resource_start(pdev, 2); bar_len = pci_resource_len(pdev, 2); zdev->zdev_bar2 = ioremap(bar_start, bar_len); if (!zdev->zdev_bar2) { zynq_err("%s ioremap failed for BAR2\n", __FUNCTION__); err = -EFAULT; goto err_ioremap_bar2; } zdev->zdev_bar2_len = bar_len; zynq_trace(ZYNQ_TRACE_PROBE, "%s map bar2: bar_start=0x%llx, " "bar_len=%d, bar_va=0x%p.\n", __FUNCTION__, bar_start, bar_len, zdev->zdev_bar2); zynq_check_hw_caps(zdev); /* the string lengh should be less than ZYNQ_DEV_NAME_LEN */ snprintf(zdev->zdev_name, sizeof(zdev->zdev_name), "%s%d-%s-%04x-%02x-%02x-%x", ZYNQ_DRV_NAME, zdev->zdev_inst, zdev->zdev_code_name, pci_domain_nr(pdev->bus), pdev->bus->number, pdev->devfn >> 3, pdev->devfn & 0x7); zynq_trace(ZYNQ_TRACE_PROBE, "FPGA device <%x,%x> %s\n", pdev->vendor, pdev->device, zdev->zdev_name); snprintf(zdev->prefix, ZYNQ_LOG_PREFIX_LEN, "%d", zdev->zdev_inst); zdev_stats_init(zdev); /* init each channel */ zchan = zdev->zdev_chans; for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { if (zchan_init(zchan)) { goto err_chan_init; } } zdev_clear_err_intr_all(zdev); zdev_clear_intr_all(zdev); zdev_disable_intr_all(zdev); /* alloc and register interrupt */ if (zynq_alloc_irq(zdev)) { goto err_chan_init; } /* sysfs support */ if (zynq_sysfs_init(zdev)) { goto err_sysfs_init; } /* create all the cdevs */ if (zynq_create_cdev_all(zdev) != 0) { goto err_create_cdev; } init_completion(&zdev->zdev_gpspps_event_comp); pci_set_master(pdev); #if LINUX_VERSION_CODE < KERNEL_VERSION(3,18,0) if (pci_set_dma_mask(pdev, DMA_64BIT_MASK)) { #else if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) { #endif zynq_err("%s failed to set DMA mask 64-bit\n", __FUNCTION__); #if LINUX_VERSION_CODE < KERNEL_VERSION(3,18,0) if (pci_set_dma_mask(pdev, DMA_32BIT_MASK)) { #else if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) { #endif zynq_err("%s failed to set DMA mask 32-bit\n", __FUNCTION__); err = -EPERM; goto err_dma_mask; } } #if LINUX_VERSION_CODE < KERNEL_VERSION(3,18,0) if (pci_set_consistent_dma_mask(pdev, DMA_64BIT_MASK)) { #else if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) { #endif zynq_err("%s failed to set DMA coherent mask 64-bit\n", __FUNCTION__); err = -EPERM; goto err_dma_mask; } pci_set_drvdata(pdev, zdev); zdev_enable_intr_all(zdev); spin_lock(&zynq_g_lock); zdev->zdev_next = zynq_dev_list; zynq_dev_list = zdev; spin_unlock(&zynq_g_lock); zynq_gps_init(zdev); zynq_log("%s found, device %s, firmware version=%08x.\n", zdev->zdev_code_name, zdev->zdev_name, zdev->zdev_version); return 0; err_dma_mask: pci_clear_master(pdev); zynq_destroy_cdev_all(zdev); err_create_cdev: zynq_sysfs_fini(zdev); err_sysfs_init: zynq_free_irq(zdev); err_chan_init: while (i--) { zchan--; zchan_fini(zchan); } iounmap(zdev->zdev_bar2); zdev->zdev_bar2 = NULL; err_ioremap_bar2: iounmap(zdev->zdev_bar0); zdev->zdev_bar0 = NULL; err_ioremap_bar0: pci_disable_device(pdev); err_enable_pci: kfree(zdev); return err; } static void zynq_remove(struct pci_dev *pdev) { zynq_dev_t *zdev; zynq_chan_t *zchan; int i; zdev = pci_get_drvdata(pdev); if (zdev == NULL) { return; } zynq_gps_fini(zdev); zdev_disable_intr_all(zdev); zynq_destroy_cdev_all(zdev); pci_clear_master(pdev); zynq_sysfs_fini(zdev); zynq_free_irq(zdev); zchan = zdev->zdev_chans; for (i = 0; i < zdev->zdev_chan_cnt; i++, zchan++) { zchan_fini(zchan); } iounmap(zdev->zdev_bar2); iounmap(zdev->zdev_bar0); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); kfree(zdev); zynq_trace(ZYNQ_TRACE_PROBE, "%s done.\n", __FUNCTION__); } static int zynq_suspend(struct pci_dev *pdev, pm_message_t state) { zynq_trace(ZYNQ_TRACE_PROBE, "%s done.\n", __FUNCTION__); return 0; } static int zynq_resume(struct pci_dev *pdev) { zynq_trace(ZYNQ_TRACE_PROBE, "%s done.\n", __FUNCTION__); return 0; } static void zynq_shutdown(struct pci_dev *pdev) { zynq_trace(ZYNQ_TRACE_PROBE, "%s done.\n", __FUNCTION__); } static struct pci_driver zynq_pci_driver = { .name = ZYNQ_DRV_NAME, .id_table = zynq_pci_dev_tbl, .probe = zynq_probe, .remove = zynq_remove, .suspend = zynq_suspend, .resume = zynq_resume, .shutdown = zynq_shutdown }; /* * sysfs support for zdev_all */ static ssize_t zynq_zdev_all_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { zynq_dev_t *zdev; int len = 0; spin_lock(&zynq_g_lock); zdev = zynq_dev_list; if (zdev == NULL) { spin_unlock(&zynq_g_lock); return sprintf(buf + len, "\nNo FPGA device is found!\n"); } while (zdev) { zdev->zdev_version = zynq_g_reg_read(zdev, ZYNQ_G_VERSION); len += sprintf(buf + len, "\n%s: %s card, F/W version=0x%08x, " "driver version=%s\n", zdev->zdev_name, zdev->zdev_code_name, (zdev->zdev_version & 0x7FFFFFFF), ZYNQ_MOD_VER); len += sprintf(buf + len, " vendorID=0x%x, deviceID=0x%x, " "instance=%d\n", zdev->zdev_vid, zdev->zdev_did, zdev->zdev_inst); len += sprintf(buf + len, " REG device: " ZYNQ_DEV_NAME_REG"%d\n", zdev->zdev_inst); if (zdev->zdev_hw_cap & ZYNQ_HW_CAP_I2C) { len += sprintf(buf + len, " I2C device: " ZYNQ_DEV_NAME_I2C"%d\n", zdev->zdev_inst); } if (zdev->zdev_hw_cap & ZYNQ_HW_CAP_CAN) { len += sprintf(buf + len, " CAN devices: " ZYNQ_DEV_NAME_CAN"[%u - %u]\n", zdev->zdev_can_num_start, zdev->zdev_can_num_start + zdev->zdev_can_cnt - 1); } if (zdev->zdev_hw_cap & ZYNQ_HW_CAP_GPS) { len += sprintf(buf + len, " GPS device: " ZYNQ_DEV_NAME_GPS"%d\n", zdev->zdev_inst); } if (zdev->zdev_hw_cap & ZYNQ_HW_CAP_FW) { len += sprintf(buf + len, " FW device: " ZYNQ_DEV_NAME_FW"%d\n", zdev->zdev_inst); } if (zdev->zdev_hw_cap & ZYNQ_HW_CAP_TRIGGER) { len += sprintf(buf + len, " Trigger device: " ZYNQ_DEV_NAME_TRIGGER"%d\n", zdev->zdev_inst); } if (zdev->zdev_hw_cap & ZYNQ_HW_CAP_VIDEO) { zynq_video_t *zvideo; int i; zvideo = zdev->zdev_videos; for (i = 0; i < zdev->zdev_video_cnt; i++, zvideo++) { if (!zvideo->caps.link_up) { continue; } len += sprintf(buf + len, " Video device: " "video%d (vid%d)", zvideo->vdev.num, i); if (zdev->zdev_video_port_map) { len += sprintf(buf + len, " (port%d)\n", zdev->zdev_video_port_map[i]); } else { len += sprintf(buf + len, "\n"); } } } zdev = zdev->zdev_next; } spin_unlock(&zynq_g_lock); return len; } static char *zynq_devnode(struct device *dev, umode_t *mode) { if (mode) { *mode = 0666; } return NULL; } static struct kobj_attribute zdev_all_attribute = __ATTR(zdev_all, 0440, zynq_zdev_all_show, NULL); /* driver module load entry point */ int zynq_module_init(void) { dev_t dev; struct module *zmod; int error; spin_lock_init(&zynq_g_lock); spin_lock_init(&zynq_gps_lock); /* allocate a major number */ if (zynq_major) { dev = MKDEV(zynq_major, zynq_minor); error = register_chrdev_region(dev, ZYNQ_MINOR_COUNT, ZYNQ_DRV_NAME); if (error) { zynq_err("%s: failed %d to get major=%d, count=%d\n", __FUNCTION__, error, zynq_major, ZYNQ_MINOR_COUNT); return error; } } else { error = alloc_chrdev_region(&dev, zynq_minor, ZYNQ_MINOR_COUNT, ZYNQ_DRV_NAME); if (error) { zynq_err("%s: failed %d to alloc major, count=%d\n", __FUNCTION__, error, ZYNQ_MINOR_COUNT); return error; } } zynq_major = MAJOR(dev); zynq_minor = MINOR(dev); zynq_g_dev = dev; zynq_class = class_create(THIS_MODULE, ZYNQ_DRV_NAME); if (zynq_class == NULL) { unregister_chrdev_region(dev, ZYNQ_MINOR_COUNT); zynq_err("%s: failed to create class\n", __FUNCTION__); return -1; } zynq_class->devnode = zynq_devnode; error = pci_register_driver(&zynq_pci_driver); if (error) { zynq_err("%s: pci_register_driver() failed, error=%d\n", __FUNCTION__, error); goto err_pci_reg; } /* kset_find_object is not exported, here we'll use &mod->mkobj.kobj */ zmod = zynq_pci_driver.driver.owner; if (!zmod) { zynq_err("%s: failed to find the driver module\n", __FUNCTION__); goto err; } /* create zdev_all */ zynq_kobject = &zmod->mkobj.kobj; error = sysfs_create_file(zynq_kobject, &zdev_all_attribute.attr); if (!error) { zynq_log("%s done, driver version %s\n", __FUNCTION__, ZYNQ_MOD_VER); return (0); } else { zynq_err("%s: sysfs_create_file() failed, error=%d\n", __FUNCTION__, error); goto err; } err: pci_unregister_driver(&zynq_pci_driver); err_pci_reg: unregister_chrdev_region(dev, ZYNQ_MINOR_COUNT); class_destroy(zynq_class); return error; } /* driver module remove entry point */ void zynq_module_exit(void) { sysfs_remove_file(zynq_kobject, &zdev_all_attribute.attr); pci_unregister_driver(&zynq_pci_driver); unregister_chrdev_region(zynq_g_dev, ZYNQ_MINOR_COUNT); class_destroy(zynq_class); zynq_trace(ZYNQ_TRACE_PROBE, "%s done.\n", __FUNCTION__); } /* module parameters */ module_param_named(trace, zynq_trace_param, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(trace, "Trace level bitmask"); module_param_named(bringup, zynq_bringup_param, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(bringup, "bringup mode"); module_param_named(fwupdate, zynq_fwupdate_param, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(fwupdate, "card firmware update enabling"); module_param_named(dbgregdump, zynq_dbg_reg_dump_param, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(dbgregdump, "enable debug register dump"); module_param_named(statslog, zynq_stats_log_interval, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(statslog, "statistics log interval");
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_can.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/module.h> #include <linux/delay.h> #include "basa.h" #define ZCAN_PIO_RX_POLLING_NS 1000000 /* 1ms in nanoseconds */ #define ZCAN_PIO_TX_RETRIES 500 #define ZCAN_PIO_RX_RETRIES 500 /* * minimum time for h/w to transmit a CAN msg: 50us (1btye data @1Mbps), * 130us (8btye data @1Mbps), 1040 us (8btye data @125Kbps). */ /* Min # of micro-seconds to sleep using usleep_range() */ #define ZCAN_PIO_WAIT_US_MIN 150 /* 500Kbps */ /* Max # of micro-seconds to sleep using usleep_range() */ #define ZCAN_PIO_WAIT_US_MAX 260 /* 500Kbps */ #define ZCAN_PIO_WAIT_DELAY 200 /* 200us */ #define ZCAN_PIO_STOP_DELAY 100 /* 100ms */ static void zcan_pio_rx_proc(zynq_can_t *zcan); /* CAN Rx buffer number */ static unsigned int zynq_can_rx_buf_num = ZCAN_IP_MSG_NUM; /* CAN bus sampling point */ static unsigned int zynq_can_ip_btr = ZCAN_IP_BTR_DEFAULT; /* disabling CAN Rx H/W timestamp */ static unsigned int zynq_disable_can_hw_ts = 0; /* enabling CAN Rx DMA mode */ unsigned int zynq_enable_can_rx_dma = 1; /* enabling CAN Tx DMA mode */ unsigned int zynq_enable_can_tx_dma = 0; /* keep the order in 'enum zynq_baudrate_val' */ static int brpr_reg_val[ZYNQ_BAUDRATE_NUM] = { ZCAN_IP_BRPR_1M, ZCAN_IP_BRPR_500K, ZCAN_IP_BRPR_250K, ZCAN_IP_BRPR_125K }; struct dbg_reg { int reg; char reg_desc[32]; }; #define CAN_IP_DBG_REG_NUM 12 static struct dbg_reg can_ip_dbg_reg[CAN_IP_DBG_REG_NUM] = { { ZCAN_IP_SRR, "s/w reset" }, { ZCAN_IP_MSR, "mode select" }, { ZCAN_IP_BRPR, "baud rate prescaler" }, { ZCAN_IP_BTR, "bit timing" }, { ZCAN_IP_ECR, "error counter" }, { ZCAN_IP_ESR, "error status" }, { ZCAN_IP_SR, "ip status" }, { ZCAN_IP_ISR, "interrupt status" }, { ZCAN_IP_IER, "interrupt enable" }, { ZCAN_IP_ICR, "interrupt clear" }, { ZCAN_IP_AFR, "acceptance filter" }, { ZCAN_IP_PIO_STATUS, "pio status" } }; #define CAN_IP_NEW_DBG_REG_NUM 3 static struct dbg_reg can_ip_new_dbg_reg[CAN_IP_NEW_DBG_REG_NUM] = { { ZCAN_IP_CFG0, "ip_cfg0" }, { ZCAN_IP_DBG_CNT0, "ip_dbg_cnt0" }, { ZCAN_IP_DBG_CNT1, "ip_dbg_cnt1" } }; #define CHAN_DBG_REG_NUM 1 static struct dbg_reg chan_dbg_reg[CHAN_DBG_REG_NUM] = { { ZYNQ_CH_ERR_STATUS, "chan error" } }; #define CHAN_NEW_DBG_REG_NUM 2 static struct dbg_reg chan_new_dbg_reg[CHAN_NEW_DBG_REG_NUM] = { { ZYNQ_CH_ERR_MASK_TX, "chan error mask0" }, { ZYNQ_CH_ERR_MASK_RX, "chan error mask1" } }; #define G_DBG_REG_NUM 5 static struct dbg_reg g_dbg_reg[G_DBG_REG_NUM] = { { ZYNQ_G_VERSION, "version" }, { ZYNQ_G_STATUS, "g_status" }, { ZYNQ_G_INTR_STATUS_TX, "g_intr_status_tx" }, { ZYNQ_G_INTR_STATUS_RX, "g_intr_status_rx" }, { ZYNQ_G_PS_INTR_STATUS, "g_ps_intr_status" } }; #define G_NEW_DBG_REG_NUM 12 static struct dbg_reg g_new_dbg_reg[G_NEW_DBG_REG_NUM] = { { ZYNQ_G_DEBUG_CFG0, "g_debug_cfg0" }, { ZYNQ_G_DEBUG_CFG1, "g_debug_cfg1" }, { ZYNQ_G_DEBUG_CFG2, "g_debug_cfg2" }, { ZYNQ_G_DEBUG_CFG3, "g_debug_cfg3" }, { ZYNQ_G_DEBUG_STA0, "g_debug_sta0" }, { ZYNQ_G_DEBUG_STA1, "g_debug_sta1" }, { ZYNQ_G_DEBUG_STA2, "g_debug_sta2" }, { ZYNQ_G_DEBUG_STA3, "g_debug_sta3" }, { ZYNQ_G_DEBUG_CNT_CFG, "g_debug_cnt_cfg" }, { ZYNQ_G_DEBUG_CNT0, "g_debug_cnt0" }, { ZYNQ_G_DEBUG_CNT1, "g_debug_cnt1" }, { ZYNQ_G_DEBUG_CNT2, "g_debug_cnt2" } }; static const char zcan_stats_label[CAN_STATS_NUM][ZYNQ_STATS_LABEL_LEN] = { "PIO Rx", "PIO Tx", "PIO Tx Hi", "User Rx wait", "User Rx wait intr", "User Rx timeout", "User Rx partial", "Bus off", "Status error", "Rx IP fifo overflow", "Rx user fifo overflow", "Tx timeout", "Tx LP fifo full", "Rx user fifo full", "Tx HP fifo full", "CRC error", "Frame error", "Stuff error", "Bit error", "Ack error" }; /* * Register dump functions for debugging purpose */ static void zcan_pio_dbg_reg_dump(zynq_can_t *zcan) { int i; zynq_err("%d CAN IP %d dbg register dump:\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num); for (i = 0; i < CAN_IP_DBG_REG_NUM; i++) { zynq_err(" 0x%x(%s) = 0x%x\n", can_ip_dbg_reg[i].reg, can_ip_dbg_reg[i].reg_desc, zcan_reg_read(zcan, can_ip_dbg_reg[i].reg)); } for (i = 0; i < CAN_IP_NEW_DBG_REG_NUM; i++) { zynq_err(" 0x%x(%s) = 0x%x\n", can_ip_new_dbg_reg[i].reg, can_ip_new_dbg_reg[i].reg_desc, zcan_reg_read(zcan, can_ip_new_dbg_reg[i].reg)); } } static void zchan_dbg_reg_dump(zynq_chan_t *zchan) { int i; zynq_err("%d chan %d dbg register dump:\n", ZYNQ_INST(zchan), zchan->zchan_num); for (i = 0; i < CHAN_DBG_REG_NUM; i++) { zynq_err(" 0x%x(%s) = 0x%x\n", chan_dbg_reg[i].reg, chan_dbg_reg[i].reg_desc, zchan_reg_read(zchan, chan_dbg_reg[i].reg)); } for (i = 0; i < CHAN_NEW_DBG_REG_NUM; i++) { zynq_err(" 0x%x(%s) = 0x%x\n", chan_new_dbg_reg[i].reg, chan_new_dbg_reg[i].reg_desc, zchan_reg_read(zchan, chan_new_dbg_reg[i].reg)); } } static void zynq_dbg_reg_dump(zynq_dev_t *zdev) { int i; zynq_err("%d global dbg register dump:\n", zdev->zdev_inst); for (i = 0; i < G_DBG_REG_NUM; i++) { zynq_err(" 0x%x(%s) = 0x%x\n", g_dbg_reg[i].reg, g_dbg_reg[i].reg_desc, zynq_g_reg_read(zdev, g_dbg_reg[i].reg)); } for (i = 0; i < G_NEW_DBG_REG_NUM; i++) { zynq_err(" 0x%x(%s) = 0x%x\n", g_new_dbg_reg[i].reg, g_new_dbg_reg[i].reg_desc, zynq_g_reg_read(zdev, g_new_dbg_reg[i].reg)); } } void zcan_pio_dbg_reg_dump_ch(zynq_can_t *zcan) { zynq_dbg_reg_dump(zcan->zdev); zchan_dbg_reg_dump(zcan->zchan); zcan_pio_dbg_reg_dump(zcan); } void zynq_dbg_reg_dump_all(zynq_dev_t *zdev) { zynq_can_t *zcan = zdev->zdev_cans; int i; zynq_dbg_reg_dump(zdev); for (i = 0; i < zdev->zdev_can_cnt; i++, zcan++) { zchan_dbg_reg_dump(zcan->zchan); zcan_pio_dbg_reg_dump(zcan); } } /* * Error interrupt handling in PIO mode */ void zcan_err_proc(zynq_can_t *zcan, int ch_err_status) { if ((zynq_trace_param & ZYNQ_TRACE_CAN) || zynq_dbg_reg_dump_param) { zcan_pio_dbg_reg_dump_ch(zcan); } /* error statistics */ if (ch_err_status & ZYNQ_CH_ERR_CAN_BUSOFF) { ZYNQ_STATS_LOG(zcan, CAN_STATS_BUS_OFF); } if (ch_err_status & ZYNQ_CH_ERR_CAN_STATERR) { ZYNQ_STATS_LOG(zcan, CAN_STATS_STATUS_ERR); } if (ch_err_status & ZYNQ_CH_ERR_CAN_RX_IPOVERFLOW) { ZYNQ_STATS_LOG(zcan, CAN_STATS_RX_IP_FIFO_OVF); } if (ch_err_status & ZYNQ_CH_ERR_CAN_RX_USROVERFLOW) { ZYNQ_STATS_LOG(zcan, CAN_STATS_RX_USR_FIFO_OVF); } if (ch_err_status & ZYNQ_CH_ERR_CAN_TX_TIMEOUT) { ZYNQ_STATS_LOG(zcan, CAN_STATS_TX_TIMEOUT); } if (ch_err_status & ZYNQ_CH_ERR_CAN_TX_LPFIFOFULL) { ZYNQ_STATS_LOG(zcan, CAN_STATS_TX_LP_FIFO_FULL); } if (ch_err_status & ZYNQ_CH_ERR_CAN_RX_FIFOFULL) { ZYNQ_STATS_LOG(zcan, CAN_STATS_RX_USR_FIFO_FULL); } if (ch_err_status & ZYNQ_CH_ERR_CAN_TX_HPFIFOFULL) { ZYNQ_STATS_LOG(zcan, CAN_STATS_TX_HP_FIFO_FULL); } if (ch_err_status & ZYNQ_CH_ERR_CAN_CRC_ERR) { ZYNQ_STATS_LOG(zcan, CAN_STATS_CRC_ERR); } if (ch_err_status & ZYNQ_CH_ERR_CAN_FRAME_ERR) { ZYNQ_STATS_LOG(zcan, CAN_STATS_FRAME_ERR); } if (ch_err_status & ZYNQ_CH_ERR_CAN_STUFF_ERR) { ZYNQ_STATS_LOG(zcan, CAN_STATS_STUFF_ERR); } if (ch_err_status & ZYNQ_CH_ERR_CAN_BIT_ERR) { ZYNQ_STATS_LOG(zcan, CAN_STATS_BIT_ERR); } if (ch_err_status & ZYNQ_CH_ERR_CAN_ACK_ERR) { ZYNQ_STATS_LOG(zcan, CAN_STATS_ACK_ERR); } } /* * Initialize the CAN IP: required for both DMA and PIO mode */ static void zcan_pio_chip_init(zynq_can_t *zcan, u32 ip_mode, int do_reset) { zynq_chan_t *zchan = zcan->zchan; if (do_reset) { /* reset the device */ zcan_reg_write(zcan, ZCAN_IP_SRR, 0); mdelay(10); zchan_reg_write(zchan, ZYNQ_CH_RESET, ZYNQ_CH_RESET_EN); zchan_reg_write(zchan, ZYNQ_CH_RESET, 0); mdelay(1); } else { zcan_reg_write(zcan, ZCAN_IP_SRR, 0); mdelay(10); } /* * Configure the CAN core */ /* 1. choose the operation mode: mode select regster */ zcan_reg_write(zcan, ZCAN_IP_MSR, ip_mode); /* 2. configure the transfer layer configuration registers */ zcan_reg_write(zcan, ZCAN_IP_BRPR, brpr_reg_val[zcan->zcan_pio_baudrate]); zcan_reg_write(zcan, ZCAN_IP_BTR, zynq_can_ip_btr); /* 3. configure the acceptance filter registers: accept ALL */ zcan_reg_write(zcan, ZCAN_IP_AFR, ZCAN_IP_AFR_NONE); /* 4. set the interrupt enable register */ zcan_reg_write(zcan, ZCAN_IP_IER, ZCAN_IP_INTR_ALL); zcan->zcan_pio_state = ZYNQ_STATE_INIT; /* make sure the previous pending interrupts are cleared */ zdev_clear_intr_ch(zcan->zdev, zchan->zchan_num); zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d ch%d %s msr=0x%x, brpr=0x%x, " "btr=0x%x, afr=0x%x, ier=0x%x, srr=0x%x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan_reg_read(zcan, ZCAN_IP_MSR), zcan_reg_read(zcan, ZCAN_IP_BRPR), zcan_reg_read(zcan, ZCAN_IP_BTR), zcan_reg_read(zcan, ZCAN_IP_AFR), zcan_reg_read(zcan, ZCAN_IP_IER), zcan_reg_read(zcan, ZCAN_IP_SRR)); } /* * Set CAN tx timeout value */ static void zcan_tx_timeout_set(zynq_can_t *zcan, unsigned long timeout) { spin_lock(&zcan->zcan_pio_lock); zcan->zcan_tx_timeout = timeout; zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done: tx_timeout=%ld\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, timeout); spin_unlock(&zcan->zcan_pio_lock); } /* * Set CAN rx timeout value */ static void zcan_rx_timeout_set(zynq_can_t *zcan, unsigned long timeout) { spin_lock(&zcan->zcan_pio_lock); zcan->zcan_rx_timeout = timeout; zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done: rx_timeout=%ld\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, timeout); spin_unlock(&zcan->zcan_pio_lock); } /* * start CAN IP */ static void zcan_pio_start(zynq_can_t *zcan) { spin_lock(&zcan->zcan_pio_lock); /* read out the firmware version again */ zcan->zdev->zdev_version = zynq_g_reg_read(zcan->zdev, ZYNQ_G_VERSION); /* enable CAN core by setting CEN bit */ zcan_reg_write(zcan, ZCAN_IP_SRR, ZCAN_IP_SRR_CEN); zcan->zcan_pio_state = ZYNQ_STATE_START; zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_lock); } /* * stop CAN IP */ static void zcan_pio_stop(zynq_can_t *zcan) { spin_lock(&zcan->zcan_pio_lock); spin_lock(&zcan->zcan_pio_tx_lock); mdelay(ZCAN_PIO_STOP_DELAY); zcan->zcan_pio_state = ZYNQ_STATE_STOP; /* disable CAN core by clearing CEN bit */ zcan_reg_write(zcan, ZCAN_IP_SRR, 0); zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_tx_lock); spin_unlock(&zcan->zcan_pio_lock); } /* * reset and re-initialize CAN IP */ static void zcan_pio_reset(zynq_can_t *zcan) { spin_lock(&zcan->zcan_pio_lock); spin_lock(&zcan->zcan_pio_tx_lock); spin_lock_bh(&zcan->zcan_pio_rx_lock); zcan->zcan_pio_state = ZYNQ_STATE_RESET; zcan_pio_chip_init(zcan, ZCAN_IP_MSR_NORMAL, 1); zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); spin_unlock_bh(&zcan->zcan_pio_rx_lock); spin_unlock(&zcan->zcan_pio_tx_lock); spin_unlock(&zcan->zcan_pio_lock); } /* * reset CAN IP */ static void zcan_pio_reset_noinit(zynq_can_t *zcan) { zynq_chan_t *zchan = zcan->zchan; spin_lock(&zcan->zcan_pio_lock); spin_lock(&zcan->zcan_pio_tx_lock); spin_lock_bh(&zcan->zcan_pio_rx_lock); zcan->zcan_pio_state = ZYNQ_STATE_RESET; /* reset device */ zcan_reg_write(zcan, ZCAN_IP_SRR, 0); mdelay(10); zchan_reg_write(zchan, ZYNQ_CH_RESET, ZYNQ_CH_RESET_EN); zchan_reg_write(zchan, ZYNQ_CH_RESET, 0); zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, __FUNCTION__); spin_unlock_bh(&zcan->zcan_pio_rx_lock); spin_unlock(&zcan->zcan_pio_tx_lock); spin_unlock(&zcan->zcan_pio_lock); } /* * Set CAN IP to loopback mode */ static void zcan_pio_loopback_set(zynq_can_t *zcan) { int pio_state; spin_lock(&zcan->zcan_pio_lock); pio_state = zcan->zcan_pio_state; zcan_pio_chip_init(zcan, ZCAN_IP_MSR_LOOPBACK, 1); zcan->zcan_pio_loopback = 1; if (pio_state == ZYNQ_STATE_START) { /* enable chip */ zcan_reg_write(zcan, ZCAN_IP_SRR, ZCAN_IP_SRR_CEN); zcan->zcan_pio_state = ZYNQ_STATE_START; } zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_lock); } /* * Unset CAN IP loopback mode */ static void zcan_pio_loopback_unset(zynq_can_t *zcan) { int pio_state; spin_lock(&zcan->zcan_pio_lock); pio_state = zcan->zcan_pio_state; zcan_pio_chip_init(zcan, ZCAN_IP_MSR_NORMAL, 1); zcan->zcan_pio_loopback = 0; if (pio_state == ZYNQ_STATE_START) { /* enable chip */ zcan_reg_write(zcan, ZCAN_IP_SRR, ZCAN_IP_SRR_CEN); zcan->zcan_pio_state = ZYNQ_STATE_START; } zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_lock); } /* * Set CAN IP working baudrate */ static int zcan_pio_set_baudrate(zynq_can_t *zcan, int baudrate) { u32 orig_val; if (baudrate >= ZYNQ_BAUDRATE_NUM) { zynq_err("%d can%d %s failed: bad baudrate %d\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, baudrate); return -EINVAL; } spin_lock(&zcan->zcan_pio_lock); /* save the orignal register value */ orig_val = zcan_reg_read(zcan, ZCAN_IP_SRR); /* clear CEN bit first */ zcan_reg_write(zcan, ZCAN_IP_SRR, 0); mdelay(10); /* set the baudrate */ zcan_reg_write(zcan, ZCAN_IP_BRPR, brpr_reg_val[baudrate]); /* restore the orignal register value */ zcan_reg_write(zcan, ZCAN_IP_SRR, orig_val); zcan->zcan_pio_baudrate = baudrate; zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_lock); return 0; } static void bcan_to_zcan(bcan_msg_t *bmsg) { zcan_msg_t *cmsg; u32 msg_id; /* * convert CAN message format of bcan_msg_t used by application * to zcan_msg_t used by H/W */ msg_id = bmsg->bcan_msg_id; cmsg = (zcan_msg_t *)bmsg; if (msg_id & BCAN_EXTENDED_FRAME) { cmsg->cmsg_id_ertr = 0; cmsg->cmsg_id_eid = msg_id & CMSG_ID_EID_MASK; cmsg->cmsg_id_ide = 1; cmsg->cmsg_id_srtr = 1; cmsg->cmsg_id_sid = (msg_id >> fls(CMSG_ID_EID_MASK)) & CMSG_ID_SID_MASK; } else { cmsg->cmsg_id = (msg_id & CMSG_ID_SID_MASK) << CMSG_ID_SID_SHIFT; } cmsg->cmsg_len = (bmsg->bcan_msg_datalen & CMSG_LEN_MASK) << CMSG_LEN_SHIFT; cmsg->cmsg_data1 = htonl(*(u32 *)&bmsg->bcan_msg_data[0]); cmsg->cmsg_data2 = htonl(*(u32 *)&bmsg->bcan_msg_data[4]); } static void zcan_to_bcan(zcan_msg_t *cmsg) { bcan_msg_t *bmsg; u32 msg_id; /* * convert CAN message format of zcan_msg_t used by H/W to * bcan_msg_t used by application */ bmsg = (bcan_msg_t *)cmsg; if (cmsg->cmsg_id_ide) { msg_id = (cmsg->cmsg_id_sid << fls(CMSG_ID_EID_MASK)) | cmsg->cmsg_id_eid; msg_id |= BCAN_EXTENDED_FRAME; } else { msg_id = cmsg->cmsg_id >> CMSG_ID_SID_SHIFT; } bmsg->bcan_msg_id = msg_id; bmsg->bcan_msg_datalen = cmsg->cmsg_len >> CMSG_LEN_SHIFT; *(u32 *)&bmsg->bcan_msg_data[0] = ntohl(cmsg->cmsg_data1); *(u32 *)&bmsg->bcan_msg_data[4] = ntohl(cmsg->cmsg_data2); } /* * High priority Tx: 1 message high priority Tx buffer */ static int zcan_pio_tx_hi_one(zynq_can_t *zcan, zcan_msg_t *cmsg, int wait, int poll) { zynq_chan_t *zchan = zcan->zchan; u32 val32; int j = 0; spin_lock(&zcan->zcan_pio_tx_hi_lock); /* check chip state */ if (zcan->zcan_pio_state != ZYNQ_STATE_START) { zynq_err("%d can%d ch%d %s failed: " "not in ZYNQ_STATE_START state\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_tx_hi_lock); return BCAN_FAIL; } if (poll) { /* clear the Tx interrupt bits first */ zcan_reg_write(zcan, ZCAN_IP_ICR, ZCAN_IP_INTR_TXOK | ZCAN_IP_INTR_ERROR); } if (wait) { /* poll status regsiter to see if the HPB is FULL */ while (zcan_reg_read(zcan, ZCAN_IP_PIO_STATUS) & ZCAN_IP_PIO_TX_HI_FULL) { if (j++ > ZCAN_PIO_TX_RETRIES) { zynq_err("%d can%d ch%d %s failed: " "Tx HI FIFO is FULL\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_tx_hi_lock); return BCAN_FAIL; } usleep_range(ZCAN_PIO_WAIT_US_MIN, ZCAN_PIO_WAIT_US_MAX); } zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s: wait_time = %dus\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, j * 200); } else { if (zcan_reg_read(zcan, ZCAN_IP_PIO_STATUS) & ZCAN_IP_PIO_TX_HI_FULL) { spin_unlock(&zcan->zcan_pio_tx_hi_lock); return BCAN_DEV_BUSY; } } /* read out CAN message from registers */ zcan_reg_write(zcan, ZCAN_IP_TXHPB_ID, cmsg->cmsg_id); zcan_reg_write(zcan, ZCAN_IP_TXHPB_DLC, cmsg->cmsg_len); zcan_reg_write(zcan, ZCAN_IP_TXHPB_DW1, cmsg->cmsg_data1); zcan_reg_write(zcan, ZCAN_IP_TXHPB_DW2, cmsg->cmsg_data2); zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s: Tx_high priority msg %lu: " "sid=0x%x, srtr=%d, eid=0x%x, ertr=%d; data_len=%d(0x%x); " "data1=0x%08x; data2=0x%08x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->stats[CAN_STATS_PIO_TX_HI].cnt, cmsg->cmsg_id_sid, cmsg->cmsg_id_srtr, cmsg->cmsg_id_eid, cmsg->cmsg_id_ertr, cmsg->cmsg_len_len, cmsg->cmsg_len, cmsg->cmsg_data1, cmsg->cmsg_data2); if (poll) { /* poll ISR regsiter to see if the Tx is finished or not */ j = 0; while (1) { val32 = zcan_reg_read(zcan, ZCAN_IP_ISR); if (val32 & (ZCAN_IP_INTR_TXOK | ZCAN_IP_INTR_ERROR)) { break; } if (j++ > ZCAN_PIO_TX_RETRIES) { zynq_err("%d can%d ch%d %s failed: " "Tx status is not updated\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_tx_hi_lock); return BCAN_FAIL; } usleep_range(ZCAN_PIO_WAIT_US_MIN, ZCAN_PIO_WAIT_US_MAX); } if (val32 & ZCAN_IP_INTR_ERROR) { zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d ch%d %s: Tx high %lu intr=0x%x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->stats[CAN_STATS_PIO_TX_HI].cnt, zcan_reg_read(zcan, ZCAN_IP_ISR)); } /* clear the Tx interrupt bits */ zcan_reg_write(zcan, ZCAN_IP_ICR, ZCAN_IP_INTR_TXOK | ZCAN_IP_INTR_ERROR); } ZYNQ_STATS(zcan, CAN_STATS_PIO_TX_HI); spin_unlock(&zcan->zcan_pio_tx_hi_lock); return (BCAN_OK); } /* * normal Tx: 64 messages Tx FIFO */ static int zcan_pio_tx_one(zynq_can_t *zcan, zcan_msg_t *cmsg, int wait, int poll) { zynq_chan_t *zchan = zcan->zchan; u32 val32; int j = 0; spin_lock(&zcan->zcan_pio_tx_lock); if (zcan->zcan_pio_state != ZYNQ_STATE_START) { zynq_err("%d can%d ch%d %s failed: " "not in ZYNQ_STATE_START state\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_tx_lock); return BCAN_FAIL; } if (poll) { /* clear the Tx interrupt bits first */ zcan_reg_write(zcan, ZCAN_IP_ICR, ZCAN_IP_INTR_TXOK | ZCAN_IP_INTR_ERROR); } /* poll status regsiter to see if the Tx FIFO is FULL */ if (wait) { while (zcan_reg_read(zcan, ZCAN_IP_PIO_STATUS) & ZCAN_IP_PIO_TX_FULL) { if (j++ > ZCAN_PIO_TX_RETRIES) { zynq_err("%d can%d ch%d %s failed: " "Tx FIFO is FULL\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_tx_lock); return BCAN_FAIL; } usleep_range(ZCAN_PIO_WAIT_US_MIN, ZCAN_PIO_WAIT_US_MAX); } zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s: wait_time = %dus\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, j * 200); } else { if (zcan_reg_read(zcan, ZCAN_IP_PIO_STATUS) & ZCAN_IP_PIO_TX_FULL) { spin_unlock(&zcan->zcan_pio_tx_lock); return BCAN_DEV_BUSY; } } /* read out CAN message from registers */ zcan_reg_write(zcan, ZCAN_IP_TXFIFO_ID, cmsg->cmsg_id); zcan_reg_write(zcan, ZCAN_IP_TXFIFO_DLC, cmsg->cmsg_len); zcan_reg_write(zcan, ZCAN_IP_TXFIFO_DW1, cmsg->cmsg_data1); zcan_reg_write(zcan, ZCAN_IP_TXFIFO_DW2, cmsg->cmsg_data2); zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s: Tx_normal priority msg %lu: " "sid=0x%x, srtr=%d, eid=0x%x, ertr=%d; data_len=%d(0x%x); " "data1=0x%08x; data2=0x%08x(%d)\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->stats[CAN_STATS_PIO_TX].cnt, cmsg->cmsg_id_sid, cmsg->cmsg_id_srtr, cmsg->cmsg_id_eid, cmsg->cmsg_id_ertr, cmsg->cmsg_len_len, cmsg->cmsg_len, cmsg->cmsg_data1, cmsg->cmsg_data2, cmsg->cmsg_data2); if (poll) { /* poll ISR regsiter to see if the Tx is finished or not */ j = 0; while (1) { val32 = zcan_reg_read(zcan, ZCAN_IP_ISR); if (val32 & (ZCAN_IP_INTR_TXOK | ZCAN_IP_INTR_ERROR)) { break; } if (j++ > ZCAN_PIO_TX_RETRIES) { zynq_err("%d can%d ch%d %s failed: " "Tx status is not updated\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_tx_lock); return BCAN_FAIL; } usleep_range(ZCAN_PIO_WAIT_US_MIN, ZCAN_PIO_WAIT_US_MAX); } if (val32 & ZCAN_IP_INTR_ERROR) { zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d ch%d %s: Tx normal %lu intr=0x%x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->stats[CAN_STATS_PIO_TX].cnt, zcan_reg_read(zcan, ZCAN_IP_ISR)); } /* clear the Tx interrupt bits */ zcan_reg_write(zcan, ZCAN_IP_ICR, ZCAN_IP_INTR_TXOK | ZCAN_IP_INTR_ERROR); } ZYNQ_STATS(zcan, CAN_STATS_PIO_TX); spin_unlock(&zcan->zcan_pio_tx_lock); return BCAN_OK; } /* * normal DMA mode Tx */ static int zcan_dma_tx_one(zynq_can_t *zcan, zcan_msg_t *cmsg, int wait, int poll) { return zchan_tx_one_msg(zcan->zchan, cmsg, sizeof(zcan_msg_t)); } /* * Tx userland CAN message(s) */ static int zcan_tx_user(zynq_can_t *zcan, ioc_bcan_msg_t *ioc_arg, int tx_hipri, int *tx_done) { zynq_chan_t *zchan = zcan->zchan; int (*tx_func)(zynq_can_t *, zcan_msg_t *, int, int); int tx_num = ioc_arg->ioc_msg_num; int tx_num_done = 0; bcan_msg_t bmsg_one; bcan_msg_t *bmsg, *bmsg_alloc = NULL; zcan_msg_t *cmsg; ktime_t ktime_end, ktime_now; int ret = BCAN_OK; zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s enter: tx_timeout=%ld, tx_num=%d\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->zcan_tx_timeout, tx_num); if (tx_num == 1) { bmsg = &bmsg_one; } else { /* alloc memory and copy-in all the sending msgs */ bmsg_alloc = kmalloc(sizeof(bcan_msg_t) * tx_num, GFP_KERNEL); if (bmsg_alloc == NULL) { ret = BCAN_FAIL; zynq_err("%d can%d ch%d %s kmalloc failed.\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); goto tx_done; } bmsg = bmsg_alloc; } if (copy_from_user(bmsg, (void __user *)ioc_arg->ioc_msgs, sizeof(bcan_msg_t) * tx_num)) { zynq_err("%d can%d ch%d %s " "copy_from_usr failed: usr_addr=0x%p.\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, ioc_arg->ioc_msgs); ret = BCAN_FAIL; goto tx_done; } /* if timeout is not set, set to MAX */ if (zcan->zcan_tx_timeout == 0) { zcan->zcan_tx_timeout = ZCAN_TIMEOUT_MAX; } if (tx_hipri) { tx_func = zcan_pio_tx_hi_one; } else if (!zcan->zdev->zcan_tx_dma) { tx_func = zcan_pio_tx_one; } else { tx_func = zcan_dma_tx_one; } ktime_end = ktime_add_ns(ktime_get(), 1000000 * zcan->zcan_tx_timeout); /* send the msg one by one till finished or timeout */ while (tx_num) { zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s bcan_msg %d: " "id=0x%08x; data_len=%d; data1=0x%08x; data2=0x%08x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, tx_num_done, bmsg->bcan_msg_id, bmsg->bcan_msg_datalen, *(u32 *)(&bmsg->bcan_msg_data[0]), *(u32 *)(&bmsg->bcan_msg_data[4])); bcan_to_zcan(bmsg); cmsg = (zcan_msg_t *)bmsg; zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s zcan_msg %d: " "sid=0x%x, srtr=%d, ide=%d, eid=0x%x, ertr=%d(0x%08x); " "data_len=%d(0x%08x); data1=0x%08x; data2=0x%08x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, tx_num_done, cmsg->cmsg_id_sid, cmsg->cmsg_id_srtr, cmsg->cmsg_id_ide, cmsg->cmsg_id_eid, cmsg->cmsg_id_ertr, cmsg->cmsg_id, cmsg->cmsg_len_len, cmsg->cmsg_len, cmsg->cmsg_data1, cmsg->cmsg_data2); retry: /* call low-level tx function to transmit the msg */ ret = tx_func(zcan, cmsg, 0, 0); if (ret == BCAN_OK) { /* wait for h/w to really transmit the MSG on-wire */ usleep_range(ZCAN_PIO_WAIT_US_MIN, ZCAN_PIO_WAIT_US_MAX); } else { /* checking timeout */ if (ret == BCAN_DEV_BUSY) { ktime_now = ktime_get(); #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 10, 0) if (ktime_now.tv64 < ktime_end.tv64) { /* } */ #else if (ktime_now < ktime_end) { #endif usleep_range(ZCAN_PIO_WAIT_US_MIN, ZCAN_PIO_WAIT_US_MAX); goto retry; } else { ret = BCAN_TIMEOUT; if ((zynq_trace_param & ZYNQ_TRACE_CAN) || zynq_dbg_reg_dump_param) { zcan_pio_dbg_reg_dump_ch(zcan); } } } break; } tx_num_done++; bmsg++; tx_num--; } tx_done: *tx_done = tx_num_done; if (bmsg_alloc) { kfree(bmsg_alloc); } zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s done: ret=%d, tx_num=%d, tx_num_done=%d\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, ret, ioc_arg->ioc_msg_num, tx_num_done); return ret; } #if !defined(PIO_RX_THREAD) && !defined(PIO_RX_INTR) /* * Rx: get the messages from Rx FIFO and put them into the * given buffer. Return the length of actual copied data size. */ static int zcan_pio_rx(zynq_can_t *zcan, char *buf, int buf_sz, int wait) { zynq_chan_t *zchan = zcan->zchan; u32 *rx_buf = (u32 *)buf; zcan_msg_t *cmsg = (zcan_msg_t *)buf; int rx_len = 0; int j = 0; if (wait) { while (!(zcan_reg_read(zcan, ZCAN_IP_PIO_STATUS) & ZCAN_IP_PIO_RX_READY)) { if (j++ > ZCAN_PIO_RX_RETRIES) { zynq_err("%d can%d ch%d %s failed: " "no Rx data\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); return (0); } udelay(ZCAN_PIO_WAIT_DELAY); } } /* check if there is data in Rx FIFO */ while (zcan_reg_read(zcan, ZCAN_IP_PIO_STATUS) & ZCAN_IP_PIO_RX_READY) { if (rx_len > buf_sz) { break; } /* read out one message */ *rx_buf++ = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_ID); *rx_buf++ = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_DLC); *rx_buf++ = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_DW1); *rx_buf++ = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_DW2); rx_len += sizeof(zcan_msg_t); buf_sz -= sizeof(zcan_msg_t); /* clear the Rx interrupt bits */ zcan_reg_write(zcan, ZCAN_IP_PIO_STATUS, ZCAN_IP_PIO_RX_READY); zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s: Rx msg %lu: " "sid=0x%x, srtr=%d, eid=0x%x, ertr=%d; " "data_len=%d(0x%x); data1=0x%x; data2=0x%x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->stats[CAN_STATS_PIO_RX].cnt, cmsg->cmsg_id_sid, cmsg->cmsg_id_srtr, cmsg->cmsg_id_eid, cmsg->cmsg_id_ertr, cmsg->cmsg_len_len, cmsg->cmsg_len, cmsg->cmsg_data1, cmsg->cmsg_data2); ZYNQ_STATS(zcan, CAN_STATS_PIO_RX); cmsg++; } zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s done: rx_len = %d.\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, rx_len); return rx_len; } #endif /* check if we have received enough data as requested */ static inline void zcan_usr_rx_complete(zynq_can_t *zcan) { u32 req_num, rx_num; spin_lock(&zcan->zcan_pio_rx_lock); if (zcan->zcan_usr_buf == NULL) { spin_unlock(&zcan->zcan_pio_rx_lock); return; } /* requested Rx number */ req_num = zcan->zcan_usr_buf_num - zcan->zcan_usr_rx_num; /* already received number */ if (zcan->zcan_buf_rx_tail >= zcan->zcan_buf_rx_head) { rx_num = zcan->zcan_buf_rx_tail - zcan->zcan_buf_rx_head; } else { rx_num = zcan->zcan_buf_rx_num + zcan->zcan_buf_rx_tail - zcan->zcan_buf_rx_head; } zcan->zcan_pio_rx_last_chk_head = zcan->zcan_buf_rx_head; zcan->zcan_pio_rx_last_chk_tail = zcan->zcan_buf_rx_tail; zcan->zcan_pio_rx_last_chk_cnt = rx_num; zcan->zcan_pio_rx_last_chk_seq = zcan->zcan_usr_rx_seq; /* received enough */ if ((rx_num > 0) && (rx_num >= req_num)) { complete(&zcan->zcan_usr_rx_comp); } spin_unlock(&zcan->zcan_pio_rx_lock); } /* copy the received CAN message(s) to usrland buffer */ static int zcan_copy_to_user(zynq_can_t *zcan) { zynq_chan_t *zchan = zcan->zchan; bcan_msg_t *buf; bcan_msg_t *bmsg; zcan_msg_t *cmsg; int head; zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s enter: buf_num=%d\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->zcan_usr_buf_num); WARN_ON(!spin_is_locked(&zcan->zcan_pio_rx_lock)); if (zcan->zcan_usr_rx_num == zcan->zcan_usr_buf_num) { goto done; } /* no pending Rx data */ if (zcan->zcan_buf_rx_head == zcan->zcan_buf_rx_tail) { goto done; } /* get buffered CAN messages to user */ for (head = zcan->zcan_buf_rx_head; head != zcan->zcan_buf_rx_tail; head++, head %= zcan->zcan_buf_rx_num) { if (zcan->zcan_usr_rx_num == zcan->zcan_usr_buf_num) { break; } bmsg = zcan->zcan_buf_rx_msg + head; cmsg = (zcan_msg_t *)bmsg; buf = (bcan_msg_t *)zcan->zcan_usr_buf + zcan->zcan_usr_rx_num; zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s zcan_msg %d: " "sid=0x%x, srtr=%d, ide=%d, eid=0x%x, ertr=%d(0x%08x); " "data_len=%d(0x%08x); data1=0x%08x; data2=0x%08x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->zcan_usr_rx_num, cmsg->cmsg_id_sid, cmsg->cmsg_id_srtr, cmsg->cmsg_id_ide, cmsg->cmsg_id_eid, cmsg->cmsg_id_ertr, cmsg->cmsg_id, cmsg->cmsg_len_len, cmsg->cmsg_len, cmsg->cmsg_data1, cmsg->cmsg_data2); zcan_to_bcan(cmsg); zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s bcan_msg %d: " "id=0x%08x, data_len=%d, data1=0x%08x, data2=0x%08x, " "timestamp=%lu.%06lu, head=%d, usr_buf=0x%p\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->zcan_usr_rx_num, bmsg->bcan_msg_id, bmsg->bcan_msg_datalen, *(u32 *)bmsg->bcan_msg_data, *(u32 *)(&bmsg->bcan_msg_data[4]), bmsg->bcan_msg_timestamp.tv_sec, bmsg->bcan_msg_timestamp.tv_usec, head, buf); if (copy_to_user((void __user *)buf, bmsg, sizeof(bcan_msg_t))) { zcan->zcan_buf_rx_head = head; zynq_err("%d can%d ch%d %s: copy_to_user() failed, " "head=%d, tail=%d, usr_buf=0x%p\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num,__FUNCTION__, zcan->zcan_buf_rx_head, zcan->zcan_buf_rx_tail, buf); return BCAN_FAIL; } zcan->zcan_usr_rx_num++; } zcan->zcan_buf_rx_head = head; done: if (zcan->zcan_usr_rx_num < zcan->zcan_usr_buf_num) { zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s: not enough, " "rx_num=%d, buf_num=%d, head=%d, tail=%d, " "check:[head=%d,tail=%d,cnt=%d,seq=%d], " "last-seq=%d, intr-total=%lu, intr-rx=%lu\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->zcan_usr_rx_num, zcan->zcan_usr_buf_num, zcan->zcan_buf_rx_head, zcan->zcan_buf_rx_tail, zcan->zcan_pio_rx_last_chk_head, zcan->zcan_pio_rx_last_chk_tail, zcan->zcan_pio_rx_last_chk_cnt, zcan->zcan_pio_rx_last_chk_seq, zcan->zcan_usr_rx_seq, zchan->zdev->stats[DEV_STATS_INTR].cnt, zchan->stats[CHAN_STATS_RX_INTR].cnt); return BCAN_PARTIAL_OK; } zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s done: head=%d, tail=%d, " "buf_num=%d, rx_num=%d\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->zcan_buf_rx_head, zcan->zcan_buf_rx_tail, zcan->zcan_usr_buf_num, zcan->zcan_usr_rx_num); return BCAN_OK; } /* * Rx CAN messages to user */ static int zcan_rx_user(zynq_can_t *zcan, ioc_bcan_msg_t *ioc_arg, int *rx_done) { zynq_chan_t *zchan = zcan->zchan; int ret; long timeout; zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s enter: timeout=%ld, buf_num=%d\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->zcan_rx_timeout, ioc_arg->ioc_msg_num); *rx_done = 0; spin_lock_bh(&zcan->zcan_pio_rx_lock); zcan->zcan_usr_rx_seq++; if (zcan->zcan_rx_timeout == 0) { zcan->zcan_rx_timeout = ZCAN_TIMEOUT_MAX; } if (zcan->zcan_usr_buf != NULL) { zynq_err("%d can%d ch%d %s: BUSY!\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); ret = BCAN_DEV_BUSY; goto out; } zcan->zcan_usr_buf = ioc_arg->ioc_msgs; zcan->zcan_usr_buf_num = ioc_arg->ioc_msg_num; /* copy existing data to usrland first */ ret = zcan_copy_to_user(zcan); if (ret == BCAN_OK) { goto done; /* received enough */ } reinit_completion(&zcan->zcan_usr_rx_comp); spin_unlock_bh(&zcan->zcan_pio_rx_lock); /* wait for more data */ ZYNQ_STATS(zcan, CAN_STATS_USR_RX_WAIT); timeout = wait_for_completion_interruptible_timeout( &zcan->zcan_usr_rx_comp, msecs_to_jiffies(zcan->zcan_rx_timeout)); if (timeout < 0) { /* interrupted */ ZYNQ_STATS(zcan, CAN_STATS_USR_RX_WAIT_INT); ret = BCAN_ERR; /* Lock RX and clean-up. */ spin_lock_bh(&zcan->zcan_pio_rx_lock); goto done; } if (timeout == 0) { ZYNQ_STATS(zcan, CAN_STATS_USR_RX_TIMEOUT); } spin_lock_bh(&zcan->zcan_pio_rx_lock); /* copy newly received data */ ret = zcan_copy_to_user(zcan); if (ret == BCAN_PARTIAL_OK) { ZYNQ_STATS(zcan, CAN_STATS_USR_RX_PARTIAL); if (timeout > 0) { /* This should never happen when timeout != 0. */ ret = BCAN_ERR; /* internal or unknown error. */ zynq_err("%s: %d can%d ch%d: " "internal error, #m=%d:%d, timeout=%ld\n", __FUNCTION__, ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, zcan->zcan_usr_rx_num, zcan->zcan_usr_buf_num, timeout); } else { ret = BCAN_TIMEOUT; } } done: *rx_done = zcan->zcan_usr_rx_num; zcan->zcan_usr_rx_num = 0; zcan->zcan_usr_buf_num = 0; zcan->zcan_usr_buf = NULL; out: spin_unlock_bh(&zcan->zcan_pio_rx_lock); zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s done: rx_done=%d\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, *rx_done); return ret; } /* clear all the buffered messaged */ static inline void zcan_clear_buf_rx(zynq_can_t *zcan) { zynq_chan_t *zchan = zcan->zchan; spin_lock_bh(&zcan->zcan_pio_rx_lock); zcan->zcan_buf_rx_head = zcan->zcan_buf_rx_tail; zynq_trace(ZYNQ_TRACE_CAN, "%d can%d ch%d %s: clear the buffered rx messages, head=tail=%d\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->zcan_buf_rx_tail); spin_unlock_bh(&zcan->zcan_pio_rx_lock); } static inline void zcan_buf_inc_rx_head(zynq_can_t *zcan, int inc) { zynq_chan_t *zchan = zcan->zchan; int head; spin_lock(&zcan->zcan_pio_rx_lock); head = (zcan->zcan_buf_rx_head + inc) % zcan->zcan_buf_rx_num; zynq_trace(ZYNQ_TRACE_CAN, "%d can%d ch%d %s: head=%d, inc=%d, new_head=%d, tail=%d\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, zcan->zcan_buf_rx_head, inc, head, zcan->zcan_buf_rx_tail); zcan->zcan_buf_rx_head = head; spin_unlock(&zcan->zcan_pio_rx_lock); ZYNQ_STATS_LOGX(zchan, CHAN_STATS_RX_DROP, inc, 0); } static inline int zcan_buf_rx_full(zynq_can_t *zcan) { int rx_tail_next; rx_tail_next = (zcan->zcan_buf_rx_tail + 1) % zcan->zcan_buf_rx_num; return rx_tail_next == zcan->zcan_buf_rx_head; } #ifdef PIO_RX_THREAD static int zcan_pio_rx_poll(void *arg) { zynq_can_t *zcan = arg; zynq_chan_t *zchan = zcan->zchan; bcan_msg_t *bmsg; zcan_msg_t *cmsg; int rx_tail; int status; rx_tail = zcan->zcan_buf_rx_tail; while (!kthread_should_stop()) { /* wait for data to be available */ while (1) { /* Rx data pending */ status = zcan_reg_read(zcan, ZCAN_IP_PIO_STATUS); if (status != -1 && status & ZCAN_IP_PIO_RX_READY) { break; } /* sleep and will poll status again */ usleep_range(1000, 1200); if (kthread_should_stop()) { goto done; } } /* check if there is data in Rx FIFO */ while (zcan_reg_read(zcan, ZCAN_IP_PIO_STATUS) & ZCAN_IP_PIO_RX_READY) { /* if full, free some buffer by increasing the rx_head */ if (zcan_buf_rx_full(zcan)) { zcan_buf_inc_rx_head(zcan, ZCAN_IP_RXFIFO_MAX); } /* read out one message */ bmsg = zcan->zcan_buf_rx_msg + rx_tail; /* record the timestamp for the msg */ ktime_get_real_ts((struct timespec *) (&bmsg->bcan_msg_timestamp)); bmsg->bcan_msg_timestamp.tv_usec /= NSEC_PER_USEC; /* CAN msg info */ cmsg = (zcan_msg_t *)bmsg; cmsg->cmsg_id = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_ID); cmsg->cmsg_len = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_DLC); cmsg->cmsg_data1 = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_DW1); cmsg->cmsg_data2 = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_DW2); /* clear the Rx interrupt bits */ zcan_reg_write(zcan, ZCAN_IP_PIO_STATUS, ZCAN_IP_PIO_RX_READY); zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s: Rx %d msg %lu: " "sid=0x%x, srtr=%d, eid=0x%x, ertr=%d; " "data_len=%d(0x%x); data1=0x%x; data2=0x%x(%d)\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, rx_tail, zcan->stats[CAN_STATS_PIO_RX].cnt, cmsg->cmsg_id_sid, cmsg->cmsg_id_srtr, cmsg->cmsg_id_eid, cmsg->cmsg_id_ertr, cmsg->cmsg_len_len, cmsg->cmsg_len, cmsg->cmsg_data1, cmsg->cmsg_data2, cmsg->cmsg_data2); /* NEXT tail */ rx_tail++; rx_tail %= zcan->zcan_buf_rx_num; zcan->zcan_buf_rx_tail = rx_tail; ZYNQ_STATS(zcan, CAN_STATS_PIO_RX); /* notify the receiver */ zcan_usr_rx_complete(zcan); if (kthread_should_stop()) { break; } } } done: zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d ch%d %s done.\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__); return 0; } #endif /* * CAN message rx handling in PIO mode: called in interrupt context * Get the received CAN messages from H/W to a CAN message buffer ring. */ static void zcan_pio_rx_proc(zynq_can_t *zcan) { zynq_chan_t *zchan = zcan->zchan; bcan_msg_t *bmsg; zcan_msg_t *cmsg; int rx_tail; int status; rx_tail = zcan->zcan_buf_rx_tail; /* check if there is data in Rx FIFO */ while (1) { status = zcan_reg_read(zcan, ZCAN_IP_PIO_STATUS); if (status == -1 || !(status & ZCAN_IP_PIO_RX_READY)) { break; /* No data pending */ } /* if full, free some buffer by increasing the rx_head */ if (zcan_buf_rx_full(zcan)) { zcan_buf_inc_rx_head(zcan, ZCAN_IP_RXFIFO_MAX); } /* read out one message */ bmsg = zcan->zcan_buf_rx_msg + rx_tail; /* record the timestamp for the msg */ #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE ktime_get_real_ts((struct timespec *) #else ktime_get_real_ts64((struct timespec64 *) #endif (&bmsg->bcan_msg_timestamp)); bmsg->bcan_msg_timestamp.tv_usec /= NSEC_PER_USEC; /* CAN msg info */ cmsg = (zcan_msg_t *)bmsg; cmsg->cmsg_id = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_ID); cmsg->cmsg_len = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_DLC); cmsg->cmsg_data1 = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_DW1); cmsg->cmsg_data2 = zcan_reg_read(zcan, ZCAN_IP_RXFIFO_DW2); /* clear the Rx interrupt bits */ zcan_reg_write(zcan, ZCAN_IP_PIO_STATUS, ZCAN_IP_PIO_RX_READY); zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s: Rx %d msg %lu: " "sid=0x%x, srtr=%d, eid=0x%x, ertr=%d; " "data_len=%d(0x%x); data1=0x%x; data2=0x%x(%d)\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, rx_tail, zcan->stats[CAN_STATS_PIO_RX].cnt, cmsg->cmsg_id_sid, cmsg->cmsg_id_srtr, cmsg->cmsg_id_eid, cmsg->cmsg_id_ertr, cmsg->cmsg_len_len, cmsg->cmsg_len, cmsg->cmsg_data1, cmsg->cmsg_data2, cmsg->cmsg_data2); /* NEXT tail */ rx_tail++; rx_tail %= zcan->zcan_buf_rx_num; zcan->zcan_buf_rx_tail = rx_tail; ZYNQ_STATS(zcan, CAN_STATS_PIO_RX); /* notify the receiver */ zcan_usr_rx_complete(zcan); } } /* * CAN message rx handling in DMA mode: called in interrupt context * Get the received CAN messages from H/W to a CAN message buffer ring. */ static void zcan_dma_rx_proc(zynq_can_t *zcan) { zynq_chan_t *zchan = zcan->zchan; bcan_msg_t *bmsg; zcan_msg_t *cmsg; int pio_rx_tail; zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; u32 rx_head, rx_tail, rx_off; void *msg = NULL; u32 msgsz = zcan->zdev->zcan_rx_hw_ts ? sizeof(bcan_msg_t) : sizeof(zcan_msg_t); rx_tail = zchan_reg_read(zchan, ZYNQ_CH_RX_TAIL); /* * The tail pointer can be pointing to the middle of a CAN message, * we must align it to the beginning boundary of the CAN message. */ rx_tail &= ~(msgsz - 1); rx_head = zchan_rx->zchan_rx_head; if (rx_head >= zchan_rx->zchan_rx_size || rx_tail >= zchan_rx->zchan_rx_size) { zynq_err("%d can%d ch%d %s check failed: " "rx_head=0x%x, rx_tail=0x%x, max_off=0x%x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, rx_head, rx_tail, zchan_rx->zchan_rx_size - 1); return; } zynq_trace(ZYNQ_TRACE_CAN, "%d can%d ch%d %s: rx_head=0x%x, rx_tail=0x%x\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, rx_head, rx_tail); zchan_rx->zchan_rx_tail = rx_tail; pio_rx_tail = zcan->zcan_buf_rx_tail; for (rx_off = rx_head; rx_off != rx_tail; rx_off += msgsz, rx_off &= (zchan_rx->zchan_rx_size - 1)) { if (rx_off == rx_head || ZCHAN_RX_BUF_OFFSET(zchan_rx, rx_off) == 0) { /* * first loop or get to a new buffer: need to retrieve * the new buffer base. */ zchan_rx_off2addr(zchan_rx, rx_off, &msg, NULL); } else { /* within the same buffer: increment the msg address */ msg = (char *)msg + msgsz; } /* if full, free some buffer by increasing the rx_head */ if (zcan_buf_rx_full(zcan)) { zcan_buf_inc_rx_head(zcan, ZCAN_IP_RXFIFO_MAX); } /* copy out one CAN message */ bmsg = zcan->zcan_buf_rx_msg + pio_rx_tail; memcpy(bmsg, msg, msgsz); if (!zcan->zdev->zcan_rx_hw_ts || zynq_disable_can_hw_ts) { /* do S/W timestamp for the msg */ #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE ktime_get_real_ts((struct timespec *)(&bmsg->bcan_msg_timestamp)); #else ktime_get_real_ts64((struct timespec64 *)(&bmsg->bcan_msg_timestamp)); #endif bmsg->bcan_msg_timestamp.tv_usec /= NSEC_PER_USEC; } /* CAN msg info */ cmsg = (zcan_msg_t *)msg; zynq_trace(ZYNQ_TRACE_CAN_MSG, "%d can%d ch%d %s: Rx %d msg %lu " "rx_off=0x%x: sid=0x%x, srtr=%d, eid=0x%x, ertr=%d; " "data_len=%d(0x%x); data1=0x%x; data2=0x%x(%d)\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, zchan->zchan_num, __FUNCTION__, pio_rx_tail, zchan->stats[CHAN_STATS_RX].cnt, rx_off, cmsg->cmsg_id_sid, cmsg->cmsg_id_srtr, cmsg->cmsg_id_eid, cmsg->cmsg_id_ertr, cmsg->cmsg_len_len, cmsg->cmsg_len, cmsg->cmsg_data1, cmsg->cmsg_data2, cmsg->cmsg_data2); /* NEXT tail */ pio_rx_tail++; pio_rx_tail %= zcan->zcan_buf_rx_num; zcan->zcan_buf_rx_tail = pio_rx_tail; ZYNQ_STATS(zchan, CHAN_STATS_RX); /* notify the receiver */ zcan_usr_rx_complete(zcan); } /* update h/w head index */ zchan_reg_write(zchan, ZYNQ_CH_RX_HEAD, rx_off); zchan_rx->zchan_rx_head = rx_off; } void zcan_rx_proc(zynq_can_t *zcan) { if (zcan->zdev->zcan_rx_dma) { zcan_dma_rx_proc(zcan); } else { zcan_pio_rx_proc(zcan); } } /* CAN Rx/Tx test function in DMA mode */ void zcan_test(zynq_can_t *zcan, int loopback, int msgcnt) { zcan_msg_t tx_cmsg; int i, retry_count = 10; /* init and start the CAN IP */ zcan_pio_reset(zcan); zcan_pio_start(zcan); if (loopback) { zcan_pio_loopback_set(zcan); } tx_cmsg.cmsg_id = 0x05000000; tx_cmsg.cmsg_len = 0x80000000; zynq_err("%d can%d %s: Tx test Start!!!\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); for (i = 1; i <= msgcnt; i++) { tx_cmsg.cmsg_data1 = i; tx_cmsg.cmsg_data2 = i; retry_count = 10; retry: if (zchan_tx_one_msg(zcan->zchan, &tx_cmsg, sizeof(zcan_msg_t))) { if (--retry_count) { msleep(1); goto retry; } else { break; } } } mdelay(ZCAN_PIO_STOP_DELAY); zynq_err("%d can%d %s: Tx test End %d(%d)!!!\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, i - 1, msgcnt); } /* CAN Rx/Tx test function in pio mode */ void zcan_pio_test(zynq_can_t *zcan, int loopback, int hi_pri, int msgcnt) { zcan_msg_t tx_cmsg; #if !defined(PIO_RX_THREAD) && !defined(PIO_RX_INTR) zcan_msg_t rx_cmsg; #endif ktime_t ktime_start, ktime_end; int i; if (msgcnt == 0) { zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s: msgcnt is 0!\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); return; } if (loopback) { zcan_pio_loopback_set(zcan); } zcan_pio_start(zcan); tx_cmsg.cmsg_id = 0; tx_cmsg.cmsg_id_sid = 0x554; tx_cmsg.cmsg_len = 0x80000000; zynq_err("%d can%d %s: Tx test start:\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); ktime_start = ktime_get(); for (i = 1; i <= msgcnt; i++) { tx_cmsg.cmsg_data1 = 0x55555555; tx_cmsg.cmsg_data2 = i; // tx_cmsg.cmsg_data1; #if !defined(PIO_RX_THREAD) && !defined(PIO_RX_INTR) /* do Rx after each Tx and verify if the data matches */ if (hi_pri) { /* use high priority Tx FIFO */ if (zcan_pio_tx_hi_one(zcan, &tx_cmsg, 1, 1) != BCAN_OK) { zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s: Tx test failed %d!!!\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, i); goto out; } } else { /* use normal priority Tx FIFO */ if (zcan_pio_tx_one(zcan, &tx_cmsg, 1, 1) != BCAN_OK) { zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s: " "Tx test failed %d!!!\n", ZYNQ_INST(zcan->zchan), zhan->zcan_ip_num, __FUNCTION__, i); goto out; } } if (loopback) { zcan_pio_rx(zcan, (char *)&rx_cmsg, sizeof(zcan_msg_t), 1); if (tx_cmsg.cmsg_data1 != rx_cmsg.cmsg_data1 || tx_cmsg.cmsg_data2 != rx_cmsg.cmsg_data2) { zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s: msg" " %d verification failed tx_data1=0x%x " "tx_data2=0x%x, rx_data1=0x%x i" "rx_data2=0x%x\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, i, tx_cmsg.cmsg_data1, tx_cmsg.cmsg_data2, rx_cmsg.cmsg_data1, rx_cmsg.cmsg_data2); goto out; } } #else if (hi_pri) { /* use high priority Tx FIFO */ if (zcan_pio_tx_hi_one(zcan, &tx_cmsg, 1, 0) != BCAN_OK) { zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s: Tx test failed %d!!!\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, i); goto out; } } else { /* use normal priority Tx FIFO */ if (zcan_pio_tx_one(zcan, &tx_cmsg, 1, 0) != BCAN_OK) { zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s: Tx test failed %d!!!\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, i); goto out; } } #endif } ktime_end = ktime_get(); zynq_err("%d can%d %s: " "Tx test succeeded, total %d pkts, per pkt time is %lld ns!!!\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, msgcnt, ktime_to_ns(ktime_sub(ktime_end, ktime_start)) / msgcnt); out: mdelay(ZCAN_PIO_STOP_DELAY); if (loopback) { zcan_pio_loopback_unset(zcan); } } #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) static int zcan_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg) #else static long zcan_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) #endif { zynq_can_t *zcan = filp->private_data; int err = 0; char ioc_name[32]; if (zcan == NULL) { return -1; } zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s enter: cmd=0x%x, arg=0x%lx, zcan=0x%p\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, cmd, arg, zcan); switch (cmd) { case ZYNQ_IOC_CAN_TX_TIMEOUT_SET: sprintf(ioc_name, "ZYNQ_IOC_CAN_TX_TIMEOUT_SET"); zcan_tx_timeout_set(zcan, arg); break; case ZYNQ_IOC_CAN_RX_TIMEOUT_SET: sprintf(ioc_name, "ZYNQ_IOC_CAN_RX_TIMEOUT_SET"); zcan_rx_timeout_set(zcan, arg); break; case ZYNQ_IOC_CAN_DEV_START: sprintf(ioc_name, "ZYNQ_IOC_CAN_DEV_START"); zcan_pio_start(zcan); break; case ZYNQ_IOC_CAN_DEV_STOP: sprintf(ioc_name, "ZYNQ_IOC_CAN_DEV_STOP"); zcan_pio_stop(zcan); break; case ZYNQ_IOC_CAN_DEV_RESET: sprintf(ioc_name, "ZYNQ_IOC_CAN_DEV_RESET"); zcan_pio_reset(zcan); break; case ZYNQ_IOC_CAN_BAUDRATE_SET: sprintf(ioc_name, "ZYNQ_IOC_CAN_BAUDRATE_SET"); err = zcan_pio_set_baudrate(zcan, arg); break; case ZYNQ_IOC_CAN_BAUDRATE_GET: sprintf(ioc_name, "ZYNQ_IOC_CAN_BAUDRATE_GET"); if (copy_to_user((void __user *)arg, &zcan->zcan_pio_baudrate, sizeof(unsigned long))) { err = -EFAULT; } break; case ZYNQ_IOC_CAN_LOOPBACK_SET: sprintf(ioc_name, "ZYNQ_IOC_CAN_LOOPBACK_SET"); zcan_pio_loopback_set(zcan); break; case ZYNQ_IOC_CAN_LOOPBACK_UNSET: sprintf(ioc_name, "ZYNQ_IOC_CAN_LOOPBACK_UNSET"); zcan_pio_loopback_unset(zcan); break; case ZYNQ_IOC_CAN_RECV: { ioc_bcan_msg_t bcan_msg_arg; sprintf(ioc_name, "ZYNQ_IOC_CAN_RECV"); if (copy_from_user(&bcan_msg_arg, (void __user *)arg, sizeof(ioc_bcan_msg_t))) { bcan_msg_arg.ioc_msg_err = BCAN_FAIL; goto rx_out; } if (bcan_msg_arg.ioc_msg_rx_clear) { zcan_clear_buf_rx(zcan); } if (ZDEV_IS_ERR(zcan->zdev)) { bcan_msg_arg.ioc_msg_err = BCAN_DEV_ERR; goto rx_out; } bcan_msg_arg.ioc_msg_err = zcan_rx_user(zcan, &bcan_msg_arg, &bcan_msg_arg.ioc_msg_num_done); rx_out: if (copy_to_user((void __user *) (&((ioc_bcan_msg_t *)arg)->ioc_msg_num_done), &bcan_msg_arg.ioc_msg_num_done, 2 * sizeof(int))) { err = -EFAULT; } break; } case ZYNQ_IOC_CAN_SEND: { ioc_bcan_msg_t bcan_msg_arg; sprintf(ioc_name, "ZYNQ_IOC_CAN_SEND"); if (copy_from_user(&bcan_msg_arg, (void __user *)arg, sizeof(ioc_bcan_msg_t))) { bcan_msg_arg.ioc_msg_err = BCAN_FAIL; goto tx_out; } if (ZDEV_IS_ERR(zcan->zdev)) { bcan_msg_arg.ioc_msg_err = BCAN_DEV_ERR; goto tx_out; } bcan_msg_arg.ioc_msg_err = zcan_tx_user(zcan, &bcan_msg_arg, 0, &bcan_msg_arg.ioc_msg_num_done); tx_out: if (copy_to_user((void __user *) (&((ioc_bcan_msg_t *)arg)->ioc_msg_num_done), &bcan_msg_arg.ioc_msg_num_done, 2 * sizeof(int))) { err = -EFAULT; } break; } case ZYNQ_IOC_CAN_SEND_HIPRI: { ioc_bcan_msg_t bcan_msg_arg; sprintf(ioc_name, "ZYNQ_IOC_CAN_SEND_HIPRI"); if (copy_from_user(&bcan_msg_arg, (void __user *)arg, sizeof(ioc_bcan_msg_t))) { bcan_msg_arg.ioc_msg_err = BCAN_FAIL; goto tx_hi_out; } if (ZDEV_IS_ERR(zcan->zdev)) { bcan_msg_arg.ioc_msg_err = BCAN_DEV_ERR; goto tx_hi_out; } bcan_msg_arg.ioc_msg_err = zcan_tx_user(zcan, &bcan_msg_arg, 1, &bcan_msg_arg.ioc_msg_num_done); tx_hi_out: if (copy_to_user((void __user *) (&((ioc_bcan_msg_t *)arg)->ioc_msg_num_done), &bcan_msg_arg.ioc_msg_num_done, 2 * sizeof(int))) { err = -EFAULT; } break; } case ZYNQ_IOC_CAN_GET_STATUS_ERR: { ioc_bcan_status_err_t status_err; sprintf(ioc_name, "ZYNQ_IOC_CAN_GET_STATUS_ERR"); if (ZDEV_IS_ERR(zcan->zdev)) { status_err.bcan_ioc_err = BCAN_DEV_ERR; } else { status_err.bcan_status = zcan_reg_read(zcan, ZCAN_IP_SR); status_err.bcan_err_status = zcan_reg_read(zcan, ZCAN_IP_ESR); status_err.bcan_err_count = zcan_reg_read(zcan, ZCAN_IP_ECR); status_err.bcan_ioc_err = BCAN_OK; } if (copy_to_user((void __user *)arg, &status_err, sizeof(ioc_bcan_status_err_t))) { err = -EFAULT; } break; } default: sprintf(ioc_name, "ZYNQ_IOC_CAN_UNKNOWN"); err = -EINVAL; break; } zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done: cmd=0x%x(%s), error=%d\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, cmd, ioc_name, err); return err; } static int zcan_open(struct inode *inode, struct file *filp) { zynq_can_t *zcan; zcan = container_of(inode->i_cdev, zynq_can_t, zcan_pio_cdev); spin_lock(&zcan->zcan_pio_lock); if (zcan->zcan_pio_opened != 0) { zynq_err("%d can%d %s: device is opened already!\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_lock); return BCAN_DEV_BUSY; } zcan->zcan_pio_opened = 1; spin_unlock(&zcan->zcan_pio_lock); filp->private_data = zcan; /* reset to default normal mode */ zcan_pio_reset(zcan); if (ZDEV_IS_ERR(zcan->zdev)) { spin_lock(&zcan->zcan_pio_lock); zcan->zcan_pio_opened = 0; zynq_err("%d can%d %s: device access error!\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); spin_unlock(&zcan->zcan_pio_lock); return BCAN_DEV_ERR; } zynq_err("%d can%d %s done: zcan=0x%p\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, zcan); return 0; } static int zcan_release(struct inode *inode, struct file *filp) { zynq_can_t *zcan = filp->private_data; zynq_chan_t *zchan = zcan->zchan; spin_lock(&zcan->zcan_pio_lock); spin_lock(&zcan->zcan_pio_tx_lock); spin_lock_bh(&zcan->zcan_pio_rx_lock); zcan->zcan_pio_opened = 0; /* reset to quiese the h/w */ zcan->zcan_pio_state = ZYNQ_STATE_RESET; zcan_reg_write(zcan, ZCAN_IP_SRR, 0); mdelay(10); zchan_reg_write(zchan, ZYNQ_CH_RESET, ZYNQ_CH_RESET_EN); zchan_reg_write(zchan, ZYNQ_CH_RESET, 0); spin_unlock_bh(&zcan->zcan_pio_rx_lock); spin_unlock(&zcan->zcan_pio_tx_lock); spin_unlock(&zcan->zcan_pio_lock); zynq_err("%d can%d %s done: zcan=0x%p\n", ZYNQ_INST(zchan), zcan->zcan_ip_num, __FUNCTION__, zcan); return 0; } struct file_operations zcan_pio_fops = { .owner = THIS_MODULE, #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) .ioctl = zcan_ioctl, #else .unlocked_ioctl = zcan_ioctl, #endif .open = zcan_open, .release = zcan_release }; int zcan_pio_init(zynq_can_t *zcan, enum zcan_ip_mode mode) { u32 ip_mode = ZCAN_IP_MSR_NORMAL; char zcan_pio_name[16]; /* create the /dev/zynq_can%d */ sprintf(zcan_pio_name, ZYNQ_DEV_NAME_CAN"%u", zcan->zdev->zdev_can_num_start + zcan->zcan_ip_num); zcan->zcan_pio_dev = zynq_create_cdev(zcan, &zcan->zcan_pio_cdev, &zcan_pio_fops, zcan_pio_name); if (!zcan->zcan_pio_dev) { zynq_err("%s: failed to create cdev.\n", __FUNCTION__); return -1; } if (zynq_can_rx_buf_num < ZCAN_IP_MSG_MIN) { zynq_can_rx_buf_num = ZCAN_IP_MSG_MIN; } else if (zynq_can_rx_buf_num > ZCAN_IP_MSG_MAX) { zynq_can_rx_buf_num = ZCAN_IP_MSG_MAX; } /* allocate Rx buffer ring */ zcan->zcan_buf_rx_msg = kzalloc(zynq_can_rx_buf_num * sizeof(bcan_msg_t), GFP_KERNEL); if (zcan->zcan_buf_rx_msg == NULL) { zynq_destroy_cdev(zcan->zcan_pio_dev, &zcan->zcan_pio_cdev); zynq_err("%s: failed to alloc cmsg array.\n", __FUNCTION__); return -1; } zcan->zcan_buf_rx_num = zynq_can_rx_buf_num; zcan->zcan_pio_baudrate = ZYNQ_BAUDRATE_500K; spin_lock_init(&zcan->zcan_pio_lock); spin_lock_init(&zcan->zcan_pio_tx_lock); spin_lock_init(&zcan->zcan_pio_tx_hi_lock); spin_lock_init(&zcan->zcan_pio_rx_lock); init_completion(&zcan->zcan_usr_rx_comp); if (mode == ZCAN_IP_SLEEP) { ip_mode = ZCAN_IP_MSR_SLEEP; } else if (mode == ZCAN_IP_LOOPBACK) { ip_mode = ZCAN_IP_MSR_LOOPBACK; } /* init the CAN IP h/w */ zcan_pio_chip_init(zcan, ip_mode, 1); #ifdef PIO_RX_THREAD /* create the pio rx thread */ zcan->zcan_pio_rx_thread = kthread_run(zcan_pio_rx_poll, (void *)zcan, "zcan_pio_rx_poll"); if (IS_ERR(zcan->zcan_pio_rx_thread)) { zynq_destroy_cdev(zcan->zcan_pio_dev, &zcan->zcan_pio_cdev); kfree(zcan->zcan_buf_rx_msg); zynq_err("%s: failed to creat rx poll thread.\n", __FUNCTION__); return (-1); } #endif zynq_trace(ZYNQ_TRACE_CAN_PIO, "%d can%d %s done.\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__); return 0; } void zcan_pio_fini(zynq_can_t *zcan) { #ifdef PIO_RX_THREAD kthread_stop(zcan->zcan_pio_rx_thread); #endif zcan_pio_reset_noinit(zcan); zynq_destroy_cdev(zcan->zcan_pio_dev, &zcan->zcan_pio_cdev); kfree(zcan->zcan_buf_rx_msg); } static void zcan_stats_init(zynq_can_t *zcan) { int i; for (i = 0; i < CAN_STATS_NUM; i++) { zcan->stats[i].label = zcan_stats_label[i]; } } int zcan_init(zynq_can_t *zcan) { zynq_dev_t *zdev = zcan->zdev; snprintf(zcan->prefix, ZYNQ_LOG_PREFIX_LEN, "%d can%d", zdev->zdev_inst, zcan->zcan_ip_num); zcan_stats_init(zcan); /* init the CAN IP register base */ zcan->zcan_ip_reg = zdev->zdev_bar2 + ZCAN_IP_OFFSET * zcan->zcan_ip_num; zynq_trace(ZYNQ_TRACE_CAN, "%d can%d %s zcan_ip_reg=0x%p\n", zdev->zdev_inst, zcan->zcan_ip_num, __FUNCTION__, zcan->zcan_ip_reg); /* init CAN IP */ if (zcan_pio_init(zcan, ZCAN_IP_NORMAL)) { zynq_err("%d can%d %s: failed to init CAN IP\n", zdev->zdev_inst, zcan->zcan_ip_num, __FUNCTION__); return -1; } zynq_trace(ZYNQ_TRACE_CAN, "%d can%d %s done: zcan=%p\n", zdev->zdev_inst, zcan->zcan_ip_num, __FUNCTION__, zcan); return 0; } void zcan_fini(zynq_can_t *zcan) { zcan_pio_fini(zcan); zynq_trace(ZYNQ_TRACE_CAN, "%d can%d %s done: zcan=%p\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, zcan); } /* * return the zcan pointer conresponding to the CAN IP number */ zynq_can_t *can_ip_to_zcan(zynq_dev_t *zdev, u32 can_ip_num) { zynq_can_t *zcan; int i; if (can_ip_num >= zdev->zdev_can_cnt) { zynq_trace(ZYNQ_TRACE_CAN, "%s wrong can_ip_num=%d, the " "device only have %d CAN IPs\n", __FUNCTION__, can_ip_num, zdev->zdev_can_cnt); return NULL; } zcan = zdev->zdev_cans; for (i = 0; i < zdev->zdev_can_cnt; i++, zcan++) { if (zcan->zcan_ip_num == can_ip_num) { zynq_trace(ZYNQ_TRACE_CAN, "%s succeeded to find " "zcan for can_ip_num=%d.\n", __FUNCTION__, can_ip_num); return zcan; } } zynq_trace(ZYNQ_TRACE_CAN, "%s failed to find zcan for can_ip_num " "%d.\n", __FUNCTION__, can_ip_num); return NULL; } #ifdef ZYNQ_DEBUG module_param_named(canbtr, zynq_can_ip_btr, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(canbtr, "CAN bus sampling point"); #endif module_param_named(canrxbuf, zynq_can_rx_buf_num, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(canrxbuf, "CAN Rx buffer number"); module_param_named(nocanhwts, zynq_disable_can_hw_ts, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(nocanhwts, "disable CAN Rx H/W timestamp"); module_param_named(canrxdma, zynq_enable_can_rx_dma, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(canrxdma, "enable CAN Rx DMA mode"); module_param_named(cantxdma, zynq_enable_can_tx_dma, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(cantxdma, "enable CAN Tx DMA mode");
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_cam_hci.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/delay.h> #include "basa.h" #define I2C_ID_CAM_DES_PRLL(i) (0x60 + (i)) #define I2C_ID_CAM_ISP 0x48 #define ZCAM_WAIT_DELAY 100 /* usec */ #define ZCAM_WAIT_RETRY 50 unsigned char zcam_dev_cfgs[2][8] = { /* * Driver ID, Read Command, Address Width, Magic Number, * Flash Size (4 bytes) */ { 0x02, 0x00, 0x03, 0x18, 0x00, 0x00, 0x80, 0x00 }, { 0x02, 0x00, 0x02, 0x10, 0x00, 0x00, 0x80, 0x00 } }; static inline void zcam_i2c_acc_init(zynq_video_t *zvideo, ioc_zynq_i2c_acc_t *i2c_acc) { i2c_acc->i2c_id = I2C_ID_CAM_DES_PRLL(zvideo->index); i2c_acc->i2c_bus = 2; } static int zcam_i2c_init(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; ioc_zynq_i2c_acc_t i2c_acc; unsigned char i2c_addrs[2] = { 0x10, 0x08 }; int i; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); zcam_i2c_acc_init(zvideo, &i2c_acc); /* Program the slave id of the ISP */ for (i = 0; i < 2; i++) { i2c_acc.i2c_addr_hi = 0; i2c_acc.i2c_addr = i2c_addrs[i]; i2c_acc.i2c_data = I2C_ID_CAM_ISP << 1; i2c_acc.i2c_addr_16 = 0; ret = zdev_i2c_write(zdev, &i2c_acc); if (ret ) { return ret; } } return 0; } static void zcam_i2c_fini(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; ioc_zynq_i2c_acc_t i2c_acc; unsigned char addrs[2] = { 0x10, 0x08 }; int i; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); zcam_i2c_acc_init(zvideo, &i2c_acc); /* Clean the previous settings */ for (i = 0; i < 2; i++) { i2c_acc.i2c_addr_hi = 0; i2c_acc.i2c_addr = addrs[i]; i2c_acc.i2c_data = 0; i2c_acc.i2c_addr_16 = 0; (void) zdev_i2c_write(zdev, &i2c_acc); } } static int zcam_i2c_read8(zynq_video_t *zvideo, unsigned short addr, unsigned char *data) { zynq_dev_t *zdev = zvideo->zdev; ioc_zynq_i2c_acc_t i2c_acc; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: addr=0x%04x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr); zcam_i2c_acc_init(zvideo, &i2c_acc); i2c_acc.i2c_id = I2C_ID_CAM_ISP; i2c_acc.i2c_addr_hi = (addr >> 8) & 0xFF; i2c_acc.i2c_addr = addr & 0xFF; i2c_acc.i2c_data = 0; i2c_acc.i2c_addr_16 = 1; ret = zdev_i2c_read(zdev, &i2c_acc); if (ret ) { return ret; } *data = i2c_acc.i2c_data; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: Done. addr=0x%04x data=0x%02x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr, *data); return 0; } static int zcam_i2c_read16(zynq_video_t *zvideo, unsigned short addr, unsigned short *data) { zynq_dev_t *zdev = zvideo->zdev; unsigned char *bytes = (unsigned char *)data; int ret; int i; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: addr=0x%04x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr); for (i = 0; i < 2; i++) { ret = zcam_i2c_read8(zvideo, addr + i, &bytes[1 - i]); if (ret) { return ret; } } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: Done. addr=0x%04x data=0x%04x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr, *data); return 0; } static int zcam_i2c_read32(zynq_video_t *zvideo, unsigned short addr, unsigned int *data) { zynq_dev_t *zdev = zvideo->zdev; unsigned char *bytes = (unsigned char *)data; int ret; int i; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: addr=0x%04x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr); for (i = 0; i < 4; i++) { ret = zcam_i2c_read8(zvideo, addr + i, &bytes[3 - i]); if (ret) { return ret; } } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: Done. addr=0x%04x data=0x%08x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr, *data); return 0; } static int zcam_i2c_write8(zynq_video_t *zvideo, unsigned short addr, unsigned char data) { zynq_dev_t *zdev = zvideo->zdev; ioc_zynq_i2c_acc_t i2c_acc; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: addr=0x%04x data=0x%02x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr, data); zcam_i2c_acc_init(zvideo, &i2c_acc); i2c_acc.i2c_id = I2C_ID_CAM_ISP; i2c_acc.i2c_addr_hi = (addr >> 8) & 0xFF; i2c_acc.i2c_addr = addr & 0xFF; i2c_acc.i2c_data = data; i2c_acc.i2c_addr_16 = 1; ret = zdev_i2c_write(zdev, &i2c_acc); if (ret ) { return ret; } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: Done. addr=0x%04x data=0x%02x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr, data); return 0; } static int zcam_i2c_write16(zynq_video_t *zvideo, unsigned short addr, unsigned short data) { zynq_dev_t *zdev = zvideo->zdev; unsigned char *bytes = (unsigned char *)&data; int ret; int i; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: addr=0x%04x data=0x%04x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr, data); for (i = 0; i < 2; i++) { ret = zcam_i2c_write8(zvideo, addr + i, bytes[1 - i]); if (ret) { return ret; } } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: Done. addr=0x%04x data=0x%04x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr, data); return 0; } static int zcam_i2c_write32(zynq_video_t *zvideo, unsigned short addr, unsigned int data) { zynq_dev_t *zdev = zvideo->zdev; unsigned char *bytes = (unsigned char *)&data; int ret; int i; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: addr=0x%04x data=0x%08x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr, data); for (i = 0; i < 4; i++) { ret = zcam_i2c_write8(zvideo, addr + i, bytes[3 - i]); if (ret) { return ret; } } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: Done. addr=0x%04x data=0x%08x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, addr, data); return 0; } int zcam_reg_read(zynq_video_t *zvideo, zynq_cam_acc_t *cam_acc) { zynq_dev_t *zdev = zvideo->zdev; int ret; spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } switch (cam_acc->data_sz) { case 1: ret = zcam_i2c_read8(zvideo, cam_acc->addr, (unsigned char *)&cam_acc->data); break; case 2: ret = zcam_i2c_read16(zvideo, cam_acc->addr, (unsigned short *)&cam_acc->data); break; case 4: ret = zcam_i2c_read32(zvideo, cam_acc->addr, &cam_acc->data); break; default: zynq_err("%d vid%d %s: ERROR invalid data size %d\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, cam_acc->data_sz); ret = -1; break; } end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } int zcam_reg_write(zynq_video_t *zvideo, zynq_cam_acc_t *cam_acc) { zynq_dev_t *zdev = zvideo->zdev; int ret; spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } switch (cam_acc->data_sz) { case 1: ret = zcam_i2c_write8(zvideo, cam_acc->addr, (unsigned char)cam_acc->data); break; case 2: ret = zcam_i2c_write16(zvideo, cam_acc->addr, (unsigned short)cam_acc->data); break; case 4: ret = zcam_i2c_write32(zvideo, cam_acc->addr, cam_acc->data); break; default: zynq_err("%d vid%d %s: ERROR invalid data size %d\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, cam_acc->data_sz); ret = -1; break; } end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } static void zcam_init_time_params(zynq_video_t *zvideo) { zynq_cam_caps_t *caps = &zvideo->caps; zvideo->t_row = T_ROW(caps->line_len_pck, caps->pixel_clock); zvideo->t_first = T_FRAME(caps->frame_len_lines, caps->line_len_pck, caps->pixel_clock); zvideo->t_middle = zvideo->t_first + T_FRAME(ZVIDEO_IMAGE_HEIGHT / 2, caps->line_len_pck, caps->pixel_clock); zvideo->t_last = zvideo->t_first + T_FRAME(ZVIDEO_IMAGE_HEIGHT, caps->line_len_pck, caps->pixel_clock); } static void zcam_read_embedded_data_230(zynq_video_t *zvideo, void *buf) { zynq_dev_t *zdev = zvideo->zdev; unsigned int frame_count = 0; unsigned short frame_lines = 0; unsigned short line_pck = 0; unsigned short coarse_int = 0; if (EM_REG_VAL_230(buf, BASE) == EM_REG_CHIP_VER) { frame_count = EM_REG_VAL_230(buf, FRAME_CNT); zvideo->last_meta_cnt = frame_count; frame_lines = EM_REG_VAL_230(buf, FRAME_LNS); if (frame_lines != zvideo->caps.frame_len_lines) { zynq_log("%d vid%d %s: changed frame_length_lines, " "new: %u, old: %u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, frame_lines, zvideo->caps.frame_len_lines); zvideo->caps.frame_len_lines = frame_lines; zcam_init_time_params(zvideo); } line_pck = EM_REG_VAL_230(buf, LINE_PCK) << 1; if (line_pck != zvideo->caps.line_len_pck) { zynq_log("%d vid%d %s: changed line_length_pck, " "new: %u, old: %u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, line_pck, zvideo->caps.line_len_pck); zvideo->caps.line_len_pck = line_pck; zcam_init_time_params(zvideo); } coarse_int = EM_REG_VAL_230(buf, COARSE_INT); zvideo->last_exp_time = T_FRAME(coarse_int, zvideo->caps.line_len_pck, zvideo->caps.pixel_clock); } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: " "sequence=%u, frame_count=%u, frame_lines=%u, line_pck=%u, " "coarse_int=%u, exposure_time=%uus\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->sequence, frame_count, frame_lines, line_pck, coarse_int, zvideo->last_exp_time); } static void zcam_read_embedded_data_231(zynq_video_t *zvideo, void *buf) { zynq_dev_t *zdev = zvideo->zdev; unsigned int frame_count = 0; unsigned int t1_clk = 0; unsigned int t1_row = 0; unsigned int t2_row = 0; unsigned int t3_row = 0; unsigned int t_tot = 0; unsigned int line_pck = 0; if (EM_REG_VAL_231(buf, BASE1) == EM_REG_FRAME_CNT_HI) { frame_count = (EM_REG_VAL_231(buf, FRAME_CNT_HI) << 16) | EM_REG_VAL_231(buf, FRAME_CNT_LO); zvideo->last_meta_cnt = frame_count; } if (EM_REG_VAL_231(buf, BASE2) == EM_REG_EXP_T1_ROW) { t1_row = EM_REG_VAL_231(buf, EXP_T1_ROW); t2_row = EM_REG_VAL_231(buf, EXP_T2_ROW); t3_row = EM_REG_VAL_231(buf, EXP_T3_ROW); t1_clk = (EM_REG_VAL_231(buf, EXP_T1_CLK_HI) << 16) | EM_REG_VAL_231(buf, EXP_T1_CLK_LO); line_pck = t1_clk / t1_row; t_tot = t1_row + t2_row + t3_row + 3; zvideo->last_exp_time = T_FRAME(t_tot, zvideo->caps.line_len_pck, zvideo->caps.pixel_clock); } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: " "sequence=%u, frame_count=%u, t1_row=%u, t2_row = %u, t3_row = %u, t_tot = %u, " "t1_clk=%u, line_pck=%u, exposure_time=%uus\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->sequence, frame_count, t1_row, t2_row, t3_row, t_tot, t1_clk, line_pck, zvideo->last_exp_time); } static int zcam_probe(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; zynq_cam_caps_t *caps = &zvideo->caps; unsigned short data; unsigned int val; unsigned int orig; int reprobe = 0; int i; int ret; spin_lock(&zdev->zdev_lock); orig = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); caps->pin_swap = (orig & ZYNQ_CAM_PIN_SWAP) ? 1 : 0; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: probe with cam_config=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, orig); probe: if ((ret = zcam_i2c_init(zvideo))) { goto end; } /* Probe the camera (Check the camera minor version) */ for (i = 0; i < 10; i++) { ret = zcam_i2c_read16(zvideo, REG_MON_MINOR_VERSION, &data); if (!ret) { /* * Check the camera code name. * Pin-swap is always required for SharpVision cameras. */ if (((data >> 13) == CAM_CAP_CODENAME_SHARPVISION) && (!caps->pin_swap)) { ret = 0xFF; } else { caps->minor_version = data; } break; } udelay(ZCAM_WAIT_DELAY); } if (ret && !reprobe) { zcam_i2c_fini(zvideo); /* Reset I2C */ val = zynq_g_reg_read(zdev, ZYNQ_G_RESET); val |= ZYNQ_I2C_RESET; zynq_g_reg_write(zdev, ZYNQ_G_RESET, val); val &= ~ZYNQ_I2C_RESET; zynq_g_reg_write(zdev, ZYNQ_G_RESET, val); spin_unlock(&zdev->zdev_lock); msleep(20); /* Set pin-swap */ spin_lock(&zdev->zdev_lock); reprobe = 1; caps->pin_swap = !caps->pin_swap; val = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); if (caps->pin_swap) { val |= ZYNQ_CAM_PIN_SWAP; } else { val &= ~ZYNQ_CAM_PIN_SWAP; } zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, val); spin_unlock(&zdev->zdev_lock); if (ret == 0xFF) { msleep(20); } else { msleep(500); } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: re-probe with cam_config=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, val); spin_lock(&zdev->zdev_lock); goto probe; } end: if (ret) { zynq_err("%d vid%d %s: " "WARNING! Failed to probe camera pin status\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); if (reprobe) { zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, orig); caps->pin_swap = (orig & ZYNQ_CAM_PIN_SWAP) ? 1 : 0; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: restore cam_config=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, orig); } } zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } int zcam_check_caps(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; zynq_cam_caps_t *caps = &zvideo->caps; unsigned short addr; unsigned char data[4]; unsigned char *p8 = data; unsigned short *p16 = (unsigned short *)data; unsigned int *p32 = (unsigned int *)data; int change = 0; int ret; snprintf(caps->name, ZYNQ_VDEV_NAME_LEN, "%s%d", ZYNQ_FPD_CAM_NAME, zdev->zdev_video_port_map[zvideo->index]); caps->unique_id = 0; caps->major_version = -1; caps->minor_version = -1; caps->timestamp_type = zynq_video_ts_type; caps->interface_type = CAM_CAP_INTERFACE_PARALLEL; caps->trigger_mode = 0; caps->embedded_data = 0; caps->frame_len_lines = DEFAULT_FRAME_LINES_230; caps->line_len_pck = DEFAULT_LINE_PCK_230; caps->pixel_clock = DEFAULT_PIXCLK_230; if (zynq_video_pin_swap >= 0) { /* Force the pin-swap status */ caps->pin_swap = (zynq_video_pin_swap > 0) ? 1 : 0; spin_lock(&zdev->zdev_lock); *p32 = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); if (caps->pin_swap) { if (!(*p32 & ZYNQ_CAM_PIN_SWAP)) { *p32 |= ZYNQ_CAM_PIN_SWAP; change = 1; } } else { if (*p32 & ZYNQ_CAM_PIN_SWAP) { *p32 &= ~ZYNQ_CAM_PIN_SWAP; change = 1; } } if (change) { zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, *p32); } spin_unlock(&zdev->zdev_lock); if (change) { msleep(500); } } else { /* Probe camera to determine the pin-swap status */ if (!(zvideo->state & ZVIDEO_STATE_STREAMING)) { if ((ret = zcam_probe(zvideo))) { return ret; } } } spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } /* Check the camera unique id */ addr = REG_UNIQUE_ID; *p16 = 0; if (!zcam_i2c_read16(zvideo, addr, p16)) { caps->unique_id = *p16; } /* Check the camera major version */ addr = REG_MON_MAJOR_VERSION; *p16 = 0; if (!zcam_i2c_read16(zvideo, addr, p16)) { caps->major_version = *p16; snprintf(caps->name, ZYNQ_VDEV_NAME_LEN, "%s%d-%04x", ZYNQ_FPD_CAM_NAME, zdev->zdev_video_port_map[zvideo->index], caps->major_version); } if (caps->minor_version == (unsigned short)-1) { /* Check the camera minor version */ addr = REG_MON_MINOR_VERSION; *p16 = 0; if (!zcam_i2c_read16(zvideo, addr, p16)) { caps->minor_version = *p16; } } /* Check the embedded metadata support */ addr = REG_SNSR_CTRL_OPERATION_MODE; *p16 = 0; if (!zcam_i2c_read16(zvideo, addr, p16)) { if (*p16 & SNSR_CTRL_EMBD_DATA_ENABLE) { caps->embedded_data = 1; } else { caps->embedded_data = 0; } } /* Check the trigger mode */ addr = REG_MODE_SYNC_TYPE; *p8 = 0; if (!zcam_i2c_read8(zvideo, addr, p8)) { caps->trigger_mode = *p8; } /* Check the frame length lines */ addr = REG_SNSR_CFG_FRAME_LEN_LINES; *p16 = 0; if (!zcam_i2c_read16(zvideo, addr, p16)) { caps->frame_len_lines = *p16; } else if (caps->code_name == CAM_CAP_CODENAME_SHARPVISION) { caps->frame_len_lines = DEFAULT_FRAME_LINES_231; } else { caps->frame_len_lines = DEFAULT_FRAME_LINES_230; } /* Check the line length pck */ addr = REG_SNSR_CFG_LINE_LEN_PCK; *p16 = 0; if (!zcam_i2c_read16(zvideo, addr, p16)) { caps->line_len_pck = *p16; } else if (caps->code_name == CAM_CAP_CODENAME_SHARPVISION) { caps->line_len_pck = DEFAULT_LINE_PCK_231; } else { caps->line_len_pck = DEFAULT_LINE_PCK_230; } /* Check the pixel clock */ addr = REG_SNSR_CFG_PIXCLK; *p32 = 0; ret = zcam_i2c_read32(zvideo, addr, p32); if (!ret && *p32) { caps->pixel_clock = *p32; } else if (caps->code_name == CAM_CAP_CODENAME_SHARPVISION) { caps->pixel_clock = DEFAULT_PIXCLK_231; } else { caps->pixel_clock = DEFAULT_PIXCLK_230; } end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); zcam_init_time_params(zvideo); zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: " "name=%s, unique_id=0x%04hx, major_version=0x%04hx, " "minor_version=0x%04hx, timestamp_type=%u, " "trigger_mode=%u, embedded_data=%u, " "interface_type=%u, pin_swap=%u, " "frame_length_lines=%hu, line_length_pck=%hu, pixclk=%u, " "t_row=%u, t_frame=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, caps->name, caps->unique_id, caps->major_version, caps->minor_version, caps->timestamp_type, caps->trigger_mode, caps->embedded_data, caps->interface_type, caps->pin_swap, caps->frame_len_lines, caps->line_len_pck, caps->pixel_clock, zvideo->t_row, zvideo->t_first); if (zynq_video_flash_16 > 0) { caps->feature |= CAM_CAP_FEATURE_FLASH_ADDR_16; } else if (zynq_video_flash_16 == 0) { caps->feature &= ~CAM_CAP_FEATURE_FLASH_ADDR_16; } if (caps->feature & CAM_CAP_FEATURE_FLASH_ADDR_16) { zvideo->dev_cfg = zcam_dev_cfgs[1]; } else { zvideo->dev_cfg = zcam_dev_cfgs[0]; } if (caps->code_name == CAM_CAP_CODENAME_SHARPVISION) { zvideo->read_em_data = zcam_read_embedded_data_231; } else { zvideo->read_em_data = zcam_read_embedded_data_230; } return ret; } static int zcam_command(zynq_video_t *zvideo, unsigned short cmd) { zynq_dev_t *zdev = zvideo->zdev; unsigned short addr; unsigned short data; int i; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: command=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, cmd); /* Check doorbell before issue the command */ addr = REG_COMMAND; data = 0; if ((ret = zcam_i2c_read16(zvideo, addr, &data))) { return ret; } if (data & CMD_DOORBELL) { zynq_err("%d vid%d %s: ERROR doorbell not cleared 0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, data); return -EAGAIN; } /* Issue the command */ addr = REG_COMMAND; data = cmd; if ((ret = zcam_i2c_write16(zvideo, addr, data))) { return ret; } /* Check and wait for the doorbell bit to be cleared */ addr = REG_COMMAND; data = -1; i = 0; while ((i < ZCAM_WAIT_RETRY) && (data & CMD_DOORBELL)) { if ((ret = zcam_i2c_read16(zvideo, addr, &data))) { return ret; } udelay(ZCAM_WAIT_DELAY); i++; } if ((i >= ZCAM_WAIT_RETRY) && (data & CMD_DOORBELL)) { zynq_err("%d vid%d %s: TIMEOUT command=0x%x response=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, cmd, data); return -EAGAIN; } if ((cmd == CMD_FLASH_STATUS) && (data == CMD_EBUSY)) { zynq_trace(ZYNQ_TRACE_VIDEO, "%d vid%d %s: BUSY command=0x%x response=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, cmd, data); return -EBUSY; } if (data) { zynq_err("%d vid%d %s: ERROR command=0x%x response=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, cmd, data); return -EINVAL; } zynq_trace(ZYNQ_TRACE_VIDEO, "%d vid%d %s: DONE command=0x%x response=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, cmd, data); return 0; } static int zcam_params_read(zynq_video_t *zvideo, unsigned char start, unsigned char *data, unsigned char size) { unsigned short addr; unsigned int i; int ret; if ((start + size) > REG_PARAM_POOL_SIZE) { return -EINVAL; } for (i = 0; i < size; i++) { addr = REG_PARAM_POOL_BASE + start + i; if ((ret = zcam_i2c_read8(zvideo, addr, &data[i]))) { return ret; } } return 0; } static int zcam_params_write(zynq_video_t *zvideo, unsigned char start, unsigned char *data, unsigned char size) { unsigned short addr; unsigned int i; int ret; if ((start + size) > REG_PARAM_POOL_SIZE) { return -EINVAL; } for (i = 0; i < size; i++) { addr = REG_PARAM_POOL_BASE + start + i; if ((ret = zcam_i2c_write8(zvideo, addr, data[i]))) { return ret; } } return 0; } static int zcam_sys_set_state(zynq_video_t *zvideo, unsigned char state) { int ret; if ((ret = zcam_params_write(zvideo, 0, &state, 1))) { return ret; } return zcam_command(zvideo, CMD_SYS_SET_STATE); } static int zcam_sys_get_state(zynq_video_t *zvideo, unsigned char *state) { int ret; if ((ret = zcam_command(zvideo, CMD_SYS_GET_STATE))) { return ret; } return zcam_params_read(zvideo, 0, state, 1); } int zcam_set_suspend(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; unsigned char state; int i; int ret; spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } state = 0x40; if ((ret = zcam_sys_set_state(zvideo, state))) { goto end; } i = 0; while (i < ZCAM_WAIT_RETRY) { ret = zcam_sys_get_state(zvideo, &state); if (!ret) { break; } if (ret != -EAGAIN) { goto end; } udelay(ZCAM_WAIT_DELAY); i++; } if (i >= ZCAM_WAIT_RETRY) { zynq_err("%d vid%d %s: timeout getting camera state\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); ret = -EAGAIN; goto end; } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: camera state 0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, state); end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } int zcam_change_config(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; unsigned char state; int i; int ret; spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } state = SYS_STATE_ENTER_CONFIG_CHANGE; if ((ret = zcam_sys_set_state(zvideo, state))) { goto end; } i = 0; while (i < ZCAM_WAIT_RETRY) { ret = zcam_sys_get_state(zvideo, &state); if (!ret) { break; } if (ret != -EAGAIN) { goto end; } udelay(ZCAM_WAIT_DELAY); i++; } if (i >= ZCAM_WAIT_RETRY) { zynq_err("%d vid%d %s: timeout getting camera state\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); ret = -EAGAIN; goto end; } if (state != SYS_STATE_STREAMING) { zynq_err("%d vid%d %s: unexpected camera state 0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, state); ret = -EINVAL; } end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } int zcam_flash_get_lock(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } ret = zcam_command(zvideo, CMD_FLASH_GET_LOCK); end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } int zcam_flash_lock_status(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } ret = zcam_command(zvideo, CMD_FLASH_LOCK_STATUS); end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } int zcam_flash_release_lock(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } ret = zcam_command(zvideo, CMD_FLASH_RELEASE_LOCK); end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } static int zcam_flash_status(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; int i; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); /* Check the flash status */ i = 0; while (i < ZCAM_WAIT_RETRY) { ret = zcam_command(zvideo, CMD_FLASH_STATUS); if (ret != -EBUSY) { return ret; } udelay(ZCAM_WAIT_DELAY); i++; } zynq_err("%d vid%d %s: TIMEOUT checking flash status\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); return -EBUSY; } int zcam_flash_query_device(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; unsigned char params[8] = { 0 }; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } /* Issue the query device command */ if ((ret = zcam_command(zvideo, CMD_FLASH_QUERY_DEVICE))) { goto end; } /* Check the flash status (ignore the response) */ (void) zcam_flash_status(zvideo); /* Read response */ (void) zcam_params_read(zvideo, 0, params, 8); end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } int zcam_flash_config_device(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } /* Write parameters */ if ((ret = zcam_params_write(zvideo, 0, zvideo->dev_cfg, 8))) { goto end; } /* Issue the config device command */ if ((ret = zcam_command(zvideo, CMD_FLASH_CONFIG_DEVICE))) { goto end; } end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } int zcam_flash_read(zynq_video_t *zvideo, unsigned int address, unsigned char *data, unsigned int size) { zynq_dev_t *zdev = zvideo->zdev; unsigned char params[5]; int len; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } while (size > 0) { len = (size > FLASH_READ_LIMIT) ? FLASH_READ_LIMIT : size; size -= len; /* Write address and length parameter */ params[0] = (address >> 24) & 0xFF; params[1] = (address >> 16) & 0xFF; params[2] = (address >> 8) & 0xFF; params[3] = address & 0xFF; params[4] = len; if ((ret = zcam_params_write(zvideo, 0, params, 5))) { goto end; } /* Issue the read command */ if ((ret = zcam_command(zvideo, CMD_FLASH_READ))) { goto end; } /* Check the flash status */ if ((ret = zcam_flash_status(zvideo))) { goto end; } /* Read data */ if ((ret = zcam_params_read(zvideo, 0, data, len))) { goto end; } address += len; data += len; } end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; } int zcam_flash_write(zynq_video_t *zvideo, unsigned int address, unsigned char *data, unsigned int size) { zynq_dev_t *zdev = zvideo->zdev; unsigned char params[5]; int off; int len; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); spin_lock(&zdev->zdev_lock); if ((ret = zcam_i2c_init(zvideo))) { goto end; } while (size > 0) { len = (size > FLASH_WRITE_LIMIT) ? FLASH_WRITE_LIMIT : size; /* The write should not span a page boundary */ off = address % FLASH_PAGE_SIZE; if ((off + len) > FLASH_PAGE_SIZE) { len = FLASH_PAGE_SIZE - off; } size -= len; /* Write address and length parameter */ params[0] = (address >> 24) & 0xFF; params[1] = (address >> 16) & 0xFF; params[2] = (address >> 8) & 0xFF; params[3] = address & 0xFF; params[4] = len; if ((ret = zcam_params_write(zvideo, 0, params, 5))) { goto end; } /* Write data */ if ((ret = zcam_params_write(zvideo, 5, data, len))) { goto end; } /* Issue the write command */ if ((ret = zcam_command(zvideo, CMD_FLASH_WRITE))) { goto end; } /* Check the flash status */ if ((ret = zcam_flash_status(zvideo))) { goto end; } address += len; data += len; } end: zcam_i2c_fini(zvideo); spin_unlock(&zdev->zdev_lock); return ret; }
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_trigger.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/module.h> #include <linux/kobject.h> #include "basa.h" static int zynq_trigger_enable_all(zynq_dev_t *zdev, unsigned long arg, int internal, int one) { zynq_trigger_t trigger[1]; zynq_video_t *zvideo; unsigned int val; int i; if (arg) { if (copy_from_user(trigger, (void __user *)arg, sizeof(zynq_trigger_t))) { return -EFAULT; } /* overwrite the internal parameter */ internal = trigger->internal; } spin_lock(&zdev->zdev_lock); /* 1. disable the global trigger */ val = zynq_g_reg_read(zdev, ZYNQ_G_CONFIG); val &= ~ZYNQ_CONFIG_TRIGGER_MASK; zynq_g_reg_write(zdev, ZYNQ_G_CONFIG, val); /* 2. set FPS and enable the individual triggers */ if (arg) { if ((trigger->fps == 0) || (trigger->fps > ZYNQ_FPD_FPS_MAX)) { trigger->fps = ZYNQ_FPD_FPS_DEFAULT; } } else { trigger->fps = ZYNQ_FPD_FPS_DEFAULT; } for (i = 0; i < zdev->zdev_video_cnt; i++) { zvideo = &zdev->zdev_videos[i]; if (!zvideo->caps.link_up) { continue; } /* Set FPS */ val = zvideo_reg_read(zvideo, ZYNQ_CAM_TRIGGER); val = SET_BITS(ZYNQ_CAM_TRIG_FPS, val, trigger->fps); zvideo_reg_write(zvideo, ZYNQ_CAM_TRIGGER, val); /* Enable individual trigger */ val = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); val |= ZYNQ_CAM_EN; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, val); zvideo->fps = trigger->fps; zvideo->frame_interval = USEC_PER_SEC / trigger->fps; zvideo->frame_usec_max = zvideo->frame_interval * zvideo->fps; } /* 3. enable the global trigger */ val = zynq_g_reg_read(zdev, ZYNQ_G_CONFIG); val &= ~ZYNQ_CONFIG_TRIGGER_MASK; if (one) { val |= ZYNQ_CONFIG_TRIGGER_ONE; } else { val |= ZYNQ_CONFIG_TRIGGER; } if (internal) { val |= ZYNQ_CONFIG_GPS_SW; } zynq_g_reg_write(zdev, ZYNQ_G_CONFIG, val); spin_unlock(&zdev->zdev_lock); zynq_log("%d: enable all triggers done. internal=%u\n", zdev->zdev_inst, internal); return 0; } static int zynq_trigger_disable_all(zynq_dev_t *zdev) { zynq_video_t *zvideo; unsigned int val; int i; /* 1. disable the global trigger */ spin_lock(&zdev->zdev_lock); val = zynq_g_reg_read(zdev, ZYNQ_G_CONFIG); val &= ~ZYNQ_CONFIG_TRIGGER_MASK; zynq_g_reg_write(zdev, ZYNQ_G_CONFIG, val); /* 2. disable the individual triggers */ for (i = 0; i < zdev->zdev_video_cnt; i++) { zvideo = &zdev->zdev_videos[i]; if (!zvideo->caps.link_up) { continue; } val = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); val &= ~ZYNQ_CAM_EN; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, val); zvideo->fps = 0; zvideo->frame_interval = 0; zvideo->frame_usec_max = 0; } spin_unlock(&zdev->zdev_lock); return 0; } static int zynq_trigger_status_fpd(zynq_dev_t *zdev, unsigned long arg) { zynq_trigger_t triggers[ZYNQ_FPD_TRIG_NUM] = {{ 0 }}; zynq_trigger_t *t; zynq_video_t *zvideo; unsigned int val; unsigned char enabled; unsigned char internal; int i; spin_lock(&zdev->zdev_lock); /* 1. check the global trigger status */ val = zynq_g_reg_read(zdev, ZYNQ_G_CONFIG); enabled = (val & ZYNQ_CONFIG_TRIGGER) ? 1 : 0; internal = (val & ZYNQ_CONFIG_GPS_SW) ? 1 : 0; /* 2. check individual triggers status */ for (i = 0; i < zdev->zdev_video_cnt; i++) { zvideo = &zdev->zdev_videos[i]; t = &triggers[i]; if (!zvideo->caps.link_up) { t->vnum = -1; continue; } if (zdev->zdev_video_port_map) { /* Use the video port number as the id */ t->id = zdev->zdev_video_port_map[i]; } val = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); t->enabled = (enabled && (val & ZYNQ_CAM_EN)) ? 1 : 0; t->internal = (internal && t->enabled) ? 1 : 0; if (t->enabled) { val = zvideo_reg_read(zvideo, ZYNQ_CAM_TRIGGER); t->fps = GET_BITS(ZYNQ_CAM_TRIG_FPS, val); } strncpy(t->name, zvideo->caps.name, ZYNQ_VDEV_NAME_LEN); t->name[ZYNQ_VDEV_NAME_LEN - 1] = '\0'; t->vnum = zvideo->vdev.num; } spin_unlock(&zdev->zdev_lock); if (copy_to_user((void __user *)arg, triggers, sizeof(zynq_trigger_t) * zdev->zdev_video_cnt)) { return -EFAULT; } if (zynq_trace_param & ZYNQ_TRACE_PROBE) { for (i = 0; i < zdev->zdev_video_cnt; i++) { t = &triggers[i]; zynq_log("[id=%u, fps=%u, internal=%u, " "enabled=%u, vnum=%d, name=%s]\n", t->id, t->fps, t->internal, t->enabled, t->vnum, t->name); } } return 0; } /* * Trigger support ioctls */ #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) static int zynq_trigger_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg) #else static long zynq_trigger_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) #endif { zynq_dev_t *zdev = filp->private_data; int err = 0, status; switch (cmd) { case ZYNQ_IOC_TRIGGER_DEV_NAME: zynq_trace(ZYNQ_TRACE_PROBE, "%d: ZYNQ_IOC_TRIGGER_DEV_NAME\n", zdev->zdev_inst); if (copy_to_user((void __user *)arg, zdev->zdev_name, ZYNQ_DEV_NAME_LEN)) { err = -EFAULT; break; } break; case ZYNQ_IOC_TRIGGER_DISABLE: zynq_trace(ZYNQ_TRACE_PROBE, "%d: ZYNQ_IOC_TRIGGER_DISABLE\n", zdev->zdev_inst); err = zynq_trigger_disable_all(zdev); break; case ZYNQ_IOC_TRIGGER_ENABLE: zynq_trace(ZYNQ_TRACE_PROBE, "%d: ZYNQ_IOC_TRIGGER_ENABLE\n", zdev->zdev_inst); err = zynq_trigger_enable_all(zdev, arg, 0, 0); break; case ZYNQ_IOC_TRIGGER_STATUS: zynq_trace(ZYNQ_TRACE_PROBE, "%d: ZYNQ_IOC_TRIGGER_STATUS\n", zdev->zdev_inst); err = zynq_trigger_status_fpd(zdev, arg); break; case ZYNQ_IOC_TRIGGER_STATUS_GPS: zynq_trace(ZYNQ_TRACE_PROBE, "%d: ZYNQ_IOC_TRIGGER_STATUS_GPS\n", zdev->zdev_inst); spin_lock(&zdev->zdev_lock); status = zynq_g_reg_read(zdev, ZYNQ_G_STATUS); status = (status & ZYNQ_STATUS_GPS_LOCKED) ? 1 : 0; spin_unlock(&zdev->zdev_lock); if (copy_to_user((void __user *)arg, &status, sizeof(status))) { err = -EFAULT; break; } break; case ZYNQ_IOC_TRIGGER_STATUS_PPS: zynq_trace(ZYNQ_TRACE_PROBE, "%d: ZYNQ_IOC_TRIGGER_STATUS_PPS\n", zdev->zdev_inst); spin_lock(&zdev->zdev_lock); status = zynq_g_reg_read(zdev, ZYNQ_G_STATUS); status = (status & ZYNQ_STATUS_PPS_LOCKED) ? 1 : 0; spin_unlock(&zdev->zdev_lock); if (copy_to_user((void __user *)arg, &status, sizeof(status))) { err = -EFAULT; break; } break; default: zynq_err("%d %s: unknown ioctl command\n", zdev->zdev_inst, __FUNCTION__); err = -EINVAL; break; } return err; } static int zynq_trigger_open(struct inode *inode, struct file *filp) { zynq_dev_t *zdev; zdev = container_of(inode->i_cdev, zynq_dev_t, zdev_cdev_trigger); filp->private_data = zdev; zdev->zdev_version = zynq_g_reg_read(zdev, ZYNQ_G_VERSION); zynq_trace(ZYNQ_TRACE_PROBE, "%d %s done.\n", zdev->zdev_inst, __FUNCTION__); return 0; } static int zynq_trigger_release(struct inode *inode, struct file *filp) { return 0; } struct file_operations zynq_trigger_fops = { .owner = THIS_MODULE, #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,35) .ioctl = zynq_trigger_ioctl, #else .unlocked_ioctl = zynq_trigger_ioctl, #endif .open = zynq_trigger_open, .release = zynq_trigger_release };
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_video.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/module.h> #include <linux/delay.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-event.h> #include <media/videobuf2-vmalloc.h> #include "basa.h" /* Video configurations */ static unsigned int zynq_video_err_tolerant = 0; static unsigned int zynq_video_err_thresh = 4; static unsigned int zynq_video_format = 0; int zynq_video_pin_swap = -1; int zynq_video_flash_16 = -1; unsigned int zynq_video_ts_type = CAM_CAP_TIMESTAMP_FORMATION; unsigned int zynq_video_buf_num = ZVIDEO_VBUF_MIN_NUM; unsigned int zynq_video_zero_copy = 1; struct v4l2_pix_format zvideo_formats[2] = { { .width = ZVIDEO_WIDTH, .height = ZVIDEO_HEIGHT, .pixelformat = V4L2_PIX_FMT_YUYV, .field = V4L2_FIELD_NONE, .bytesperline = ZVIDEO_BYTES_PER_LINE(YUV), .sizeimage = ZVIDEO_BYTES(YUV), .colorspace = V4L2_COLORSPACE_JPEG, .priv = 0 }, { .width = ZVIDEO_WIDTH, .height = ZVIDEO_HEIGHT, .pixelformat = V4L2_PIX_FMT_RGB24, .field = V4L2_FIELD_NONE, .bytesperline = ZVIDEO_BYTES_PER_LINE(RGB), .sizeimage = ZVIDEO_BYTES(RGB), .colorspace = V4L2_COLORSPACE_SRGB, .priv = 0 } }; static const char zvideo_stats_label[VIDEO_STATS_NUM][ZYNQ_STATS_LABEL_LEN] = { "Frames received", "Reset count", "Trigger pulse error", "Link change", "DMA Rx buffer full", "DMA Rx FIFO full", "Trigger count mismatch", "Metadata count mismatch", "Frame gap error", "Frame format error", "Frame too short", "Frame too long", "Frame corrupted", "Frame drop total", "Frame drop 1", "Frame drop 2", "Frame drop 3+", "No video buffer" }; static const char ts_label_host[] = "HOST"; static const char ts_label_formation[] = "EXP"; static const char ts_label_trigger[] = "TRIG"; static const char ts_label_fpga[] = "FPGA"; static void zvideo_set_format(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; unsigned int val; zvideo->format = zvideo_formats[zynq_video_format]; zvideo->meta_header_lines = ZVIDEO_EM_DATA_LINES; zvideo->meta_footer_lines = ZVIDEO_EM_STATS_LINES; if (zvideo->caps.embedded_data != 1) { zvideo->meta_header_lines = 0; zvideo->meta_footer_lines = 0; zvideo->format.width = ZVIDEO_IMAGE_WIDTH; zvideo->format.height = ZVIDEO_IMAGE_HEIGHT; zvideo->format.sizeimage = zvideo->format.bytesperline * zvideo->format.height + ZVIDEO_EXT_META_DATA_BYTES; } else { spin_lock(&zdev->zdev_lock); val = zynq_g_reg_read(zdev, ZYNQ_G_CAM_TRIG_CFG); val &= ~(ZYNQ_G_CAM_FPS_DRIFT_MASK << ZYNQ_G_CAM_FPS_DRIFT_OFFSET); val &= ~(ZYNQ_G_CAM_DELAY_UPDATE_MASK << ZYNQ_G_CAM_DELAY_UPDATE_OFFSET); val = SET_BITS(ZYNQ_G_CAM_FPS_DRIFT, val, 2) | SET_BITS(ZYNQ_G_CAM_DELAY_UPDATE, val, 10); zynq_g_reg_write(zdev, ZYNQ_G_CAM_TRIG_CFG, val); spin_unlock(&zdev->zdev_lock); } } static inline zynq_video_buffer_t *vb_to_zvb(struct vb2_buffer *vb) { return container_of(to_vb2_v4l2_buffer(vb), zynq_video_buffer_t, vbuf); } static inline unsigned char *zvideo_buffer_vaddr(zynq_video_buffer_t *buf) { return buf->addr; } static inline unsigned long zvideo_buffer_size(zynq_video_buffer_t *buf) { return buf->size; } static void zvideo_config(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; u32 cam_cfg; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: zvideo=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo); cam_cfg = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); cam_cfg = SET_BITS(ZYNQ_CAM_HEADER, cam_cfg, zvideo->meta_header_lines); cam_cfg = SET_BITS(ZYNQ_CAM_FOOTER, cam_cfg, zvideo->meta_footer_lines); if (zvideo->format.pixelformat == V4L2_PIX_FMT_RGB24) { cam_cfg |= ZYNQ_CAM_RGB_YUV_SEL; } else { cam_cfg &= ~ZYNQ_CAM_RGB_YUV_SEL; } cam_cfg |= ZYNQ_CAM_TIMESTAMP_RCV; cam_cfg |= ZYNQ_CAM_COLOR_SWAP; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, cam_cfg); } void zvideo_enable(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; u32 cam_cfg; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: zvideo=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo); /* Enable the trigger */ cam_cfg = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); cam_cfg |= ZYNQ_CAM_EN; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, cam_cfg); } void zvideo_disable(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; u32 cam_cfg; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: zvideo=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo); /* Disable the trigger */ cam_cfg = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); cam_cfg &= ~ZYNQ_CAM_EN; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, cam_cfg); } static void zvideo_cam_reset(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; u32 cam_cfg; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: zvideo=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo); cam_cfg = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); cam_cfg |= ZYNQ_CAM_SENSOR_RESET; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, cam_cfg); mdelay(1); cam_cfg &= ~ZYNQ_CAM_SENSOR_RESET; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, cam_cfg); zvideo->last_meta_cnt = UINT_MAX; } static void zvideo_reset(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; int retry = 0; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: zvideo=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo); spin_lock_bh(&zvideo->rlock); spin_lock_bh(&zvideo->qlock); if (zvideo->state & ZVIDEO_STATE_STREAMING) { /* Disable trigger */ zvideo_disable(zvideo); if (zynq_video_zero_copy) { while (zvideo->buf_avail != zvideo->buf_total) { if (retry >= 5) { /* Give up and re-enable the trigger */ zynq_err("%d vid%d %s: Reset aborted\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); zvideo_enable(zvideo); } spin_unlock_bh(&zvideo->qlock); spin_unlock_bh(&zvideo->rlock); if (retry >= 5) { return; } msleep(10); retry++; spin_lock_bh(&zvideo->rlock); spin_lock_bh(&zvideo->qlock); } } } ZYNQ_STATS_LOGX(zvideo, VIDEO_STATS_RESET, 1, 0); zvideo->state &= ~ZVIDEO_STATE_CHAN_FAULT; if (zvideo->state & ZVIDEO_STATE_CAM_FAULT) { /* Reset the camera sensor */ zvideo_cam_reset(zvideo); zvideo->state &= ~ZVIDEO_STATE_CAM_FAULT; } if (zvideo->state & ZVIDEO_STATE_STREAMING) { /* Reset and start the DMA channel */ zchan_rx_start(zvideo->zchan); /* Re-config the video channel */ zvideo_config(zvideo); /* Re-enable the trigger */ zvideo_enable(zvideo); } spin_unlock_bh(&zvideo->qlock); spin_unlock_bh(&zvideo->rlock); } /* * Reset the extended meta data received in the DMA buffer */ static void zvideo_reset_meta_data(zynq_video_t *zvideo, u32 rx_off) { zynq_dev_t *zdev = zvideo->zdev; zynq_chan_t *zchan = zvideo->zchan; zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; zynq_video_ext_meta_data_t *ext; u32 rx_off1, rx_off2; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: zvideo=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo); rx_off2 = rx_off + zvideo->format.sizeimage - 1; if (rx_off2 >= zchan_rx->zchan_rx_size) { rx_off2 -= zchan_rx->zchan_rx_size; } rx_off1 = rx_off + zvideo->format.sizeimage - sizeof(zynq_video_ext_meta_data_t); if (rx_off1 >= zchan_rx->zchan_rx_size) { rx_off1 -= zchan_rx->zchan_rx_size; } ASSERT(ZCHAN_WITHIN_RX_BUF(zchan_rx, rx_off1, rx_off2)); zchan_rx_off2addr(zchan_rx, rx_off1, (void **)&ext, NULL); ext->error = ZVIDEO_EXT_ERR_INVALID; } inline static long tv_diff(struct timeval *tv1, struct timeval *tv2) { return (tv2->tv_sec - tv1->tv_sec) * USEC_PER_SEC + tv2->tv_usec - tv1->tv_usec; } inline static unsigned long div_round(unsigned long val, unsigned long round) { unsigned long result; result = val / round; if ((val - (result * round)) > ((result + 1) * round - val)) { result++; } return result; } inline static void tv_sub(struct timeval *tv, unsigned int usec) { if (tv->tv_usec < usec) { tv->tv_sec--; tv->tv_usec += USEC_PER_SEC; } tv->tv_usec -= usec; } inline static void tv_add(struct timeval *tv, unsigned int usec) { tv->tv_usec += usec; if (tv->tv_usec >= USEC_PER_SEC) { tv->tv_sec++; tv->tv_usec -= USEC_PER_SEC; } } inline static void fpga_to_trigger(zynq_video_t *zvideo, zynq_video_ext_meta_data_t *ext, struct timeval *tv) { unsigned int trigger_delay = zvideo->last_trig_delay; tv->tv_sec = ext->time_stamp.sec; tv->tv_usec = ext->time_stamp.usec; tv_sub(tv, zvideo->t_first + trigger_delay); tv->tv_usec -= tv->tv_usec % zvideo->frame_interval; if (tv->tv_usec >= (zvideo->frame_usec_max - 100)) { tv->tv_sec++; tv->tv_usec = 0; } tv_add(tv, trigger_delay); } inline static void fpga_to_formation(zynq_video_t *zvideo, zynq_video_ext_meta_data_t *ext, struct timeval *tv) { fpga_to_trigger(zvideo, ext, tv); tv_add(tv, zvideo->t_middle - (zvideo->last_exp_time / 2)); } inline static void host_to_trigger(zynq_video_t *zvideo, struct timeval *tv) { unsigned int trigger_delay = zvideo->last_trig_delay; tv->tv_sec = zvideo->tv_intr.tv_sec; tv->tv_usec = zvideo->tv_intr.tv_usec; tv_sub(tv, zvideo->t_last + trigger_delay); tv->tv_usec -= tv->tv_usec % zvideo->frame_interval; if (tv->tv_usec >= (zvideo->frame_usec_max - 100)) { tv->tv_sec++; tv->tv_usec = 0; } tv_add(tv, trigger_delay); } inline static void host_to_formation(zynq_video_t *zvideo, struct timeval *tv) { host_to_trigger(zvideo, tv); tv_add(tv, zvideo->t_middle - (zvideo->last_exp_time / 2)); } /* * Check the meta data saved in the v4l2 buffer */ static int zvideo_check_meta_data(zynq_video_t *zvideo, zynq_video_buffer_t *buf) { zynq_dev_t *zdev = zvideo->zdev; zynq_video_ext_meta_data_t *ext; struct timeval *tv; #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 5, 0) struct timeval curTv={0, 0}; u64 *timeval_in_ns; #endif const char *label; unsigned char *mem; unsigned long memsz; unsigned int trig_cnt; unsigned int last_cnt; int meta_cnt_gap = -1; int trig_cnt_gap = -1; long cnt_gap = -1; long drop_cnt; long ts_gap; int corrupted; int ret = 0; mem = zvideo_buffer_vaddr(buf); memsz = zvideo_buffer_size(buf); /* Check camera embedded header metadata */ if (zvideo->caps.embedded_data == 1) { if (EM_DATA_VALID(mem)) { last_cnt = zvideo->last_meta_cnt; zvideo->read_em_data(zvideo, mem); if (last_cnt != UINT_MAX) { /* The first frame is ignored */ meta_cnt_gap = zvideo->last_meta_cnt - last_cnt; if (meta_cnt_gap == 0) { zynq_err("%d vid%d %s: WARNING! " "metadata frame count error, " "sequence %u, current %u, last %u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->sequence, zvideo->last_meta_cnt, last_cnt); } } } else { zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: invalid header metadata\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); } } /* Check extended metadata */ ext = (zynq_video_ext_meta_data_t *) (mem + memsz - sizeof(zynq_video_ext_meta_data_t)); trig_cnt = ext->trigger_cnt; corrupted = ZVIDEO_FRAME_CORRUPTED(ext); if (corrupted) { /* * When the frame is corrupted, the trigger count in * the extended metadata is not reliable. We assume * the valid count should be increment by 1. */ trig_cnt = zvideo->last_trig_cnt + 1; ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_FRAME_CORRUPT); zvideo->frame_err_cnt++; if (!zynq_video_err_tolerant) { ret = -1; } } else if (ext->error) { if ((ext->error & ZVIDEO_EXT_ERR_FRAME_FORMAT)) { ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_FRAME_FORMAT_ERR); } if ((ext->error & ZVIDEO_EXT_ERR_SHORT_FRAME)) { ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_FRAME_SHORT); } if ((ext->error & ZVIDEO_EXT_ERR_LONG_FRAME)) { ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_FRAME_LONG); } zvideo->frame_err_cnt++; if (!zynq_video_err_tolerant) { ret = -1; } } else { zvideo->frame_err_cnt = 0; } if (zvideo->frame_err_cnt >= zynq_video_err_thresh) { zynq_err("%d vid%d %s: Reset needed, err_cnt=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->frame_err_cnt); zvideo->frame_err_cnt = 0; spin_lock(&zvideo->qlock); zvideo->state |= ZVIDEO_STATE_CHAN_FAULT; spin_unlock(&zvideo->qlock); zchan_watchdog_complete(zvideo->zchan); } if (zvideo->last_trig_cnt != 0) { /* The first frame is ignored because it always has errors */ trig_cnt_gap = trig_cnt - zvideo->last_trig_cnt; if (trig_cnt_gap == 0) { zynq_err("%d vid%d %s: WARNING! trigger count error, " "sequence %u, current %u, last %u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->sequence, trig_cnt, zvideo->last_trig_cnt); } } zvideo->last_trig_cnt = trig_cnt; #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 5, 0) tv = &buf->vbuf.timestamp; #else // To keep the original logic, all the following logic manipulates tv. // convert it to timeval_in_ns at the end. tv = &curTv; timeval_in_ns = &buf->vbuf.vb2_buf.timestamp; #endif switch (zynq_video_ts_type) { default: case CAM_CAP_TIMESTAMP_FPGA: fpga_time: if (corrupted) { tv->tv_sec = 0; tv->tv_usec = 0; } else { tv->tv_sec = ext->time_stamp.sec; tv->tv_usec = ext->time_stamp.usec; } label = ts_label_fpga; break; case CAM_CAP_TIMESTAMP_TRIGGER: if (corrupted) { host_to_trigger(zvideo, tv); } else { fpga_to_trigger(zvideo, ext, tv); } label = ts_label_trigger; break; case CAM_CAP_TIMESTAMP_FORMATION: if (zvideo->last_exp_time == 0) { goto fpga_time; } if (corrupted) { host_to_formation(zvideo, tv); } else { fpga_to_formation(zvideo, ext, tv); } label = ts_label_formation; break; case CAM_CAP_TIMESTAMP_HOST: tv->tv_sec = zvideo->tv_intr.tv_sec; tv->tv_usec = zvideo->tv_intr.tv_usec; label = ts_label_host; break; } #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 5, 0) *timeval_in_ns = tv->tv_sec * 1000000000 + tv->tv_usec * 1000; #endif buf->vbuf.sequence = zvideo->sequence; /* * Check possible frame drop. * * We have 3 different ways to calculate the frame count gap: * 1. Use host receive time * The problem of this method is that the host time could * jump when GPS signal is not stable. * 2. Use the frame count in the header metadata * The problem of this method is that the header metadata * may not be available. * 3. Use the trigger count in the extended metadata * The problem of this method is that the trigger count * is not reliable because it could be corrupted. * The precedence we take is: 2 > 1, and 3 is only for reference. */ if (zvideo->last_tv_intr.tv_sec == 0) { ts_gap = zvideo->frame_interval; } else { ts_gap = tv_diff(&zvideo->last_tv_intr, &zvideo->tv_intr); } if ((ts_gap < 0) || (ts_gap > (USEC_PER_SEC << 3))) { zynq_err("%d vid%d %s: WARNING! possible system time change. " "frame sequence %u, host ts %lu.%06lu, last %lu.%06lu\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->sequence, zvideo->tv_intr.tv_sec, zvideo->tv_intr.tv_usec, zvideo->last_tv_intr.tv_sec, zvideo->last_tv_intr.tv_usec); ZYNQ_STATS(zvideo, VIDEO_STATS_FRAME_GAP_ERR); } else if (zvideo->frame_interval != 0) { cnt_gap = div_round(ts_gap, zvideo->frame_interval); if (cnt_gap == 0) { /* Interval too short */ ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_FRAME_GAP_ERR); } } else { zynq_err("%d vid%d %s: WARNING! driver not ready. " "frame sequence %u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->sequence); } if (meta_cnt_gap > 0) { /* * When the frame count in the header metadata is * available, we always trust this frame count. */ if ((cnt_gap > 0) && (cnt_gap != meta_cnt_gap)) { ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_META_COUNT_MISMATCH); } cnt_gap = meta_cnt_gap; } if (trig_cnt_gap > 0) { if ((cnt_gap > 0) && (cnt_gap != trig_cnt_gap)) { ZYNQ_STATS(zvideo, VIDEO_STATS_TRIG_COUNT_MISMATCH); } } if (cnt_gap > 1) { /* Possible frame drop */ drop_cnt = cnt_gap - 1; ZYNQ_STATS_LOGX(zvideo, VIDEO_STATS_FRAME_DROP, drop_cnt, 0); if (drop_cnt == 1) { ZYNQ_STATS(zvideo, VIDEO_STATS_FRAME_DROP_1); } else if (drop_cnt == 2) { ZYNQ_STATS(zvideo, VIDEO_STATS_FRAME_DROP_2); } else { ZYNQ_STATS(zvideo, VIDEO_STATS_FRAME_DROP_M); } } ZYNQ_STATS(zvideo, VIDEO_STATS_FRAME); zvideo->last_tv_intr = zvideo->tv_intr; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: sequence=%u, trigger_cnt=%u, " "ts[%s]=%ld.%06ld, host_ts=%ld.%06ld, " "meta_ts=%u.%06u, debug_ts=%u.%06u, " "error=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->sequence, ext->trigger_cnt, label, tv->tv_sec, tv->tv_usec, zvideo->tv_intr.tv_sec, zvideo->tv_intr.tv_usec, ext->time_stamp.sec, ext->time_stamp.usec, ext->debug_ts.sec, ext->debug_ts.us_cnt << 8, ext->error); return ret; } /* * Check the pending list. If there is a pending buffer that matches * the rx head pointer, move it from the pending list to the buf list, * and update the head pointer accordingly. * * This function has to be called with zvideo->qlock acquired. */ static void zvideo_check_pending(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; zynq_chan_t *zchan = zvideo->zchan; zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; zynq_video_buffer_t *buf, *next; u32 rx_head; size_t bufsz; size_t vbufsz; bufsz = zchan_rx->zchan_rx_bufsz; rx_head = zchan_rx->zchan_rx_head; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: begin rx_head=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, rx_head); again: list_for_each_entry_safe(buf, next, &zvideo->pending_list, list) { if (buf->offset != rx_head) { continue; } /* * Found a pending video buffer that matches the head, * remove it from the pending_list and add it to the * buf_list for data receiving. */ list_del(&buf->list); list_add_tail(&buf->list, &zvideo->buf_list); zvideo->buf_avail++; /* * Before allowing the buffer to be filled with new * video frame data, reset the meta data. */ zvideo_reset_meta_data(zvideo, buf->offset); /* Update the head pointer */ vbufsz = ALIGN(zvideo_buffer_size(buf), bufsz); ASSERT(vbufsz == ALIGN(zvideo->format.sizeimage, bufsz)); rx_head += vbufsz; if (rx_head >= zchan_rx->zchan_rx_size) { rx_head -= zchan_rx->zchan_rx_size; } zchan_rx->zchan_rx_head = rx_head; zchan_reg_write(zchan, ZYNQ_CH_RX_HEAD, rx_head); zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: update rx_head=0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, rx_head); goto again; } } static int zvideo_map_buf(struct pci_dev *pdev, zchan_buf_t *zchan_buf, void *vaddr, size_t bufsz, enum dma_data_direction dmatype) { struct page *page; dma_addr_t paddr; if (!is_vmalloc_addr(vaddr)) { zynq_err("%s: vaddr 0x%p is not a vmalloc addr\n", __FUNCTION__, vaddr); return -1; } page = vmalloc_to_page(vaddr); paddr = pci_map_page(pdev, page, 0, bufsz, dmatype); if (pci_dma_mapping_error(pdev, paddr)) { zynq_err("%s: pci_map_page failed, va=0x%p, pa=0x%llx\n", __FUNCTION__, vaddr, paddr); return -1; } if (paddr & (bufsz - 1)) { zynq_err("%s dma addr 0x%llx is not bufsz %zd aligned.\n", __FUNCTION__, paddr, bufsz); pci_unmap_page(pdev, paddr, bufsz, dmatype); return -1; } zynq_trace(ZYNQ_TRACE_BUF, "%s done, va=0x%p, pa=0x%llx\n", __FUNCTION__, vaddr, paddr); zchan_buf->zchan_bufp = vaddr; zchan_buf->zchan_buf_page = page; zchan_buf->zchan_buf_dma = paddr; return 0; } static void zvideo_unmap_buf(struct pci_dev *pdev, zchan_buf_t *zchan_buf, size_t bufsz, enum dma_data_direction dmatype) { pci_unmap_page(pdev, zchan_buf->zchan_buf_dma, bufsz, dmatype); zchan_buf->zchan_bufp = NULL; zchan_buf->zchan_buf_page = NULL; zchan_buf->zchan_buf_dma = 0; } static void zvideo_fini_rx(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; zynq_chan_t *zchan = zvideo->zchan; zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; struct pci_dev *pdev = zchan->zdev->zdev_pdev; zchan_rx_pt_t *rx_ptp; /* page table array */ zchan_buf_t *bufp; size_t bufsz; int i, j; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: zvideo=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo); rx_ptp = zchan_rx->zchan_rx_ptp; bufsz = zchan_rx->zchan_rx_bufsz; for (i = 0; i < zchan_rx->zchan_rx_pdt_num; i++, rx_ptp++) { if (!rx_ptp->zchan_rx_pt) { continue; } bufp = rx_ptp->zchan_rx_pt_bufp; ASSERT(bufp); /* Unmap the DMA buffers */ for (j = 0; j < rx_ptp->zchan_rx_pt_buf_num; j++, bufp++) { if (bufp->zchan_buf_dma) { zvideo_unmap_buf(pdev, bufp, bufsz, PCI_DMA_FROMDEVICE); } } /* Free the array of zchan_buf_t */ kfree(rx_ptp->zchan_rx_pt_bufp); /* Free the page table */ zchan_free_consistent(pdev, rx_ptp->zchan_rx_pt, rx_ptp->zchan_rx_pt_dma, ZCHAN_RX_PT_SIZE); } /* Free the array of zchan_rx_pt_t */ kfree(zchan_rx->zchan_rx_ptp); zchan_rx->zchan_rx_ptp = NULL; zchan_rx->zchan_rx_pt_entries = 0; zchan_rx->zchan_rx_size = 0; zchan_rx->zchan_rx_bufsz = 0; /* Free the page directory table */ zchan_free_consistent(pdev, zchan_rx->zchan_rx_pdt, zchan_rx->zchan_rx_pdt_dma, zchan_rx->zchan_rx_pdt_num * sizeof(u64)); zchan_rx->zchan_rx_pdt = NULL; zchan_rx->zchan_rx_pdt_dma = 0; zchan_rx->zchan_rx_pdt_num = 0; } static int zvideo_init_rx(zynq_video_t *zvideo, unsigned int count) { zynq_dev_t *zdev = zvideo->zdev; zynq_chan_t *zchan = zvideo->zchan; zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; struct pci_dev *pdev = zchan->zdev->zdev_pdev; enum dma_data_direction dmatype; zynq_video_buffer_t *zbuf, *next; size_t vbufsz; unsigned char *vaddr; u32 pdt_entries; u32 pt_entries; u32 buf_num; size_t pdt_size; size_t bufsz; u64 *rx_pdtp; /* page directory table array */ zchan_rx_pt_t *rx_ptp; /* page table array */ u64 *rx_pt; /* page table */ zchan_buf_t *bufp; int i; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: zvideo=0x%p, count=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo, count); dmatype = PCI_DMA_FROMDEVICE; bufsz = ZCHAN_BUF_SIZE; pt_entries = count * CEILING(zvideo->format.sizeimage, bufsz); pdt_entries = CEILING(pt_entries, ZCHAN_RX_PT_ENTRIES); /* allocate page directory table first */ pdt_size = pdt_entries * sizeof(u64); rx_pdtp = zchan_alloc_consistent(pdev, &zchan_rx->zchan_rx_pdt_dma, pdt_size); if (rx_pdtp == NULL) { zynq_err("%d vid%d %s " "failed to alloc page directory table.\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); return -1; } zchan_rx->zchan_rx_pt_entries = pt_entries; zchan_rx->zchan_rx_pdt_num = pdt_entries; zchan_rx->zchan_rx_pdt = rx_pdtp; /* allocate the array of zchan_rx_pt_t */ rx_ptp = kzalloc(pdt_entries * sizeof(zchan_rx_pt_t), GFP_KERNEL); if (rx_ptp == NULL) { zchan_free_consistent(pdev, zchan_rx->zchan_rx_pdt, zchan_rx->zchan_rx_pdt_dma, pdt_size); zynq_err("%d vid%d, %s failed to alloc page table array.\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); return -1; } zchan_rx->zchan_rx_ptp = rx_ptp; zchan_rx->zchan_rx_bufsz = bufsz; for (i = 0; i < zchan_rx->zchan_rx_pdt_num; i++, rx_pdtp++, rx_ptp++) { /* allocate each page table */ rx_pt = zchan_alloc_consistent(pdev, &rx_ptp->zchan_rx_pt_dma, ZCHAN_RX_PT_SIZE); if (rx_pt == NULL) { zynq_err("%d vid%d %s " "failed to alloc a page table.\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); goto init_rx_fail; } rx_ptp->zchan_rx_pt = rx_pt; /* init the page directory table entry */ *rx_pdtp = rx_ptp->zchan_rx_pt_dma; /* allocate the array of zchan_buf_t */ buf_num = MIN(pt_entries, ZCHAN_RX_PT_ENTRIES); ASSERT(buf_num > 0); bufp = kzalloc(buf_num * sizeof(zchan_buf_t), GFP_KERNEL); if (bufp == NULL) { zchan_free_consistent(pdev, rx_ptp->zchan_rx_pt, rx_ptp->zchan_rx_pt_dma, ZCHAN_RX_PT_SIZE); rx_ptp->zchan_rx_pt = NULL; rx_ptp->zchan_rx_pt_dma = 0; zynq_err("%d vid%d %s " "failed to alloc a Rx buffer array.\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); goto init_rx_fail; } rx_ptp->zchan_rx_pt_bufp = bufp; rx_ptp->zchan_rx_pt_buf_num = buf_num; pt_entries -= buf_num; } zchan_rx->zchan_rx_size = zchan_rx->zchan_rx_pt_entries * bufsz; zchan_rx->zchan_rx_pdt_shift = fls(ZCHAN_RX_PT_ENTRIES * bufsz) - 1; zchan_rx->zchan_rx_pt_shift = fls(bufsz) - 1; zchan_rx->zchan_rx_pt_mask = ZCHAN_RX_PT_ENTRIES - 1; zchan_rx->zchan_rx_buf_mask = bufsz - 1; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: rx_bufsz=%zd, " "rx_buf_mask=0x%x, rx_pdt_num=0x%x, pt_entries=0x%x, rx_size=0x%x, " "rx_pdt_shift=%d, rx_pt_shift=%d, rx_pt_mask=0x%x.\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, bufsz, zchan_rx->zchan_rx_buf_mask, zchan_rx->zchan_rx_pdt_num, zchan_rx->zchan_rx_pt_entries, zchan_rx->zchan_rx_size, zchan_rx->zchan_rx_pdt_shift, zchan_rx->zchan_rx_pt_shift, zchan_rx->zchan_rx_pt_mask); rx_ptp = zchan_rx->zchan_rx_ptp; rx_pt = rx_ptp->zchan_rx_pt; bufp = rx_ptp->zchan_rx_pt_bufp; buf_num = rx_ptp->zchan_rx_pt_buf_num; pt_entries = 0; list_for_each_entry_safe(zbuf, next, &zvideo->buf_list, list) { zbuf->offset = pt_entries << zchan_rx->zchan_rx_pt_shift; vaddr = zvideo_buffer_vaddr(zbuf); vbufsz = ALIGN(zvideo_buffer_size(zbuf), bufsz); ASSERT(vbufsz == ALIGN(zvideo->format.sizeimage, bufsz)); while (vbufsz > 0) { if (zvideo_map_buf(pdev, bufp, vaddr, bufsz, PCI_DMA_FROMDEVICE)) { goto init_rx_fail; } /* init the page table entry */ *rx_pt = bufp->zchan_buf_dma; pt_entries++; if (pt_entries & zchan_rx->zchan_rx_pt_mask) { rx_pt++; bufp++; } else { rx_ptp++; rx_pt = rx_ptp->zchan_rx_pt; bufp = rx_ptp->zchan_rx_pt_bufp; buf_num += rx_ptp->zchan_rx_pt_buf_num; } vbufsz -= bufsz; vaddr += bufsz; } } ASSERT(pt_entries == buf_num); return 0; init_rx_fail: zvideo_fini_rx(zvideo); return -1; } /* * Setup the constraints of the queue before allocating the buffers. * * The vb2 framework will check the number of allocated buffers against * the min_buffers_needed before calling this function. Here we don't * do any additional check for the buffer number. */ #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 5, 0) static int zvideo_queue_setup(struct vb2_queue *vq, const void *parg, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], void *alloc_ctxs[]) { const struct v4l2_format *fmt = parg; zynq_video_t *zvideo = vb2_get_drv_priv(vq); zynq_dev_t *zdev = zvideo->zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: vq=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, vq); if (fmt && fmt->fmt.pix.sizeimage != zvideo->format.sizeimage) { zynq_err("%d vid%d %s: requested size invalid (%u != %u)\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, fmt->fmt.pix.sizeimage, zvideo->format.sizeimage); return -EINVAL; } *nplanes = 1; sizes[0] = zvideo->format.sizeimage; return 0; } #else /* int (*queue_setup)(struct vb2_queue *q, unsigned int *num_buffers, unsigned int *num_planes, unsigned int sizes[], struct device *alloc_devs[]); */ static int zvideo_queue_setup(struct vb2_queue *vq, unsigned int *nbuffers, unsigned int *nplanes, unsigned int sizes[], struct device *alloc_ctxs[]) { zynq_video_t *zvideo = vb2_get_drv_priv(vq); zynq_dev_t *zdev = zvideo->zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: vq=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, vq); *nplanes = 1; sizes[0] = zvideo->format.sizeimage; return 0; } #endif /* * Initialize the buffer right after the allocation. */ static int zvideo_buffer_init(struct vb2_buffer *vb) { zynq_video_t *zvideo = vb2_get_drv_priv(vb->vb2_queue); zynq_dev_t *zdev = zvideo->zdev; zynq_video_buffer_t *zbuf = vb_to_zvb(vb); zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: vb=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, vb); /* * We save the vaddr and size of the buffer before the plane size * of the vb2 buffer is adjusted for meta data drop. */ zbuf->addr = vb2_plane_vaddr(vb, 0); zbuf->size = vb2_plane_size(vb, 0); return 0; } /* * Prepare the buffer for queuing to the DMA engine: check and set the * payload size. */ static int zvideo_buffer_prepare(struct vb2_buffer *vb) { zynq_video_t *zvideo = vb2_get_drv_priv(vb->vb2_queue); zynq_dev_t *zdev = zvideo->zdev; zynq_video_buffer_t *zbuf = vb_to_zvb(vb); unsigned long bufsz = zvideo_buffer_size(zbuf); unsigned long size; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: vb=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, vb); size = zvideo->format.sizeimage; if (bufsz != size) { zynq_err("%d vid%d %s: buffer size invalid (%lu != %lu)\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, bufsz, size); return -EINVAL; } vb2_set_plane_payload(vb, 0, 0); return 0; } /* * Finish the buffer for dequeuing */ static void zvideo_buffer_finish(struct vb2_buffer *vb) { zynq_video_t *zvideo = vb2_get_drv_priv(vb->vb2_queue); zynq_dev_t *zdev = zvideo->zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: vb=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, vb); } /* * Cleanup the buffer before it is freed */ static void zvideo_buffer_cleanup(struct vb2_buffer *vb) { zynq_video_t *zvideo = vb2_get_drv_priv(vb->vb2_queue); zynq_dev_t *zdev = zvideo->zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: vb=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, vb); } /* * Queue this buffer to the DMA engine. */ static void zvideo_buffer_queue(struct vb2_buffer *vb) { zynq_video_t *zvideo = vb2_get_drv_priv(vb->vb2_queue); zynq_dev_t *zdev = zvideo->zdev; zynq_video_buffer_t *buf = vb_to_zvb(vb); zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: vb=0x%p, state=%d\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, vb, vb->state); spin_lock_bh(&zvideo->qlock); if (zynq_video_zero_copy) { if (zvideo->state & ZVIDEO_STATE_STREAMING) { /* * Considering the case that the buffers may be * returned to the kernel in a changed sequence, * we add them to the pending list first and then * move them to the buf list later when the expected * sequence is matched. */ list_add(&buf->list, &zvideo->pending_list); zvideo_check_pending(zvideo); } else { list_add_tail(&buf->list, &zvideo->buf_list); zvideo->buf_avail++; } } else { list_add_tail(&buf->list, &zvideo->buf_list); zvideo->buf_avail++; } spin_unlock_bh(&zvideo->qlock); } static void zvideo_return_all_buffers(zynq_video_t *zvideo, enum vb2_buffer_state state) { zynq_video_buffer_t *buf, *node; spin_lock_bh(&zvideo->qlock); list_for_each_entry_safe(buf, node, &zvideo->pending_list, list) { vb2_buffer_done(&buf->vbuf.vb2_buf, state); list_del(&buf->list); } list_for_each_entry_safe(buf, node, &zvideo->buf_list, list) { vb2_buffer_done(&buf->vbuf.vb2_buf, state); list_del(&buf->list); zvideo->buf_avail--; } spin_unlock_bh(&zvideo->qlock); } static void zvideo_init_params(zynq_video_t *zvideo) { zvideo->sequence = 0; zvideo->frame_err_cnt = 0; zvideo->last_exp_time = 0; zvideo->last_meta_cnt = UINT_MAX; zvideo->last_trig_cnt = 0; zvideo->last_tv_intr.tv_sec = 0; zvideo->last_tv_intr.tv_usec = 0; } /* * Start streaming. First check if the minimum number of buffers have been * queued. If not, then return -ENOBUFS and the vb2 framework will call * this function again the next time a buffer has been queued until enough * buffers are available to actually start streaming. */ static int zvideo_start_streaming(struct vb2_queue *vq, unsigned int count) { zynq_video_t *zvideo = vb2_get_drv_priv(vq); zynq_dev_t *zdev = zvideo->zdev; zynq_chan_t *zchan = zvideo->zchan; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: vq=0x%p, count=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, vq, count); if (count < zynq_video_buf_num) { zynq_err("%d vid%d %s no enough buffers\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); return -ENOBUFS; } zvideo->buf_total = count; ASSERT(zvideo->buf_total == zvideo->buf_avail); zvideo_init_params(zvideo); spin_lock_bh(&zvideo->rlock); spin_lock_bh(&zvideo->qlock); if (zynq_video_zero_copy) { if (zvideo_init_rx(zvideo, count)) { spin_unlock_bh(&zvideo->qlock); spin_unlock_bh(&zvideo->rlock); return -ENOSR; } } /* Start DMA */ zchan_rx_start(zchan); /* Configure the video channel */ zvideo_config(zvideo); /* * For Non-zerocopy, we don't enable DMA here. DMA is already enabled * when the driver is initialized. The flag ZVIDEO_STATE_STREAMING is * used to sync up data receiving. */ /* Set the streaming flag */ zvideo->state |= ZVIDEO_STATE_STREAMING; spin_unlock_bh(&zvideo->qlock); spin_unlock_bh(&zvideo->rlock); return 0; } /* * Stop streaming. Any remaining buffers in the DMA queue are dequeued * and passed on to the vb2 framework marked as STATE_ERROR. */ static void zvideo_stop_streaming(struct vb2_queue *vq) { zynq_video_t *zvideo = vb2_get_drv_priv(vq); zynq_dev_t *zdev = zvideo->zdev; zynq_chan_t *zchan = zvideo->zchan; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: vq=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, vq); spin_lock_bh(&zvideo->rlock); spin_lock_bh(&zvideo->qlock); /* Clear the streaming flag */ zvideo->state &= ~ZVIDEO_STATE_STREAMING; /* Disable the trigger */ zvideo_disable(zvideo); if (zynq_video_zero_copy) { /* Stop DMA */ zchan_rx_stop(zchan); /* Unmap the DMA buffers */ zvideo_fini_rx(zvideo); } /* * For Non-zerocopy, we don't disable DMA here. DMA is always enabled. * The streaming flag is used to sync up data receiving. */ spin_unlock_bh(&zvideo->qlock); spin_unlock_bh(&zvideo->rlock); /* Release all active buffers */ zvideo_return_all_buffers(zvideo, VB2_BUF_STATE_ERROR); /* Wait until other pending buffers are returned to vb2 */ vb2_wait_for_all_buffers(vq); zvideo->buf_total = 0; ASSERT(zvideo->buf_total == zvideo->buf_avail); } /* * The vb2 queue ops. Note that since q->lock is set we can use the standard * vb2_ops_wait_prepare/finish helper functions. If q->lock would be NULL, * then this driver would have to provide these ops. */ static struct vb2_ops video_qops = { .queue_setup = zvideo_queue_setup, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, .buf_init = zvideo_buffer_init, .buf_prepare = zvideo_buffer_prepare, .buf_finish = zvideo_buffer_finish, .buf_cleanup = zvideo_buffer_cleanup, .start_streaming = zvideo_start_streaming, .stop_streaming = zvideo_stop_streaming, .buf_queue = zvideo_buffer_queue }; /* * Required ioctl querycap. Note that the version field is prefilled with * the version of the kernel. */ static int zvideo_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { zynq_video_t *zvideo = video_drvdata(file); zynq_dev_t *zdev = zvideo->zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: file=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, file); strlcpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver)); strlcpy(cap->card, zvideo->caps.name, sizeof(cap->card)); snprintf(cap->bus_info, sizeof(cap->bus_info), "PCI:%s", pci_name(zvideo->zdev->zdev_pdev)); cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING; cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS; return 0; } static int zvideo_try_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { zynq_video_t *zvideo = video_drvdata(file); zynq_dev_t *zdev = zvideo->zdev; struct v4l2_pix_format *pix = &f->fmt.pix; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: file=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, file); if (pix->pixelformat != zvideo->format.pixelformat) { return -EINVAL; } *pix = zvideo->format; return 0; } static int zvideo_s_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { zynq_video_t *zvideo = video_drvdata(file); zynq_dev_t *zdev = zvideo->zdev; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: file=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, file); ret = zvideo_try_fmt_vid_cap(file, priv, f); if (ret) { return ret; } /* * It is not allowed to change the format while buffers for use with * streaming have already been allocated. */ if (vb2_is_busy(&zvideo->queue)) { return -EBUSY; } /* We do not allow changing format for now */ return 0; } static int zvideo_g_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { zynq_video_t *zvideo = video_drvdata(file); zynq_dev_t *zdev = zvideo->zdev; struct v4l2_pix_format *pix = &f->fmt.pix; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: file=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, file); *pix = zvideo->format; return 0; } static int zvideo_enum_fmt_vid_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { zynq_video_t *zvideo = video_drvdata(file); zynq_dev_t *zdev = zvideo->zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: file=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, file); if (f->index != 0) { return -EINVAL; } f->pixelformat = zvideo->format.pixelformat; return 0; } static int zvideo_enum_input(struct file *file, void *priv, struct v4l2_input *i) { zynq_video_t *zvideo = video_drvdata(file); zynq_dev_t *zdev = zvideo->zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: file=0x%p, input->index=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, file, i->index); if (i->index > 0) { return -EINVAL; } i->type = V4L2_INPUT_TYPE_CAMERA; strlcpy(i->name, zvideo->caps.name, sizeof(i->name)); return 0; } static int zvideo_s_input(struct file *file, void *priv, unsigned int i) { zynq_video_t *zvideo = video_drvdata(file); zynq_dev_t *zdev = zvideo->zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: file=0x%p, i=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, file, i); if (i > 0) { return -EINVAL; } /* * Changing the input implies a format change, which is not allowed * while buffers for use with streaming have already been allocated. */ if (vb2_is_busy(&zvideo->queue)) { return -EBUSY; } zvideo->input = i; return 0; } static int zvideo_g_input(struct file *file, void *priv, unsigned int *i) { zynq_video_t *zvideo = video_drvdata(file); zynq_dev_t *zdev = zvideo->zdev; *i = zvideo->input; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: file=0x%p, *i=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, file, *i); return 0; } static void zvideo_trigger_enable(zynq_video_t *zvideo, zynq_trigger_t *trigger) { zynq_dev_t *zdev = zvideo->zdev; unsigned int val; if ((trigger->fps == 0) || (trigger->fps > ZYNQ_FPD_FPS_MAX)) { trigger->fps = ZYNQ_FPD_FPS_DEFAULT; } spin_lock(&zvideo->rlock); /* 1. Disable the individual trigger */ val = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); val &= ~ZYNQ_CAM_EN; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, val); /* 2. Set FPS */ val = zvideo_reg_read(zvideo, ZYNQ_CAM_TRIGGER); val = SET_BITS(ZYNQ_CAM_TRIG_FPS, val, trigger->fps); zvideo_reg_write(zvideo, ZYNQ_CAM_TRIGGER, val); /* 3. Enable the individual trigger */ val = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); val |= ZYNQ_CAM_EN; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, val); /* 4. Enable the global trigger */ spin_lock(&zdev->zdev_lock); val = zynq_g_reg_read(zdev, ZYNQ_G_CONFIG); val &= ~ZYNQ_CONFIG_TRIGGER_MASK; val |= ZYNQ_CONFIG_TRIGGER; if (trigger->internal) { val |= ZYNQ_CONFIG_GPS_SW; } zynq_g_reg_write(zdev, ZYNQ_G_CONFIG, val); spin_unlock(&zdev->zdev_lock); zvideo->fps = trigger->fps; zvideo->frame_interval = USEC_PER_SEC / trigger->fps; zvideo->frame_usec_max = zvideo->frame_interval * zvideo->fps; spin_unlock(&zvideo->rlock); zynq_log("%d vid%d %s: done. fps=%u, internal=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, trigger->fps, trigger->internal); } static void zvideo_trigger_disable(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; unsigned int val; spin_lock(&zvideo->rlock); /* Disable the individual trigger */ val = zvideo_reg_read(zvideo, ZYNQ_CAM_CONFIG); val &= ~ZYNQ_CAM_EN; zvideo_reg_write(zvideo, ZYNQ_CAM_CONFIG, val); zvideo->fps = 0; zvideo->frame_interval = 0; zvideo->frame_usec_max = 0; spin_unlock(&zvideo->rlock); zynq_log("%d vid%d %s: done.\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); } static void zvideo_trigger_delay_set(zynq_video_t *zvideo, zynq_trigger_delay_t *delay) { zynq_dev_t *zdev = zvideo->zdev; unsigned int val; spin_lock(&zvideo->rlock); val = zvideo_reg_read(zvideo, ZYNQ_CAM_TRIGGER); val = SET_BITS(ZYNQ_CAM_TRIG_DELAY, val, delay->trigger_delay); zvideo_reg_write(zvideo, ZYNQ_CAM_TRIGGER, val); spin_unlock(&zvideo->rlock); zvideo->last_trig_delay = delay->trigger_delay; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: trigger_delay=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, delay->trigger_delay); } static void zvideo_trigger_delay_get(zynq_video_t *zvideo, zynq_trigger_delay_t *delay) { zynq_dev_t *zdev = zvideo->zdev; unsigned int val; spin_lock(&zvideo->rlock); val = zvideo_reg_read(zvideo, ZYNQ_CAM_TRIGGER); val = GET_BITS(ZYNQ_CAM_TRIG_DELAY, val); spin_unlock(&zvideo->rlock); delay->trigger_delay = val; delay->exposure_time = zvideo->last_exp_time; ASSERT(zvideo->last_trig_delay == delay->trigger_delay); zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: " "trigger_delay=%u, exposure_time=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, delay->trigger_delay, delay->exposure_time); } static long zvideo_ioctl_default(struct file *file, void *fh, bool valid_prio, unsigned int cmd, void *arg) { zynq_video_t *zvideo = video_drvdata(file); zynq_dev_t *zdev = zvideo->zdev; int err = 0; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: file=0x%p\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, file); switch (cmd) { case ZYNQ_IOC_CAM_REG_READ: { zynq_cam_acc_t *cam_acc = (zynq_cam_acc_t *)arg; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_CAM_REG_READ: addr=0x%x\n", zdev->zdev_inst, zvideo->index, cam_acc->addr); err = zcam_reg_read(zvideo, cam_acc); break; } case ZYNQ_IOC_CAM_REG_WRITE: { zynq_cam_acc_t *cam_acc = (zynq_cam_acc_t *)arg; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_CAM_REG_WRITE: addr=0x%x data=0x%x\n", zdev->zdev_inst, zvideo->index, cam_acc->addr, cam_acc->data); err = zcam_reg_write(zvideo, cam_acc); break; } case ZYNQ_IOC_CAM_FLASH_INIT: { int config_device = *(int *)arg; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_CAM_FLASH_INIT, config_device=%d\n", zdev->zdev_inst, zvideo->index, config_device); /* Safety patch 15 */ if (config_device) { if ((err = zcam_set_suspend(zvideo))) { break; } } if ((err = zcam_flash_get_lock(zvideo))) { break; } if ((err = zcam_flash_lock_status(zvideo))) { break; } if (!config_device) { break; } if ((err = zcam_flash_query_device(zvideo))) { (void) zcam_flash_release_lock(zvideo); break; } if ((err = zcam_flash_config_device(zvideo))) { (void) zcam_flash_release_lock(zvideo); break; } break; } case ZYNQ_IOC_CAM_FLASH_FINI: zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_CAM_FLASH_FINI\n", zdev->zdev_inst, zvideo->index); err = zcam_flash_release_lock(zvideo); break; case ZYNQ_IOC_CAM_FLASH_READ: { zynq_cam_fw_t *cam_fw = (zynq_cam_fw_t *)arg; unsigned char data[ZYNQ_CAM_FW_BLOCK_SIZE_MAX]; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d " "ZYNQ_IOC_CAM_FLASH_READ: address=0x%x, size=%d\n", zdev->zdev_inst, zvideo->index, cam_fw->address, cam_fw->size); if ((cam_fw->size > ZYNQ_CAM_FW_BLOCK_SIZE_MAX) || (cam_fw->data == NULL)) { err = -EINVAL; break; } if ((err = zcam_flash_read(zvideo, cam_fw->address, data, cam_fw->size))) { break; } if (copy_to_user((void __user *)cam_fw->data, data, cam_fw->size)) { zynq_err("%d vid%d " "ZYNQ_IOC_CAM_FLASH_READ: copy_to_user failed\n", zdev->zdev_inst, zvideo->index); err = -EFAULT; break; } break; } case ZYNQ_IOC_CAM_FLASH_WRITE: { zynq_cam_fw_t *cam_fw = (zynq_cam_fw_t *)arg; unsigned char data[ZYNQ_CAM_FW_BLOCK_SIZE_MAX]; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d " "ZYNQ_IOC_CAM_FLASH_WRITE: address=0x%x, size=%d\n", zdev->zdev_inst, zvideo->index, cam_fw->address, cam_fw->size); if ((cam_fw->size > ZYNQ_CAM_FW_BLOCK_SIZE_MAX) || (cam_fw->data == NULL)) { err = -EINVAL; break; } if (copy_from_user(data, (void __user *)cam_fw->data, cam_fw->size)) { zynq_err("%d vid%d " "ZYNQ_IOC_CAM_FLASH_WRITE: copy_from_user failed\n", zdev->zdev_inst, zvideo->index); err = -EFAULT; break; } err = zcam_flash_write(zvideo, cam_fw->address, data, cam_fw->size); break; } case ZYNQ_IOC_CAM_CAPS: { zynq_cam_caps_t *caps = (zynq_cam_caps_t *)arg; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_CAM_CAPS\n", zdev->zdev_inst, zvideo->index); if (caps->unique_id == 0xFFFF) { (void) zcam_check_caps(zvideo); } memcpy(caps, &zvideo->caps, sizeof(zynq_cam_caps_t)); break; } case ZYNQ_IOC_CAM_RESET: zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_CAM_RESET\n", zdev->zdev_inst, zvideo->index); spin_lock_bh(&zvideo->qlock); zvideo->state |= ZVIDEO_STATE_CAM_FAULT; spin_unlock_bh(&zvideo->qlock); zchan_watchdog_complete(zvideo->zchan); break; case ZYNQ_IOC_TRIGGER_ENABLE_ONE: zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_TRIGGER_ENABLE_ONE\n", zdev->zdev_inst, zvideo->index); zvideo_trigger_enable(zvideo, arg); break; case ZYNQ_IOC_TRIGGER_DISABLE_ONE: zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_TRIGGER_DISABLE_ONE\n", zdev->zdev_inst, zvideo->index); zvideo_trigger_disable(zvideo); break; case ZYNQ_IOC_TRIGGER_DELAY_SET: zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_TRIGGER_DELAY_SET\n", zdev->zdev_inst, zvideo->index); zvideo_trigger_delay_set(zvideo, arg); break; case ZYNQ_IOC_TRIGGER_DELAY_GET: zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ZYNQ_IOC_TRIGGER_DELAY_GET\n", zdev->zdev_inst, zvideo->index); zvideo_trigger_delay_get(zvideo, arg); break; default: zynq_err("%d vid%d unknown ioctl command\n", zdev->zdev_inst, zvideo->index); err = -EINVAL; break; } return err; } /* The control handler. */ static int zvideo_s_ctrl(struct v4l2_ctrl *ctrl) { zynq_video_t *zvideo = container_of(ctrl->handler, zynq_video_t, ctrl_handler); zynq_dev_t *zdev = zvideo->zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: id=%u\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, ctrl->id - V4L2_CID_BASE); return 0; } static const struct v4l2_ctrl_ops zvideo_ctrl_ops = { .s_ctrl = zvideo_s_ctrl, }; /* * The set of all supported ioctls. Note that all the streaming ioctls * use the vb2 helper functions that take care of all the locking and * that also do ownership tracking (i.e. only the filehandle that requested * the buffers can call the streaming ioctls, all other filehandles will * receive -EBUSY if they attempt to call the same streaming ioctls). * * The last three ioctls also use standard helper functions: these implement * standard behavior for drivers with controls. */ static const struct v4l2_ioctl_ops video_ioctl_ops = { .vidioc_querycap = zvideo_querycap, .vidioc_try_fmt_vid_cap = zvideo_try_fmt_vid_cap, .vidioc_s_fmt_vid_cap = zvideo_s_fmt_vid_cap, .vidioc_g_fmt_vid_cap = zvideo_g_fmt_vid_cap, .vidioc_enum_fmt_vid_cap = zvideo_enum_fmt_vid_cap, .vidioc_enum_input = zvideo_enum_input, .vidioc_g_input = zvideo_g_input, .vidioc_s_input = zvideo_s_input, .vidioc_reqbufs = vb2_ioctl_reqbufs, .vidioc_create_bufs = vb2_ioctl_create_bufs, .vidioc_querybuf = vb2_ioctl_querybuf, .vidioc_qbuf = vb2_ioctl_qbuf, .vidioc_dqbuf = vb2_ioctl_dqbuf, .vidioc_expbuf = vb2_ioctl_expbuf, .vidioc_streamon = vb2_ioctl_streamon, .vidioc_streamoff = vb2_ioctl_streamoff, .vidioc_log_status = v4l2_ctrl_log_status, .vidioc_subscribe_event = v4l2_ctrl_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, .vidioc_default = zvideo_ioctl_default }; /* * The set of file operations. Note that all these ops are standard core * helper functions. */ static const struct v4l2_file_operations zvideo_fops = { .owner = THIS_MODULE, .open = v4l2_fh_open, .release = vb2_fop_release, .unlocked_ioctl = video_ioctl2, .read = vb2_fop_read, .mmap = vb2_fop_mmap, .poll = vb2_fop_poll, }; static int zvideo_check_link_status(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; u32 status; unsigned char prev; int changed; status = zvideo_reg_read(zvideo, ZYNQ_CAM_STATUS); zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: camera status 0x%x\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, status); prev = zvideo->caps.link_up; zvideo->caps.link_up = !(status & ZYNQ_CAM_FPD_UNLOCK); zynq_log("%d vid%d %s: FPD-link %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->caps.link_up ? "locked" : "NOT locked"); changed = (zvideo->caps.link_up != prev); return changed; } static void zvideo_get_camera_info(zynq_video_t *zvideo) { (void) zcam_check_caps(zvideo); zvideo_set_format(zvideo); } void zvideo_watchdog(zynq_video_t *zvideo) { if ((zvideo->state & ZVIDEO_STATE_LINK_CHANGE) && (jiffies >= (zvideo->ts_link_change + msecs_to_jiffies(ZVIDEO_LINK_CHANGE_DELAY)))) { zvideo_link_change(zvideo); } if (zvideo->state & (ZVIDEO_STATE_CHAN_FAULT | ZVIDEO_STATE_CAM_FAULT)) { zvideo_reset(zvideo); } } int zvideo_register_vdev(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; struct video_device *vdev; int ret; /* Initialize the video_device structure */ vdev = &zvideo->vdev; if (video_is_registered(vdev)) { zynq_err("%d vid%d %s: video device already registerd\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); return -1; } memset(vdev, 0, sizeof(struct video_device)); vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING; strlcpy(vdev->name, zvideo->caps.name, sizeof(vdev->name)); /* * There is nothing to clean up, so release is set to an empty release * function. The release callback must be non-NULL. */ vdev->release = video_device_release_empty; vdev->fops = &zvideo_fops, vdev->ioctl_ops = &video_ioctl_ops, /* * The main serialization lock. All ioctls are serialized by this * lock. Exception: if q->lock is set, then the streaming ioctls * are serialized by that separate lock. */ vdev->lock = &zvideo->mlock; vdev->queue = &zvideo->queue; vdev->v4l2_dev = &zvideo->v4l2_dev; video_set_drvdata(vdev, zvideo); ret = video_register_device(vdev, VFL_TYPE_GRABBER, -1); if (ret) { zynq_err("%d vid%d %s: failed to register video device\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); return ret; } zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: video device registered, /dev/video%d, %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->vdev.num, zvideo->caps.name); return 0; } void zvideo_unregister_vdev(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; video_unregister_device(&zvideo->vdev); zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d %s: video device unregistered, /dev/video%d, %s\n", zdev->zdev_inst, zvideo->index, __FUNCTION__, zvideo->vdev.num, zvideo->caps.name); } static void zvideo_stats_init(zynq_video_t *zvideo) { int i; for (i = 0; i < VIDEO_STATS_NUM; i++) { zvideo->stats[i].label = zvideo_stats_label[i]; } } /* * The initial setup of this device instance. Note that the initial state of * the driver should be complete. So the initial format, standard, timings * and video input should all be initialized to some reasonable value. */ int zvideo_init(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; zynq_chan_t *zchan = zvideo->zchan; struct v4l2_ctrl_handler *hdl; struct vb2_queue *q; int ret; zynq_trace(ZYNQ_TRACE_PROBE, "%d ch%d vid%d %s: zvideo=0x%p\n", zdev->zdev_inst, zchan->zchan_num, zvideo->index, __FUNCTION__, zvideo); snprintf(zvideo->prefix, ZYNQ_LOG_PREFIX_LEN, "%d vid%d", zdev->zdev_inst, zvideo->index); zvideo_stats_init(zvideo); zvideo->reg_base = zdev->zdev_bar0 + (ZYNQ_CAM_REG_OFFSET * zvideo->index); INIT_LIST_HEAD(&zvideo->buf_list); INIT_LIST_HEAD(&zvideo->pending_list); spin_lock_init(&zvideo->rlock); spin_lock_init(&zvideo->qlock); mutex_init(&zvideo->mlock); mutex_init(&zvideo->slock); /* Initialize the top-level structure */ ret = v4l2_device_register(&zdev->zdev_pdev->dev, &zvideo->v4l2_dev); if (ret) { zynq_err("%d ch%d vid%d %s: failed to regiser v4l2\n", zdev->zdev_inst, zchan->zchan_num, zvideo->index, __FUNCTION__); return -1; } /* Add the controls */ hdl = &zvideo->ctrl_handler; v4l2_ctrl_handler_init(hdl, 0); zvideo->v4l2_dev.ctrl_handler = hdl; /* Initialize the vb2 queue */ q = &zvideo->queue; q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; q->io_modes = VB2_MMAP; q->drv_priv = zvideo; q->buf_struct_size = sizeof (zynq_video_buffer_t); q->ops = &video_qops; q->mem_ops = &vb2_vmalloc_memops; q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; q->min_buffers_needed = zynq_video_buf_num; /* * The serialization lock for streaming ioctls. It could be the same * as the main serialization lock, but if some of the non-streaming * ioctls could take a long time to execute, then we might want to * have a different lock here to prevent VIDIOC_DQBUF from being * blocked while waiting for another action to finish. Here we use * a different lock. */ q->lock = &zvideo->slock; q->gfp_flags = GFP_DMA; ret = vb2_queue_init(q); if (ret) { zynq_err("%d ch%d vid%d %s: failed to init vb2 queue\n", zdev->zdev_inst, zchan->zchan_num, zvideo->index, __FUNCTION__); goto free_hdl; } /* Check the camera link status and register video device */ (void) zvideo_check_link_status(zvideo); if (zvideo->caps.link_up) { zvideo_get_camera_info(zvideo); ret = zvideo_register_vdev(zvideo); if (ret) { goto free_hdl; } } zynq_trace(ZYNQ_TRACE_PROBE, "%d ch%d vid%d %s done\n", zdev->zdev_inst, zchan->zchan_num, zvideo->index, __FUNCTION__); return 0; free_hdl: v4l2_ctrl_handler_free(&zvideo->ctrl_handler); v4l2_device_unregister(&zvideo->v4l2_dev); return ret; } void zvideo_fini(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; zynq_chan_t *zchan = zvideo->zchan; zynq_trace(ZYNQ_TRACE_PROBE, "%d ch%d vid%d %s %s: zvideo=0x%p\n", zdev->zdev_inst, zchan->zchan_num, zvideo->index, zvideo->caps.name, __FUNCTION__, zvideo); zvideo_unregister_vdev(zvideo); v4l2_ctrl_handler_free(&zvideo->ctrl_handler); v4l2_device_unregister(&zvideo->v4l2_dev); } void zvideo_link_change(zynq_video_t *zvideo) { zynq_dev_t *zdev = zvideo->zdev; int link_changed; spin_lock_bh(&zvideo->qlock); zvideo->state &= ~ZVIDEO_STATE_LINK_CHANGE; link_changed = zvideo_check_link_status(zvideo); if (!link_changed) { spin_unlock_bh(&zvideo->qlock); return; } if (zvideo->state & ZVIDEO_STATE_STREAMING) { zynq_err("%d vid%d %s: device busy\n", zdev->zdev_inst, zvideo->index, __FUNCTION__); } spin_unlock_bh(&zvideo->qlock); if (zvideo->caps.link_up) { zvideo_get_camera_info(zvideo); (void) zvideo_register_vdev(zvideo); } else { zvideo_unregister_vdev(zvideo); } } static inline int zvideo_data_range_check(unsigned long offset, unsigned long start, unsigned long end, void **vaddr, unsigned long *len) { unsigned long size = *len; long diff; if (((offset + size) >= start) && (offset < end)) { diff = start - offset; if (diff > 0) { *vaddr = (void *)((uintptr_t)*vaddr + diff); *len -= diff; } diff = offset + size - end; if (diff > 0) { *len -= diff; } return 1; } return 0; } static void zvideo_rx_proc_copy(zynq_video_t *zvideo) { zynq_chan_t *zchan = zvideo->zchan; zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; zynq_video_buffer_t *buf; struct vb2_buffer *vb; unsigned char *mem; unsigned long memsz; unsigned long size; unsigned long len; u32 hw_tail; u32 rx_tail; u32 rx_off; void *data_phy; void *data; rx_off = zchan_rx->zchan_rx_head; hw_tail = zchan_reg_read(zchan, ZYNQ_CH_RX_TAIL); rx_tail = hw_tail & ~(PAGE_SIZE - 1); if (rx_off == rx_tail) { zynq_err("%d vid%d ch%d %s: no data to receive, " "rx_head=0x%x, rx_tail=0x%x\n", ZYNQ_INST(zchan), zvideo->index, zchan->zchan_num, __FUNCTION__, zchan_rx->zchan_rx_head, hw_tail); return; } zvideo_get_timestamp(&zvideo->tv_intr); zynq_trace(ZYNQ_TRACE_PROBE, "%d ch%d vid%d %s: begin, rx_head=0x%x, rx_tail=0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, zvideo->index, __FUNCTION__, zchan_rx->zchan_rx_head, hw_tail); do { buf = NULL; size = 0; /* Retrieve one buffer from the driver owned buffer list */ spin_lock(&zvideo->qlock); if (zvideo->state & ZVIDEO_STATE_STREAMING) { if (!list_empty(&zvideo->buf_list)) { buf = list_first_entry(&zvideo->buf_list, zynq_video_buffer_t, list); list_del(&buf->list); zvideo->buf_avail--; } } spin_unlock(&zvideo->qlock); if (buf == NULL) { ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_NO_VIDEO_BUF); if (ZCHAN_RX_FREE_SIZE(zchan_rx, rx_off, rx_tail) >= zvideo->format.sizeimage) { /* * There are still available DMA buffers, * we simply return and leave the data to * be handled with the next interrupt. */ return; } ZYNQ_STATS_LOGX(zchan, CHAN_STATS_RX_DROP, 1, 0); /* Discard the current frame data */ rx_off += zvideo->format.sizeimage; goto next; } vb = &buf->vbuf.vb2_buf; /* Get the virtual address and size of the video buffer */ mem = zvideo_buffer_vaddr(buf); memsz = zvideo_buffer_size(buf); while ((rx_off != rx_tail) && (memsz > 0) && (size < zvideo->format.sizeimage)) { /* * Retrive the actual addresses of the data */ zchan_rx_off2addr(zchan_rx, rx_off, &data, &data_phy); /* Calculate the length of the data to be copied */ if (ZCHAN_WITHIN_RX_BUF(zchan_rx, rx_off, rx_tail) && (rx_off <= rx_tail)) { len = rx_tail - rx_off; } else { len = zchan_rx->zchan_rx_bufsz - ZCHAN_RX_BUF_OFFSET(zchan_rx, rx_off); } /* Limit the length when buffer space is not enough */ if (len > memsz) { len = memsz; } pci_dma_sync_single_for_cpu(zchan->zdev->zdev_pdev, (dma_addr_t)data_phy, len, PCI_DMA_FROMDEVICE); /* Copy the data to the video buffer */ memcpy(mem, data, len); mem += len; memsz -= len; rx_off += len; if (rx_off >= zchan_rx->zchan_rx_size) { rx_off -= zchan_rx->zchan_rx_size; } size += len; } ASSERT((memsz == 0) && (size == zvideo->format.sizeimage)); ZYNQ_STATS(zchan, CHAN_STATS_RX); next: /* * Reset the meta data right after the video frame is copied * to the video buffer or is discarded. */ zvideo_reset_meta_data(zvideo, zchan_rx->zchan_rx_head); /* * Advance the pointer to the beginning of next video frame. * Video frame data always starts at the beginning boundary * of a DMA buffer (a page). */ rx_off = ALIGN(rx_off, zchan_rx->zchan_rx_bufsz); if (rx_off >= zchan_rx->zchan_rx_size) { rx_off -= zchan_rx->zchan_rx_size; } /* Update head index */ zchan_rx->zchan_rx_head = rx_off; zchan_reg_write(zchan, ZYNQ_CH_RX_HEAD, rx_off); zynq_trace(ZYNQ_TRACE_PROBE, "%d ch%d vid%d %s: frame end, " "size=0x%lx, rx_head=0x%x, rx_tail=0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, zvideo->index, __FUNCTION__, size, zchan_rx->zchan_rx_head, hw_tail); if (buf != NULL) { if (zvideo_check_meta_data(zvideo, buf)) { /* * If the video frame has error, discard * the frame, and return the buffer to * the buffer list. */ spin_lock(&zvideo->qlock); list_add_tail(&buf->list, &zvideo->buf_list); zvideo->buf_avail++; spin_unlock(&zvideo->qlock); } else { zynq_trace(ZYNQ_TRACE_PROBE, "%d ch%d vid%d %s: " "buffer done, vb=0x%p, state=%d\n", ZYNQ_INST(zchan), zchan->zchan_num, zvideo->index, __FUNCTION__, vb, vb->state); vb2_set_plane_payload(vb, 0, size); vb2_buffer_done(vb, VB2_BUF_STATE_DONE); } } zvideo->sequence++; } while (rx_off != rx_tail); } static void zvideo_rx_proc_zero_copy(zynq_video_t *zvideo) { zynq_chan_t *zchan = zvideo->zchan; zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; zynq_video_buffer_t *buf, *cur, *next; struct vb2_buffer *vb; u32 hw_tail; u32 rx_tail; u32 rx_off; unsigned long memsz; unsigned long size, len = 0; void *data_phy = NULL; if (zchan_rx->zchan_rx_bufsz == 0) { zynq_err("%d vid%d ch%d %s: DMA is not initialized\n", ZYNQ_INST(zchan), zvideo->index, zchan->zchan_num, __FUNCTION__); return; } ASSERT(zchan_rx->zchan_rx_head == zchan_reg_read(zchan, ZYNQ_CH_RX_HEAD)); hw_tail = zchan_reg_read(zchan, ZYNQ_CH_RX_TAIL); rx_tail = hw_tail & ~(PAGE_SIZE - 1); if (ZCHAN_RX_USED_SIZE(zchan_rx, zchan_rx->zchan_rx_head, rx_tail) % ALIGN(zvideo->format.sizeimage, zchan_rx->zchan_rx_bufsz)) { zynq_err("%d vid%d ch%d %s: index check failed, " "rx_head=0x%x, rx_tail=0x%x\n", ZYNQ_INST(zchan), zvideo->index, zchan->zchan_num, __FUNCTION__, zchan_rx->zchan_rx_head, hw_tail); return; } rx_off = zchan_rx->zchan_rx_off; if (rx_off == rx_tail) { zynq_err("%d vid%d ch%d %s: no data to receive, " "rx_head=0x%x, rx_tail=0x%x, rx_off=0x%x\n", ZYNQ_INST(zchan), zvideo->index, zchan->zchan_num, __FUNCTION__, zchan_rx->zchan_rx_head, hw_tail, rx_off); return; } zvideo_get_timestamp(&zvideo->tv_intr); zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ch%d %s: begin, " "rx_head=0x%x, rx_tail=0x%x, rx_off=0x%x\n", ZYNQ_INST(zchan), zvideo->index, zchan->zchan_num, __FUNCTION__, zchan_rx->zchan_rx_head, hw_tail, rx_off); do { buf = NULL; size = 0; /* * Find the video buffer bound to the current offset */ spin_lock(&zvideo->qlock); if (zvideo->state & ZVIDEO_STATE_STREAMING) { list_for_each_entry_safe(cur, next, &zvideo->buf_list, list) { if (cur->offset == rx_off) { list_del(&cur->list); zvideo->buf_avail--; buf = cur; break; } } } spin_unlock(&zvideo->qlock); if (buf == NULL) { ZYNQ_STATS_LOGX(zvideo, VIDEO_STATS_NO_VIDEO_BUF, 1, 0); return; } vb = &buf->vbuf.vb2_buf; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ch%d %s: buffer avail, " "vb=0x%p, vb.state=%d, buf.offset=0x%x, rx_off=0x%x\n", ZYNQ_INST(zchan), zvideo->index, zchan->zchan_num, __FUNCTION__, vb, vb->state, buf->offset, rx_off); /* Get the size of the video buffer */ memsz = zvideo_buffer_size(buf); while ((rx_off != rx_tail) && (memsz > 0) && (size < zvideo->format.sizeimage)) { /* * Retrive the actual addresses of the data */ zchan_rx_off2addr(zchan_rx, rx_off, NULL, &data_phy); /* Calculate the length of the data to sync */ if (ZCHAN_WITHIN_RX_BUF(zchan_rx, rx_off, rx_tail) && (rx_off <= rx_tail)) { len = rx_tail - rx_off; } else { len = zchan_rx->zchan_rx_bufsz - ZCHAN_RX_BUF_OFFSET(zchan_rx, rx_off); } /* Limit the length when buffer space is not enough */ if (len > memsz) { len = memsz; } pci_dma_sync_single_for_cpu(zchan->zdev->zdev_pdev, (dma_addr_t)data_phy, len, PCI_DMA_FROMDEVICE); rx_off += len; if (rx_off >= zchan_rx->zchan_rx_size) { rx_off -= zchan_rx->zchan_rx_size; } size += len; memsz -= len; } ASSERT((memsz == 0) && (size == zvideo->format.sizeimage)); if ((memsz != 0) || ( size != zvideo->format.sizeimage)) { zynq_err("%d vid%d ch%d %s: expected size=%u, " "received size=%lu, avail memsz=%lu, " "rx_head=0x%x, rx_tail=0x%x, rx_off=0x%x\n", ZYNQ_INST(zchan), zvideo->index, zchan->zchan_num, __FUNCTION__, zvideo->format.sizeimage, size, memsz, zchan_rx->zchan_rx_head, hw_tail, rx_off); rx_off += memsz; } ZYNQ_STATS(zchan, CHAN_STATS_RX); if (zvideo_check_meta_data(zvideo, buf)) { /* * If the video frame has error, discard the frame. * Put the buffer to the pending list for further * handling. */ spin_lock(&zvideo->qlock); list_add(&buf->list, &zvideo->pending_list); zvideo_check_pending(zvideo); spin_unlock(&zvideo->qlock); } else { zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ch%d %s: " "buffer done, vb=0x%p, vb.state=%d\n", ZYNQ_INST(zchan), zvideo->index, zchan->zchan_num, __FUNCTION__, vb, vb->state); vb2_set_plane_payload(vb, 0, size); vb2_buffer_done(vb, VB2_BUF_STATE_DONE); } /* * Advance the pointer to the beginning of next video frame. * Video frame data always starts at the beginning boundary * of a DMA buffer (a page). */ rx_off = ALIGN(rx_off, zchan_rx->zchan_rx_bufsz); if (rx_off >= zchan_rx->zchan_rx_size) { rx_off -= zchan_rx->zchan_rx_size; } /* * Update global offset. The head pointer will be updated * later when the video buffer is returned from user space. */ zchan_rx->zchan_rx_off = rx_off; zynq_trace(ZYNQ_TRACE_PROBE, "%d vid%d ch%d %s: frame end, " "rx_head=0x%x, rx_tail=0x%x, rx_off=0x%x, size=0x%lx\n", ZYNQ_INST(zchan), zvideo->index, zchan->zchan_num, __FUNCTION__, zchan_rx->zchan_rx_head, hw_tail, rx_off, size); zvideo->sequence++; } while (rx_off != rx_tail); } void zvideo_rx_proc(zynq_video_t *zvideo) { spin_lock(&zvideo->rlock); if (zynq_video_zero_copy) { zvideo_rx_proc_zero_copy(zvideo); } else { zvideo_rx_proc_copy(zvideo); } spin_unlock(&zvideo->rlock); } void zvideo_err_proc(zynq_video_t *zvideo, int ch_err_status) { /* error statistics */ if (ch_err_status & ZYNQ_CH_ERR_CAM_TRIGGER) { ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_TRIG_PULSE_ERR); } if (ch_err_status & ZYNQ_CH_ERR_CAM_LINK_CHANGE) { ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_LINK_CHANGE); spin_lock(&zvideo->qlock); zvideo->state |= ZVIDEO_STATE_LINK_CHANGE; zvideo->ts_link_change = jiffies; spin_unlock(&zvideo->qlock); } if (ch_err_status & ZYNQ_CH_ERR_DMA_RX_BUF_FULL) { ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_DMA_RX_BUF_FULL); } if (ch_err_status & ZYNQ_CH_ERR_DMA_RX_FIFO_FULL) { ZYNQ_STATS_LOG(zvideo, VIDEO_STATS_DMA_RX_FIFO_FULL); } } void zvideo_get_timestamp(struct timeval *tv) { #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE struct timespec ts; ktime_get_real_ts(&ts); #else struct timespec64 ts; ktime_get_real_ts64(&ts); #endif tv->tv_sec = ts.tv_sec; tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC; } module_param_named(videofmt, zynq_video_format, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(videofmt, "video format"); module_param_named(videobufnum, zynq_video_buf_num, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(videobufnum, "video buffer number"); module_param_named(videozerocopy, zynq_video_zero_copy, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(videozerocopy, "video zero copy"); module_param_named(videotstype, zynq_video_ts_type, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(videotstype, "video timestamp type"); module_param_named(videoflash16, zynq_video_flash_16, int, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(videoflash16, "camera flash 16b address width"); module_param_named(videopinswap, zynq_video_pin_swap, int, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(videopinswap, "camera pin swap"); module_param_named(videoerrtol, zynq_video_err_tolerant, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(videoerrtol, "video error tolerant"); module_param_named(videoerrthr, zynq_video_err_thresh, uint, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(videoerrthr, "video error threshold");
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_sysfs.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/kobject.h> #include <linux/sysfs.h> #include <linux/string.h> #include "basa.h" /* * sysfs related to global driver level parameter is under * /sys/module/basa/parameters/ */ /* * show the number of CAN IP(s) the device has: * cat num_can_ip */ static ssize_t zynq_sysfs_num_can_ip_show(zynq_dev_t *zdev, char *buf) { int len; len = sprintf(buf, "%u\n", zdev->zdev_can_cnt); return len; } /* * show the number of channels the device has: * cat num_chan */ static ssize_t zynq_sysfs_num_chan_show(zynq_dev_t *zdev, char *buf) { int len; len = sprintf(buf, "%u\n", zdev->zdev_chan_cnt); return len; } static u32 zynq_sysfs_can_ip = 0; /* * show the CAN IP instance that we are going to operate: * cat can_ip */ static ssize_t zynq_sysfs_can_ip_read(zynq_dev_t *zdev, char *buf) { int len; len = sprintf(buf, "CAN IP number is %u\n", zynq_sysfs_can_ip); return len; } /* * set the CAN IP instance that we are going to operate: * echo <can> > can_ip */ static ssize_t zynq_sysfs_can_ip_set(zynq_dev_t *zdev, const char *buf, size_t sz) { u32 can_ip; sscanf(buf, "%u", &can_ip); if (can_ip >= zdev->zdev_can_cnt || !can_ip_to_zcan(zdev, can_ip)) { zynq_err("bad CAN IP number %u, maximum is %u\n", can_ip, zdev->zdev_can_cnt - 1); } else { zynq_err("CAN IP number changed %u -> %u\n", zynq_sysfs_can_ip, can_ip); zynq_sysfs_can_ip = can_ip; } return sz; } static u32 zynq_sysfs_chan = 0; /* * show the channel number that we are going to operate: * cat chan */ static ssize_t zynq_sysfs_chan_read(zynq_dev_t *zdev, char *buf) { int len; len = sprintf(buf, "channel number is %u\n", zynq_sysfs_chan); return len; } /* * set the channel number that we are going to operate: * echo <chan> > chan */ static ssize_t zynq_sysfs_chan_set(zynq_dev_t *zdev, const char *buf, size_t sz) { u32 chan; sscanf(buf, "%u", &chan); if (chan >= zdev->zdev_chan_cnt) { zynq_err("bad channel number %u, maximum is %u\n", chan, zdev->zdev_chan_cnt - 1); } else { zynq_err("channel number changed %u -> %u\n", zynq_sysfs_chan, chan); zynq_sysfs_chan = chan; } return sz; } static u32 zynq_sysfs_g_reg_offset = 0; /* cat g_reg_value */ static ssize_t zynq_sysfs_g_reg_read(zynq_dev_t *zdev, char *buf) { int len; len = sprintf(buf, "device register offset 0x%x = 0x%x\n", zynq_sysfs_g_reg_offset, ZDEV_G_REG32_RD(zdev, zynq_sysfs_g_reg_offset)); return len; } /* * echo <offset> <val> > g_reg_value * echo <offset> > g_reg_value */ static ssize_t zynq_sysfs_g_reg_set(zynq_dev_t *zdev, const char *buf, size_t sz) { u32 offset, val; if (strchr(buf, ' ')) { sscanf(buf, "%x %x", &offset, &val); if (offset > (zdev->zdev_bar0_len - 4)) { zynq_err("bad register offset 0x%x, maximum is 0x%x\n", offset, zdev->zdev_bar0_len - 4); } else { zynq_err("device register offset 0x%x set to 0x%x\n", offset, val); ZDEV_G_REG32(zdev, offset) = val; zynq_sysfs_g_reg_offset = offset; } } else { sscanf(buf, "%x", &offset); if (offset > (zdev->zdev_bar0_len - 4)) { zynq_err("bad register offset 0x%x, maximum is 0x%x\n", offset, zdev->zdev_bar0_len - 4); } else { zynq_err("device register offset changed 0x%x -> 0x%x\n", zynq_sysfs_g_reg_offset, offset); zynq_sysfs_g_reg_offset = offset; } } return sz; } static u8 zynq_sysfs_i2c_id = 0; static u8 zynq_sysfs_i2c_addr = 0; static u8 zynq_sysfs_i2c_addr_hi = 0; static u8 zynq_sysfs_i2c_bus = 0; /* * show the i2c bus number that we are going to operate: * cat i2c_bus */ static ssize_t zynq_sysfs_i2c_bus_read(zynq_dev_t *zdev, char *buf) { int len; len = sprintf(buf, "I2C bus number is %u\n", zynq_sysfs_i2c_bus); return len; } /* * set the i2c bus number that we are going to operate: * echo <i2c_bus> > i2c_bus */ static ssize_t zynq_sysfs_i2c_bus_set(zynq_dev_t *zdev, const char *buf, size_t sz) { u8 i2c_bus; sscanf(buf, "%hhu", &i2c_bus); if (i2c_bus >= ZYNQ_I2C_BUS_NUM) { zynq_err("bad I2C bus number %u, maximum is %u\n", i2c_bus, ZYNQ_I2C_BUS_NUM - 1); } else { zynq_err("I2C bus number changed %u -> %u\n", zynq_sysfs_i2c_bus, i2c_bus); zynq_sysfs_i2c_bus = i2c_bus; } return sz; } static ssize_t zynq_sysfs_i2c_read(zynq_dev_t *zdev, char *buf, unsigned char i2c_addr_16) { ioc_zynq_i2c_acc_t i2c_acc; u32 i2c_addr; int err; int len; i2c_acc.i2c_id = zynq_sysfs_i2c_id; i2c_acc.i2c_addr_hi = zynq_sysfs_i2c_addr_hi; i2c_acc.i2c_addr = zynq_sysfs_i2c_addr; i2c_acc.i2c_data = 0; i2c_acc.i2c_addr_16 = i2c_addr_16; i2c_acc.i2c_bus = zynq_sysfs_i2c_bus; err = zdev_i2c_read(zdev, &i2c_acc); i2c_addr = (i2c_addr_16) ? (zynq_sysfs_i2c_addr_hi << 8) | zynq_sysfs_i2c_addr : zynq_sysfs_i2c_addr; if (err) { len = sprintf(buf, "I2C read failed: id = 0x%x, " "addr = 0x%x\n", i2c_acc.i2c_id, i2c_addr); } else { len = sprintf(buf, "I2C read OK: id = 0x%x, " "addr = 0x%x, data = 0x%x\n", i2c_acc.i2c_id, i2c_addr, i2c_acc.i2c_data); } return len; } /* cat i2c_reg */ static ssize_t zynq_sysfs_i2c_reg_read(zynq_dev_t *zdev, char *buf) { return zynq_sysfs_i2c_read(zdev, buf, 0); } /* cat i2c_reg16 */ static ssize_t zynq_sysfs_i2c_reg16_read(zynq_dev_t *zdev, char *buf) { return zynq_sysfs_i2c_read(zdev, buf, 1); } static int zynq_sysfs_i2c_write(zynq_dev_t *zdev, const char *buf, unsigned char i2c_addr_16) { ioc_zynq_i2c_acc_t i2c_acc; u32 i2c_id, i2c_addr, i2c_data; u32 addr_max = (i2c_addr_16) ? 0xffff : 0xff; int err = 0; /* * SysFS has stripped all unnecessary spaces from buf (leading, * trailing, extra in the middle) */ if (!strchr(buf, ' ')) { zynq_err("%s: bad format\n", __FUNCTION__); return -1; } if ((u64)strchr(buf, ' ') == (u64)strrchr(buf, ' ')) { /* only two arguments */ sscanf(buf, "%x %x", &i2c_id, &i2c_addr); if (i2c_id > ZYNQ_I2C_ID_MAX) { zynq_err("%s: bad id 0x%x, maximum is 0x%x\n", __FUNCTION__, i2c_id, ZYNQ_I2C_ID_MAX); return -1; } if (i2c_addr > addr_max) { zynq_err("%s: bad addr 0x%x, maximum is 0x%x\n", __FUNCTION__, i2c_addr, addr_max); return -1; } zynq_log("I2C update OK: id = 0x%x, addr = 0x%x\n", i2c_id, i2c_addr); zynq_sysfs_i2c_id = (u8)i2c_id; zynq_sysfs_i2c_addr = (u8)i2c_addr; zynq_sysfs_i2c_addr_hi = (i2c_addr_16) ? (u8)(i2c_addr >> 8) : 0; } else { /* more than two arguments */ sscanf(buf, "%x %x %x", &i2c_id, &i2c_addr, &i2c_data); if (i2c_id > ZYNQ_I2C_ID_MAX) { zynq_err("%s: bad id 0x%x, maximum is 0x%x\n", __FUNCTION__, i2c_id, ZYNQ_I2C_ID_MAX); return -1; } if (i2c_addr > addr_max) { zynq_err("%s: bad addr 0x%x, maximum is 0x%x\n", __FUNCTION__, i2c_addr, addr_max); return -1; } if (i2c_data > 0xff) { zynq_err("%s: bad data 0x%x, maximum is 0xff\n", __FUNCTION__, i2c_data); return -1; } zynq_sysfs_i2c_id = (u8)i2c_id; zynq_sysfs_i2c_addr = (u8)i2c_addr; zynq_sysfs_i2c_addr_hi = (i2c_addr_16) ? (u8)(i2c_addr >> 8) : 0; i2c_acc.i2c_id = zynq_sysfs_i2c_id; i2c_acc.i2c_addr_hi = zynq_sysfs_i2c_addr_hi; i2c_acc.i2c_addr = zynq_sysfs_i2c_addr; i2c_acc.i2c_data = (unsigned char)i2c_data; i2c_acc.i2c_addr_16 = i2c_addr_16; i2c_acc.i2c_bus = zynq_sysfs_i2c_bus; err = zdev_i2c_write(zdev, &i2c_acc); if (!err) { zynq_log("I2C write OK: id = 0x%x, addr = 0x%x, " "data = 0x%x\n", i2c_id, i2c_addr, i2c_data); } } return err; } /* * echo <i2c_id> <i2c_addr> <i2c_data> > i2c_reg * echo <i2c_id> <i2c_addr> > i2c_reg */ static ssize_t zynq_sysfs_i2c_reg_write(zynq_dev_t *zdev, const char *buf, size_t sz) { (void) zynq_sysfs_i2c_write(zdev, buf, 0); return sz; } /* * echo <i2c_id> <i2c_addr> <i2c_data> > i2c_reg16 * echo <i2c_id> <i2c_addr> > i2c_reg16 */ static ssize_t zynq_sysfs_i2c_reg16_write(zynq_dev_t *zdev, const char *buf, size_t sz) { (void) zynq_sysfs_i2c_write(zdev, buf, 1); return sz; } static u32 zynq_sysfs_chan_reg_offset = 0; /* cat chan_reg_value */ static ssize_t zynq_sysfs_chan_reg_read(zynq_dev_t *zdev, char *buf) { zynq_chan_t *zchan; int len; zchan = zdev->zdev_chans + zynq_sysfs_chan; len = sprintf(buf, "channel %u register offset 0x%x = 0x%x\n", zynq_sysfs_chan, zynq_sysfs_chan_reg_offset, ZCHAN_REG32_RD(zchan, zynq_sysfs_chan_reg_offset)); return len; } /* * echo <offset> <val> > chan_reg_value * echo <offset> > chan_reg_value */ static ssize_t zynq_sysfs_chan_reg_set(zynq_dev_t *zdev, const char *buf, size_t sz) { zynq_chan_t *zchan; u32 offset, val; if (strchr(buf, ' ')) { sscanf(buf, "%x %x", &offset, &val); if (offset > ZYNQ_CHAN_REG_MAX) { zynq_err("bad channel register offset 0x%x, maximum is " "0x%x\n", offset, ZYNQ_CHAN_REG_MAX); } else { zchan = zdev->zdev_chans + zynq_sysfs_chan; zynq_err("channel %u register offset 0x%x set to 0x%x\n", zynq_sysfs_chan, offset, val); ZCHAN_REG32(zchan, offset) = val; zynq_sysfs_chan_reg_offset = offset; } } else { sscanf(buf, "%x", &offset); if (offset > ZYNQ_CHAN_REG_MAX) { zynq_err("bad channel register offset 0x%x, maximum is " "0x%x\n", offset, ZYNQ_CHAN_REG_MAX); } else { zynq_err("channel %u register offset changed 0x%x -> " "0x%x\n", zynq_sysfs_chan, zynq_sysfs_chan_reg_offset, offset); zynq_sysfs_chan_reg_offset = offset; } } return sz; } static u32 zynq_sysfs_can_ip_reg_offset = 0; /* cat can_ip_reg_value */ static ssize_t zynq_sysfs_can_ip_reg_read(zynq_dev_t *zdev, char *buf) { zynq_can_t *zcan; int len; zcan = can_ip_to_zcan(zdev, zynq_sysfs_can_ip); if (zcan != NULL && zynq_sysfs_can_ip_reg_offset <= (ZCAN_IP_OFFSET - 4)) { len = sprintf(buf, "CAN IP %u register offset 0x%x = 0x%x\n", zynq_sysfs_can_ip, zynq_sysfs_can_ip_reg_offset, ZCAN_REG32_RD(zcan, zynq_sysfs_can_ip_reg_offset)); } else { /* Bar2 direct access */ len = sprintf(buf, "Bar2 register offset 0x%x = 0x%x\n", zynq_sysfs_can_ip_reg_offset, ZDEV_BAR2_REG32_RD(zdev, zynq_sysfs_can_ip_reg_offset)); } return len; } /* * echo <offset> <val> > can_ip_reg_value * echo <offset> > can_ip_reg_value */ static ssize_t zynq_sysfs_can_ip_reg_set(zynq_dev_t *zdev, const char *buf, size_t sz) { zynq_can_t *zcan; u32 offset, val; if (strchr(buf, ' ')) { sscanf(buf, "%x %x", &offset, &val); if (offset > (zdev->zdev_bar2_len - 4)) { zynq_err("bad Bar2/CAN IP register offset 0x%x, maximum " "is 0x%x\n", offset, zdev->zdev_bar2_len - 4); } else { zcan = can_ip_to_zcan(zdev, zynq_sysfs_can_ip); if (zcan != NULL && offset <= (ZCAN_IP_OFFSET - 4)) { zynq_err("CAN IP %u register offset 0x%x set to " "0x%x\n", zynq_sysfs_can_ip, offset, val); ZCAN_REG32(zcan, offset) = val; } else { zynq_err("Bar2 register offset 0x%x set to " "0x%x\n", offset, val); ZDEV_BAR2_REG32(zdev, offset) = val; } zynq_sysfs_can_ip_reg_offset = offset; } } else { sscanf(buf, "%x", &offset); if (offset > (zdev->zdev_bar2_len - 4)) { zynq_err("bad Bar2/CAN IP register offset 0x%x, maximum " "is 0x%x\n", offset, zdev->zdev_bar2_len - 4); } else { zcan = can_ip_to_zcan(zdev, zynq_sysfs_can_ip); if (zcan != NULL && offset <= (ZCAN_IP_OFFSET - 4)) { zynq_err("CAN IP %u register offset changed 0x%x" " -> 0x%x\n", zynq_sysfs_can_ip, zynq_sysfs_can_ip_reg_offset, offset); } else { zynq_err("Bar2 register offset changed 0x%x -> " "0x%x\n", zynq_sysfs_can_ip_reg_offset, offset); } zynq_sysfs_can_ip_reg_offset = offset; } } return sz; } /* * echo <loopback> <msgcnt> > can_ip_test */ static ssize_t zynq_sysfs_can_ip_test(zynq_dev_t *zdev, const char *buf, size_t sz) { zynq_can_t *zcan; int loopback = 1; /* test loopback mode by default */ int msgcnt = 1; zcan = can_ip_to_zcan(zdev, zynq_sysfs_can_ip); if (zdev->zcan_tx_dma) { zynq_err("CAN %u in not in PIO mode, use can_test instead\n", zcan->zcan_ip_num); return sz; } if (strchr(buf, ' ')) { sscanf(buf, "%d %d", &loopback, &msgcnt); } else { sscanf(buf, "%d", &msgcnt); } zcan_pio_test(zcan, loopback, 0, msgcnt); return sz; } /* * echo <loopback> <msgcnt> > can_ip_hi_test */ static ssize_t zynq_sysfs_can_ip_hi_test(zynq_dev_t *zdev, const char *buf, size_t sz) { zynq_can_t *zcan; int loopback = 1; /* test loopback mode by default */ int msgcnt = 1; zcan = can_ip_to_zcan(zdev, zynq_sysfs_can_ip); if (zdev->zcan_tx_dma) { zynq_err("CAN %u is not in PIO mode, use can_test instead\n", zcan->zcan_ip_num); return sz; } if (strchr(buf, ' ')) { sscanf(buf, "%d %d", &loopback, &msgcnt); } else { sscanf(buf, "%d", &msgcnt); } zcan_pio_test(zcan, loopback, 1, msgcnt); return sz; } /* * echo <loopback> <msgcnt> > can_test */ static ssize_t zynq_sysfs_can_test(zynq_dev_t *zdev, const char *buf, size_t sz) { zynq_can_t *zcan; int loopback = 1; /* test loopback mode by default */ int msgcnt = 1; zcan = can_ip_to_zcan(zdev, zynq_sysfs_can_ip); if (!zdev->zcan_tx_dma) { zynq_err("CAN %u is not in DMA mode, use can_ip_test instead\n", zcan->zcan_ip_num); return sz; } if (strchr(buf, ' ')) { sscanf(buf, "%d %d", &loopback, &msgcnt); } else { sscanf(buf, "%d", &msgcnt); } zcan_test(zcan, loopback, msgcnt); return sz; } static u32 zynq_sysfs_tx_desc = 0; /* * show the tx descriptor # that we are going to operate: * cat tx_desc */ static ssize_t zynq_sysfs_tx_desc_read(zynq_dev_t *zdev, char *buf) { int len; len = sprintf(buf, "tx descriptor number is %u\n", zynq_sysfs_tx_desc); return len; } /* * set the tx descriptor # that we are going to operate: * echo <tx_desc#> > tx_desc */ static ssize_t zynq_sysfs_tx_desc_set(zynq_dev_t *zdev, const char *buf, size_t sz) { zynq_chan_t *zchan; zchan_tx_ring_t *zchan_tx; u32 tx_desc; zchan = zdev->zdev_chans + zynq_sysfs_chan; if (zchan->zchan_type == ZYNQ_CHAN_VIDEO || (zchan->zchan_type == ZYNQ_CHAN_CAN && !zdev->zcan_tx_dma)) { zynq_err("not available: ch %d Tx is not in DMA mode\n", zchan->zchan_num); return sz; } sscanf(buf, "%u", &tx_desc); zchan_tx = &zchan->zchan_tx_ring; if (tx_desc >= zchan_tx->zchan_tx_num) { zynq_err("bad tx descriptor number %u, maximum is %u\n", tx_desc, zchan_tx->zchan_tx_num - 1); } else { zynq_err("tx descriptor number changed %u -> %u\n", zynq_sysfs_tx_desc, tx_desc); zynq_sysfs_tx_desc = tx_desc; } return sz; } /* * show the channel Tx info: * cat chan_tx_info */ static ssize_t zynq_sysfs_chan_tx_info_show(zynq_dev_t *zdev, char *buf) { zynq_chan_t *zchan; zchan_tx_ring_t *zchan_tx; zchan_tx_desc_t *tx_descp; zchan_buf_t *bufp; int len = 0, i; zchan = zdev->zdev_chans + zynq_sysfs_chan; if (zchan->zchan_type == ZYNQ_CHAN_VIDEO || (zchan->zchan_type == ZYNQ_CHAN_CAN && !zdev->zcan_tx_dma)) { len = sprintf(buf + len, "info not available: ch %d Tx is not in " "DMA mode\n", zchan->zchan_num); return len; } zchan_tx = &zchan->zchan_tx_ring; len = sprintf(buf + len, "------ channel %u Tx info ------\n", zynq_sysfs_chan); len += sprintf(buf + len, "tx_descp=0x%p, tx_dma=0x%llx, bufsz=0x%x\n", zchan_tx->zchan_tx_descp, zchan_tx->zchan_tx_dma, zchan_tx->zchan_tx_bufsz); tx_descp = zchan_tx->zchan_tx_descp + zynq_sysfs_tx_desc; len += sprintf(buf + len, "tx_desc[%u]: 0x%llx, 0x%llx\n", zynq_sysfs_tx_desc, *(u64 *)tx_descp, *((u64 *)tx_descp + 1)); bufp = zchan_tx->zchan_tx_bufp + zynq_sysfs_tx_desc; for (i = 0; i < tx_descp->tx_len / 8; i++) { len += sprintf(buf + len, "tx_buf[%d]: 0x%llx\n", i, *(((u64 *)bufp->zchan_bufp) + i)); } len += sprintf(buf + len, "tx_head=%u, tx_tail=%u, tx_num=%u\n", zchan_tx->zchan_tx_head, zchan_tx->zchan_tx_tail, zchan_tx->zchan_tx_num); return len; } static ssize_t zynq_sysfs_chan_rx_info_dump(zynq_chan_t *zchan, char *buf) { zchan_rx_tbl_t *zchan_rx; u64 *pdtp; zchan_rx_pt_t *ptp; int i, len = 0; zchan_rx = &zchan->zchan_rx_tbl; len = sprintf(buf + len, "------ channel %u Rx info ------\n", zynq_sysfs_chan); len += sprintf(buf + len, "rx_pdt=0x%p, rx_pdt_dma=0x%llx, " "rx_pdt_num=%u\n", zchan_rx->zchan_rx_pdt, zchan_rx->zchan_rx_pdt_dma, zchan_rx->zchan_rx_pdt_num); pdtp = zchan_rx->zchan_rx_pdt; ptp = zchan_rx->zchan_rx_ptp; for (i = 0; i < zchan_rx->zchan_rx_pdt_num; i++, pdtp++, ptp++) { len += sprintf(buf + len, "rx_pdt[%d]=0x%llx: " "rx_pt=0x%p(0x%llx), rx_pt_dma=0x%llx, rx_buf_dma=0x%llx\n", i, *pdtp, ptp->zchan_rx_pt, *(ptp->zchan_rx_pt), ptp->zchan_rx_pt_dma, ptp->zchan_rx_pt_bufp->zchan_buf_dma); } len += sprintf(buf + len, "rx_head=0x%x, rx_tail=0x%x, " "rx_size=0x%x\n", zchan_rx->zchan_rx_head, zchan_rx->zchan_rx_tail, zchan_rx->zchan_rx_size); return len; } /* * show the channel Rx info: * cat chan_rx_info */ static ssize_t zynq_sysfs_chan_rx_info_show(zynq_dev_t *zdev, char *buf) { zynq_chan_t *zchan; zynq_video_t *zvideo; int len; zchan = zdev->zdev_chans + zynq_sysfs_chan; switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: if (!zdev->zcan_rx_dma) { len = sprintf(buf, "info not available: " "ch %d Rx is not in DMA mode\n", zchan->zchan_num); return len; } len = zynq_sysfs_chan_rx_info_dump(zchan, buf); break; case ZYNQ_CHAN_VIDEO: zvideo = (zynq_video_t *)zchan->zchan_dev; if (zynq_video_zero_copy) { spin_lock_bh(&zvideo->qlock); len = zynq_sysfs_chan_rx_info_dump(zchan, buf); spin_unlock_bh(&zvideo->qlock); } else { len = zynq_sysfs_chan_rx_info_dump(zchan, buf); } break; default: len = sprintf(buf, "info not available: " "ch %d channel type is not supported\n", zchan->zchan_num); break; } return len; } /* * show the channel Rx info: * cat chan_rx_info */ static ssize_t zynq_sysfs_chan_pio_info_show(zynq_dev_t *zdev, char *buf) { zynq_can_t *zcan; zynq_chan_t *zchan; int len = 0; zcan = can_ip_to_zcan(zdev, zynq_sysfs_can_ip); zchan = zcan->zchan; len = sprintf(buf + len, "------ channel PIO %u info ------\n", zynq_sysfs_can_ip); len += sprintf(buf + len, "pio_rx_tail=%d, pio_rx_head=%d, " "pio_rx_num=%d, usr_buf_num=%d, pio_usr_rx_num=%d, " "pio_baudrate=%lu, zcan_usr_rx_seq=%d\n", zcan->zcan_buf_rx_tail, zcan->zcan_buf_rx_head, zcan->zcan_buf_rx_num, zcan->zcan_usr_buf_num, zcan->zcan_usr_rx_num, zcan->zcan_pio_baudrate, zcan->zcan_usr_rx_seq); if ((zynq_trace_param & ZYNQ_TRACE_CAN) || zynq_dbg_reg_dump_param) { zcan_pio_dbg_reg_dump_ch(zcan); } return (len); } static u32 zynq_sysfs_cam = 0; static unsigned short zynq_sysfs_cam_reg = 0; /* * show the camera number that we are going to operate: * cat cam */ static ssize_t zynq_sysfs_cam_read(zynq_dev_t *zdev, char *buf) { int len; len = sprintf(buf, "camera number is %u\n", zynq_sysfs_cam); return len; } /* * set the camera number that we are going to operate: * echo <number> > cam */ static ssize_t zynq_sysfs_cam_set(zynq_dev_t *zdev, const char *buf, size_t sz) { u32 cam; sscanf(buf, "%u", &cam); if (cam >= zdev->zdev_video_cnt) { zynq_err("invalid camera number %u, maximum is %u\n", cam, zdev->zdev_video_cnt - 1); } else { zynq_err("camera number changed %u -> %u\n", zynq_sysfs_cam, cam); zynq_sysfs_cam = cam; } return sz; } /* * read an 8bit camera register value * cat cam_reg8 */ static ssize_t zynq_sysfs_cam_reg8_read(zynq_dev_t *zdev, char *buf) { zynq_video_t *zvideo; zynq_cam_acc_t cam_acc; int len; zvideo = &zdev->zdev_videos[zynq_sysfs_cam]; cam_acc.addr = zynq_sysfs_cam_reg; cam_acc.data = 0; cam_acc.data_sz = 1; if (zcam_reg_read(zvideo, &cam_acc)) { len = sprintf(buf, "failed to read camera %u register 0x%04hx\n", zynq_sysfs_cam, zynq_sysfs_cam_reg); return len; } len = sprintf(buf, "camera %u register 0x%04hx = 0x%02hhx\n", zynq_sysfs_cam, zynq_sysfs_cam_reg, (unsigned char)cam_acc.data); return len; } /* * echo <reg> <val> > cam_reg8 * echo <reg> > cam_reg8 */ static ssize_t zynq_sysfs_cam_reg8_set(zynq_dev_t *zdev, const char *buf, size_t sz) { zynq_video_t *zvideo; zynq_cam_acc_t cam_acc; if (strchr(buf, ' ')) { sscanf(buf, "%hx %hhx", &cam_acc.addr, (unsigned char *)&cam_acc.data); cam_acc.data_sz = 1; zvideo = &zdev->zdev_videos[zynq_sysfs_cam]; if (zcam_reg_write(zvideo, &cam_acc)) { return sz; } zynq_sysfs_cam_reg = cam_acc.addr; zynq_log("camera %u register 0x%04hx written with 0x%02hhx\n", zynq_sysfs_cam, zynq_sysfs_cam_reg, (unsigned char)cam_acc.data); } else { sscanf(buf, "%hx", &cam_acc.addr); zynq_log("camera %u register changed 0x%04hx -> 0x%04hx\n", zynq_sysfs_cam, zynq_sysfs_cam_reg, cam_acc.addr); zynq_sysfs_cam_reg = cam_acc.addr; } return sz; } /* * read a 16bit camera register value * cat cam_reg16 */ static ssize_t zynq_sysfs_cam_reg16_read(zynq_dev_t *zdev, char *buf) { zynq_video_t *zvideo; zynq_cam_acc_t cam_acc; int len; zvideo = &zdev->zdev_videos[zynq_sysfs_cam]; cam_acc.addr = zynq_sysfs_cam_reg; cam_acc.data = 0; cam_acc.data_sz = 2; if (zcam_reg_read(zvideo, &cam_acc)) { len = sprintf(buf, "failed to read camera %u register 0x%04hx\n", zynq_sysfs_cam, zynq_sysfs_cam_reg); return len; } len = sprintf(buf, "camera %u register 0x%04hx = 0x%04hx\n", zynq_sysfs_cam, zynq_sysfs_cam_reg, (unsigned short)cam_acc.data); return len; } /* * echo <reg> <val> > cam_reg16 * echo <reg> > cam_reg16 */ static ssize_t zynq_sysfs_cam_reg16_set(zynq_dev_t *zdev, const char *buf, size_t sz) { zynq_video_t *zvideo; zynq_cam_acc_t cam_acc; if (strchr(buf, ' ')) { sscanf(buf, "%hx %hx", &cam_acc.addr, (unsigned short *)&cam_acc.data); cam_acc.data_sz = 2; zvideo = &zdev->zdev_videos[zynq_sysfs_cam]; if (zcam_reg_write(zvideo, &cam_acc)) { return sz; } zynq_sysfs_cam_reg = cam_acc.addr; zynq_log("camera %u register 0x%04hx written with 0x%04hx\n", zynq_sysfs_cam, zynq_sysfs_cam_reg, (unsigned short)cam_acc.data); } else { sscanf(buf, "%hx", &cam_acc.addr); zynq_log("camera %u register changed 0x%04hx -> 0x%04hx\n", zynq_sysfs_cam, zynq_sysfs_cam_reg, cam_acc.addr); zynq_sysfs_cam_reg = cam_acc.addr; } return sz; } #define INDENT 2 #define ALIGNMENT ZYNQ_STATS_LABEL_LEN static ssize_t zynq_sysfs_list_stats(char *buf, zynq_stats_t *stats, int num) { ssize_t len = 0; int padding; int i; for (i = 0; i < num; i++) { padding = ALIGNMENT - strlen(stats[i].label); padding = (padding < 0) ? 0 : padding; len += sprintf(buf + len, "%*c%s%*c %7lu\n", INDENT, ' ', stats[i].label, padding, ' ', stats[i].cnt); } return len; } static ssize_t zynq_sysfs_chan_stats_show(zynq_dev_t *zdev, char *buf) { zynq_chan_t *zchan; zynq_can_t *zcan; zynq_video_t *zvideo; ssize_t len = 0; zchan = zdev->zdev_chans + zynq_sysfs_chan; switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: zcan = (zynq_can_t *)zchan->zchan_dev; len += sprintf(buf + len, "Channel %d, can_ip %d, /dev/zynq_can%u:\n", zchan->zchan_num, zcan->zcan_ip_num, zchan->zdev->zdev_can_num_start + zcan->zcan_ip_num); len += zynq_sysfs_list_stats(buf + len, zchan->stats, CHAN_STATS_NUM); len += zynq_sysfs_list_stats(buf + len, zcan->stats, CAN_STATS_NUM); break; case ZYNQ_CHAN_VIDEO: zvideo = (zynq_video_t *)zchan->zchan_dev; len += sprintf(buf + len, "Channel %d, vid %d, /dev/video%d:\n", zchan->zchan_num, zvideo->index, zvideo->vdev.num); len += zynq_sysfs_list_stats(buf + len, zchan->stats, CHAN_STATS_NUM); len += zynq_sysfs_list_stats(buf + len, zvideo->stats, VIDEO_STATS_NUM); break; default: break; } return len; } static ssize_t zynq_sysfs_stats_show(zynq_dev_t *zdev, char *buf) { zynq_chan_t *zchan; zynq_can_t *zcan; zynq_video_t *zvideo; zynq_stats_t *stats; int vcnt; ssize_t len = 0; int padding; int i, j; len += sprintf(buf + len, "General:\n"); len += zynq_sysfs_list_stats(buf + len, zdev->stats, DEV_STATS_NUM); if (zynq_trace_param & ZYNQ_TRACE_GPS) { long drift = 0; long period = zdev->zdev_gps_ts.tv_sec - zdev->zdev_gps_ts_first.tv_sec; if (period > 0) { long total = zdev->zdev_sys_drift; if (total < 0) { total = -total; } drift = total / period; if ((total - (drift * period)) > ((drift + 1) * period - total)) { drift++; } if (zdev->zdev_sys_drift < 0) { drift = -drift; } } len += sprintf(buf + len, "%*c%s%*c %7ld\n", INDENT, ' ', "SYS time drift", ALIGNMENT - 14, ' ', drift); } /* Print CAN channel statistics */ len += sprintf(buf + len, "\nCAN Channels:%*c", ALIGNMENT + INDENT - 13, ' '); for (j = 0; j < zdev->zdev_can_cnt; j++) { zcan = &zdev->zdev_cans[j]; len += sprintf(buf + len, " can%u", zdev->zdev_can_num_start + zcan->zcan_ip_num); } for (i = 0; i < CHAN_STATS_NUM; i++) { stats = &zdev->zdev_cans[0].zchan->stats[i]; padding = ALIGNMENT - strlen(stats->label); padding = (padding < 0) ? 0 : padding; len += sprintf(buf + len, "\n%*c%s%*c", INDENT, ' ', stats->label, padding, ' '); for (j = 0; j < zdev->zdev_can_cnt; j++) { zchan = zdev->zdev_cans[j].zchan; len += sprintf(buf + len, " %7lu", zchan->stats[i].cnt); } } for (i = 0; i < CAN_STATS_NUM; i++) { stats = &zdev->zdev_cans[0].stats[i]; padding = ALIGNMENT - strlen(stats->label); padding = (padding < 0) ? 0 : padding; len += sprintf(buf + len, "\n%*c%s%*c", INDENT, ' ', stats->label, padding, ' '); for (j = 0; j < zdev->zdev_can_cnt; j++) { zcan = &zdev->zdev_cans[j]; len += sprintf(buf + len, " %7lu", zcan->stats[i].cnt); } } len += sprintf(buf + len, "\n"); vcnt = 0; for (j = 0; j < zdev->zdev_video_cnt; j++) { zvideo = &zdev->zdev_videos[j]; if (video_is_registered(&zvideo->vdev)) { vcnt++; } } if (vcnt == 0) { return len; } /* Print Video channel statistics */ len += sprintf(buf + len, "\nVideo Channels:%*c", ALIGNMENT + INDENT - 15, ' '); for (j = 0; j < zdev->zdev_video_cnt; j++) { zvideo = &zdev->zdev_videos[j]; if (!video_is_registered(&zvideo->vdev)) { continue; } padding = (zvideo->vdev.num < 10) ? 2 : 1; len += sprintf(buf + len, "%*cvideo%d", padding, ' ', zvideo->vdev.num); } for (i = 0; i < CHAN_STATS_NUM; i++) { stats = &zdev->zdev_videos[0].zchan->stats[i]; padding = ALIGNMENT - strlen(stats->label); padding = (padding < 0) ? 0 : padding; len += sprintf(buf + len, "\n%*c%s%*c", INDENT, ' ', stats->label, padding, ' '); for (j = 0; j < zdev->zdev_video_cnt; j++) { zvideo = &zdev->zdev_videos[j]; if (!video_is_registered(&zvideo->vdev)) { continue; } zchan = zvideo->zchan; len += sprintf(buf + len, " %7lu", zchan->stats[i].cnt); } } for (i = 0; i < VIDEO_STATS_NUM; i++) { stats = &zdev->zdev_videos[0].stats[i]; padding = ALIGNMENT - strlen(stats->label); padding = (padding < 0) ? 0 : padding; len += sprintf(buf + len, "\n%*c%s%*c", INDENT, ' ', stats->label, padding, ' '); for (j = 0; j < zdev->zdev_video_cnt; j++) { zvideo = &zdev->zdev_videos[j]; if (!video_is_registered(&zvideo->vdev)) { continue; } len += sprintf(buf + len, " %7lu", zvideo->stats[i].cnt); } } len += sprintf(buf + len, "\n"); return len; } /* * echo 1 > cam_change_config */ static ssize_t zynq_sysfs_cam_change_config(zynq_dev_t *zdev, const char *buf, size_t sz) { zynq_video_t *zvideo; int data; sscanf(buf, "%d", &data); if (data != 0) { zvideo = &zdev->zdev_videos[zynq_sysfs_cam]; (void) zcam_change_config(zvideo); } return sz; } struct zynq_sysfs_attr { struct attribute attr; ssize_t (*show)(zynq_dev_t *zdev, char *buf); ssize_t (*store)(zynq_dev_t *zdev, const char *buf, size_t sz); }; #define TO_ZYNQ_DEV_ATTR(x) container_of(x, struct zynq_sysfs_attr, attr) #define SET_ZYNQ_DEV_ATTR(name, mode, show, store) \ static struct zynq_sysfs_attr zynq_sysfs_attr_##name = \ __ATTR(name, mode, show, store) SET_ZYNQ_DEV_ATTR(num_can_ip, 0440, zynq_sysfs_num_can_ip_show, NULL); SET_ZYNQ_DEV_ATTR(num_chan, 0440, zynq_sysfs_num_chan_show, NULL); SET_ZYNQ_DEV_ATTR(can_ip, 0660, zynq_sysfs_can_ip_read, zynq_sysfs_can_ip_set); SET_ZYNQ_DEV_ATTR(chan, 0660, zynq_sysfs_chan_read, zynq_sysfs_chan_set); SET_ZYNQ_DEV_ATTR(g_reg_value, 0660, zynq_sysfs_g_reg_read, zynq_sysfs_g_reg_set); SET_ZYNQ_DEV_ATTR(i2c_bus, 0660, zynq_sysfs_i2c_bus_read, zynq_sysfs_i2c_bus_set); SET_ZYNQ_DEV_ATTR(i2c_reg_value, 0660, zynq_sysfs_i2c_reg_read, zynq_sysfs_i2c_reg_write); SET_ZYNQ_DEV_ATTR(i2c_reg16_value, 0660, zynq_sysfs_i2c_reg16_read, zynq_sysfs_i2c_reg16_write); SET_ZYNQ_DEV_ATTR(chan_reg_value, 0660, zynq_sysfs_chan_reg_read, zynq_sysfs_chan_reg_set); SET_ZYNQ_DEV_ATTR(can_ip_reg_value, 0660, zynq_sysfs_can_ip_reg_read, zynq_sysfs_can_ip_reg_set); SET_ZYNQ_DEV_ATTR(can_ip_test, 0220, NULL, zynq_sysfs_can_ip_test); SET_ZYNQ_DEV_ATTR(can_ip_hi_test, 0220, NULL, zynq_sysfs_can_ip_hi_test); SET_ZYNQ_DEV_ATTR(can_test, 0220, NULL, zynq_sysfs_can_test); SET_ZYNQ_DEV_ATTR(tx_desc, 0660, zynq_sysfs_tx_desc_read, zynq_sysfs_tx_desc_set); SET_ZYNQ_DEV_ATTR(chan_tx_info, 0440, zynq_sysfs_chan_tx_info_show, NULL); SET_ZYNQ_DEV_ATTR(chan_rx_info, 0440, zynq_sysfs_chan_rx_info_show, NULL); SET_ZYNQ_DEV_ATTR(chan_pio_info, 0440, zynq_sysfs_chan_pio_info_show, NULL); SET_ZYNQ_DEV_ATTR(cam, 0660, zynq_sysfs_cam_read, zynq_sysfs_cam_set); SET_ZYNQ_DEV_ATTR(cam_reg8, 0660, zynq_sysfs_cam_reg8_read, zynq_sysfs_cam_reg8_set); SET_ZYNQ_DEV_ATTR(cam_reg16, 0660, zynq_sysfs_cam_reg16_read, zynq_sysfs_cam_reg16_set); SET_ZYNQ_DEV_ATTR(chan_stats, 0440, zynq_sysfs_chan_stats_show, NULL); SET_ZYNQ_DEV_ATTR(stats, 0440, zynq_sysfs_stats_show, NULL); SET_ZYNQ_DEV_ATTR(cam_change_config, 0220, NULL, zynq_sysfs_cam_change_config); static struct attribute *zynq_sysfs_attrs[] = { &zynq_sysfs_attr_num_can_ip.attr, &zynq_sysfs_attr_num_chan.attr, &zynq_sysfs_attr_can_ip.attr, &zynq_sysfs_attr_chan.attr, &zynq_sysfs_attr_g_reg_value.attr, &zynq_sysfs_attr_i2c_bus.attr, &zynq_sysfs_attr_i2c_reg_value.attr, &zynq_sysfs_attr_i2c_reg16_value.attr, &zynq_sysfs_attr_chan_reg_value.attr, &zynq_sysfs_attr_can_ip_reg_value.attr, &zynq_sysfs_attr_can_ip_test.attr, &zynq_sysfs_attr_can_ip_hi_test.attr, &zynq_sysfs_attr_can_test.attr, &zynq_sysfs_attr_tx_desc.attr, &zynq_sysfs_attr_chan_tx_info.attr, &zynq_sysfs_attr_chan_rx_info.attr, &zynq_sysfs_attr_chan_pio_info.attr, &zynq_sysfs_attr_cam.attr, &zynq_sysfs_attr_cam_reg8.attr, &zynq_sysfs_attr_cam_reg16.attr, &zynq_sysfs_attr_chan_stats.attr, &zynq_sysfs_attr_stats.attr, &zynq_sysfs_attr_cam_change_config.attr, NULL }; static struct attribute *zynq_sysfs_fw_attrs[] = { &zynq_sysfs_attr_g_reg_value.attr, &zynq_sysfs_attr_can_ip_reg_value.attr, NULL }; #define TO_ZYNQ_DEV(x) container_of(x, zynq_dev_t, zdev_kobj) static ssize_t zynq_show_sysfs(struct kobject *kobj, struct attribute *attr, char *buf) { struct zynq_sysfs_attr *a = TO_ZYNQ_DEV_ATTR(attr); zynq_dev_t *zdev = TO_ZYNQ_DEV(kobj); return a->show ? a->show(zdev, buf) : 0; } static ssize_t zynq_store_sysfs(struct kobject *kobj, struct attribute *attr, const char *buf, size_t sz) { struct zynq_sysfs_attr *a = TO_ZYNQ_DEV_ATTR(attr); zynq_dev_t *zdev = TO_ZYNQ_DEV(kobj); return a->store ? a->store(zdev, buf, sz) : 0; } static struct sysfs_ops zynq_sysfs_ops = { .show = zynq_show_sysfs, .store = zynq_store_sysfs }; struct kobj_type zynq_kobj_type = { .sysfs_ops = &zynq_sysfs_ops, .default_attrs = zynq_sysfs_attrs }; struct kobj_type zynq_kobj_fw_type = { .sysfs_ops = &zynq_sysfs_ops, .default_attrs = zynq_sysfs_fw_attrs }; void zynq_sysfs_fini(zynq_dev_t *zdev) { if (zdev == NULL) { return; } kobject_put(&zdev->zdev_kobj); kobject_del(&zdev->zdev_kobj); } int zynq_sysfs_init(zynq_dev_t *zdev) { int ret; if (zdev == NULL) { return (-1); } if (zynq_fwupdate_param) { ret = kobject_init_and_add(&zdev->zdev_kobj, &zynq_kobj_fw_type, NULL, zdev->zdev_name); } else { ret = kobject_init_and_add(&zdev->zdev_kobj, &zynq_kobj_type, NULL, zdev->zdev_name); } if (ret) { zynq_err("%s: failed to init and add kobj %d.\n", __FUNCTION__, ret); return (ret); } zynq_trace(ZYNQ_TRACE_SYSFS, "%s: created /sys/%s\n", __FUNCTION__, zdev->zdev_name); return (0); }
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_debug.h
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _BASA_DEBUG_H_ #define _BASA_DEBUG_H_ /* ------------------------------------------------------------------------ * Debugging, printing and logging */ #define ZYNQ_TRACE_PROBE (1 << 0) #define ZYNQ_TRACE_CHAN (1 << 1) #define ZYNQ_TRACE_CAN (1 << 2) #define ZYNQ_TRACE_CAN_PIO (1 << 3) #define ZYNQ_TRACE_CAN_MSG (1 << 4) #define ZYNQ_TRACE_SYSFS (1 << 5) #define ZYNQ_TRACE_FW (1 << 6) #define ZYNQ_TRACE_GPS (1 << 7) #define ZYNQ_TRACE_VIDEO (1 << 8) #define ZYNQ_TRACE_INTR (1 << 9) #define ZYNQ_TRACE_STATS (1 << 10) #define ZYNQ_TRACE_REG (1 << 29) #define ZYNQ_TRACE_BUF (1 << 30) #define ZYNQ_TRACE_ERR (1 << 31) #define zynq_trace(flag, msg...) \ do { \ if (zynq_trace_param & flag) \ printk(KERN_DEBUG ZYNQ_DRV_NAME ": " msg); \ } while (0) #define zynq_warn(msg...) \ printk(KERN_WARNING ZYNQ_DRV_NAME ": " msg) #define zynq_err(msg...) \ printk(KERN_ERR ZYNQ_DRV_NAME ": " msg) #define zynq_log(msg...) \ printk(KERN_INFO ZYNQ_DRV_NAME ": " msg) #ifdef ZYNQ_DEBUG #define ASSERT(x) \ if (!(x)) { \ printk(KERN_WARNING "ASSERT FAILED %s:%d: %s\n", \ __FILE__, __LINE__, #x); \ } #else #define ASSERT(x) #endif #define ZYNQ_STATS_LOGX(p, id, count, interval) \ if (zynq_stats_log(&(p)->stats[id], count, interval)) { \ zynq_err("%s: WARNING! %s, %lu\n", \ (p)->prefix, (p)->stats[id].label, \ (p)->stats[id].cnt); \ } #define ZYNQ_STATS_LOG(p, id) ZYNQ_STATS_LOGX(p, id, 1, -1) #define ZYNQ_STATS(p, id) ((p)->stats[id].cnt++) #define ZYNQ_LOG_PREFIX_LEN 32 #define ZYNQ_STATS_LABEL_LEN 24 typedef struct zynq_stats { unsigned long cnt; /* count of errors */ unsigned long ts; /* jiffies of last report */ const char *label; } zynq_stats_t; extern int zynq_stats_log(zynq_stats_t *stats, int count, int interval); extern unsigned int zynq_trace_param; extern unsigned int zynq_bringup_param; #endif /* _BASA_DEBUG_H_ */
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_chan.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/module.h> #include <linux/delay.h> #include <linux/kthread.h> #include "basa.h" static const char zchan_stats_label[CHAN_STATS_NUM][ZYNQ_STATS_LABEL_LEN] = { "Rx interrupt", "Tx interrupt", "Rx error interrupt", "Tx error interrupt", "Rx drop", "Rx count", "Tx count" }; /* * channel H/W reset */ static void zchan_reset(zynq_chan_t *zchan) { zchan_reg_write(zchan, ZYNQ_CH_DMA_CONTROL, ZYNQ_CH_DMA_RD_STOP | ZYNQ_CH_DMA_WR_STOP); mdelay(1); zchan_reg_write(zchan, ZYNQ_CH_RESET, ZYNQ_CH_DMA_RESET_EN); zchan_reg_write(zchan, ZYNQ_CH_RESET, 0); mdelay(1); } /* * read the H/W Tx head index */ static inline u32 zchan_tx_read_head(zchan_tx_ring_t *zchan_tx) { zynq_chan_t *zchan = zchan_tx->zchan; u64 tx_head_dma; u32 tx_head = zchan_tx->zchan_tx_head; tx_head_dma = zchan_reg_read(zchan, ZYNQ_CH_TX_HEAD_HI); tx_head_dma <<= 32; tx_head_dma |= zchan_reg_read(zchan, ZYNQ_CH_TX_HEAD_LO); if (tx_head_dma >= zchan_tx->zchan_tx_dma) { tx_head = (tx_head_dma - zchan_tx->zchan_tx_dma) / sizeof(zchan_tx_desc_t); if (tx_head >= zchan_tx->zchan_tx_num) { zynq_err("%d ch %d %s bad index: tx_head=%u, " "zchan_tx_num=%u\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, tx_head, zchan_tx->zchan_tx_num); tx_head = zchan_tx->zchan_tx_head; } } else { zynq_err("%d ch %d %s failed: tx_head_dma=0x%llx, zchan_tx_dma=" "0x%llx\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, tx_head_dma, zchan_tx->zchan_tx_dma); } return tx_head; } /* * write the H/W Tx tail index */ static inline void zchan_tx_write_tail(zchan_tx_ring_t *zchan_tx, u32 tail_index) { zynq_chan_t *zchan = zchan_tx->zchan; u64 tx_tail_dma; if (tail_index >= zchan_tx->zchan_tx_num) { zynq_err("%d ch %d %s failed: bad tail_index=x%x zchan_tx_num=" "%u\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, tail_index, zchan_tx->zchan_tx_num); return; } tx_tail_dma = zchan_tx->zchan_tx_dma; tx_tail_dma += tail_index * sizeof(zchan_tx_desc_t); zchan_reg_write(zchan, ZYNQ_CH_TX_TAIL_HI, HI32(tx_tail_dma)); zchan_reg_write(zchan, ZYNQ_CH_TX_TAIL_LO, LO32(tx_tail_dma)); zchan_tx->zchan_tx_tail = tail_index; zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s done, tx_tail=%d, " "tx_tail_dma=0x%llx\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, tail_index, tx_tail_dma); } int zchan_tx_one_msg(zynq_chan_t *zchan, void *msg, u32 msgsz) { zchan_tx_ring_t *zchan_tx = &zchan->zchan_tx_ring; u32 tx_head, tx_tail, tx_next, tx_mask; zchan_buf_t *bufp; zchan_tx_desc_t *descp; /* currently only used for CAN message transmit */ if (msgsz > zchan_tx->zchan_tx_bufsz) { zynq_err("%d ch %d %s failed: too large msgsz %u, " "need to be less than %u\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, msgsz, zchan_tx->zchan_tx_bufsz); return BCAN_FAIL; } spin_lock(&zchan_tx->zchan_tx_lock); tx_mask = zchan_tx->zchan_tx_num - 1; tx_head = zchan_tx->zchan_tx_head; tx_tail = zchan_tx->zchan_tx_tail; tx_next = (tx_tail + 1) & tx_mask; /* tx ring is full */ if (tx_next == tx_head) { zynq_err("%d ch %d %s failed: ring FULL tx_head=%u, " "tx_tail=%u\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, tx_head, tx_tail); spin_unlock(&zchan_tx->zchan_tx_lock); return BCAN_DEV_BUSY; } bufp = zchan_tx->zchan_tx_bufp + tx_tail; memcpy(bufp->zchan_bufp, msg, msgsz); pci_dma_sync_single_for_device(zchan->zdev->zdev_pdev, bufp->zchan_buf_dma, msgsz, PCI_DMA_TODEVICE); descp = zchan_tx->zchan_tx_descp + tx_tail; descp->tx_len = msgsz; if (descp->tx_addr != 0) { zynq_err("%d ch %d %s: desc %d buffer is not cleared\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, tx_tail); } descp->tx_addr = bufp->zchan_buf_dma; zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s Tx desc %d msg %lu: " "tx_len=%d, tx_addr=0x%p, tx_addr_dma=0x%llx, msgid_len=0x%llx, " "data[0-7]=0x%llx\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, tx_tail, zchan->stats[CHAN_STATS_TX].cnt, descp->tx_len, bufp, descp->tx_addr, *(u64 *)bufp->zchan_bufp, *((u64 *)bufp->zchan_bufp + 1)); zchan_tx_write_tail(zchan_tx, tx_next); ZYNQ_STATS(zchan, CHAN_STATS_TX); spin_unlock(&zchan_tx->zchan_tx_lock); return 0; } void zchan_rx_off2addr(zchan_rx_tbl_t *zchan_rx, u32 rx_off, void **virt_addr, void **phy_addr) { int pdt_entry, pt_entry; zchan_rx_pt_t *rx_ptp; zchan_buf_t *rx_buf; pdt_entry = ZCHAN_RX_PDT_ENTRY(zchan_rx, rx_off); rx_ptp = zchan_rx->zchan_rx_ptp + pdt_entry; pt_entry = ZCHAN_RX_PT_ENTRY(zchan_rx, rx_off); rx_buf = rx_ptp->zchan_rx_pt_bufp + pt_entry; if (virt_addr != NULL) { *virt_addr = (void *)((uintptr_t)rx_buf->zchan_bufp + ZCHAN_RX_BUF_OFFSET(zchan_rx, rx_off)); zynq_trace(ZYNQ_TRACE_BUF, "%d ch %d %s rx_off=0x%x, " "virt_addr=0x%p, pdt_entry=%d, rx_ptp=%p, pt_entry=%d, " "rx_buf = %p\n", ZYNQ_INST(zchan_rx->zchan), zchan_rx->zchan->zchan_num, __FUNCTION__, rx_off, *virt_addr, pdt_entry, rx_ptp, pt_entry, rx_buf); } if (phy_addr != NULL) { *phy_addr = (void *)(rx_buf->zchan_buf_dma + ZCHAN_RX_BUF_OFFSET(zchan_rx, rx_off)); zynq_trace(ZYNQ_TRACE_BUF, "%d ch %d %s rx_off=0x%x, " "phy_addr=0x%p\n", ZYNQ_INST(zchan_rx->zchan), zchan_rx->zchan->zchan_num, __FUNCTION__, rx_off, *phy_addr); } } /* * pci_alloc_consistent returns only 32-bit DMA address. Since Zynq device is * 64-bit access only, this the replacement for 64-bit pci_alloc_consistent. */ void *zchan_alloc_consistent(struct pci_dev *pdev, dma_addr_t *dmap, size_t sz) { return pci_alloc_consistent(pdev, sz, dmap); } void zchan_free_consistent(struct pci_dev *pdev, void *ptr, dma_addr_t dma, size_t sz) { pci_free_consistent(pdev, sz, ptr, dma); } static int zchan_alloc_buf(struct pci_dev *pdev, zchan_buf_t *zchan_buf, size_t bufsz, enum dma_data_direction dmatype) { void *bufp; if (dmatype == PCI_DMA_BIDIRECTIONAL) { bufp = zchan_alloc_consistent(pdev, &zchan_buf->zchan_buf_dma, bufsz); if (bufp == NULL) { zynq_err("%s alloc consistent failed: bufsz=%zd.\n", __FUNCTION__, bufsz); return -1; } zchan_buf->zchan_bufp = bufp; return 0; } if (bufsz < PAGE_SIZE) { bufp = kmalloc(bufsz, GFP_KERNEL); if (bufp == NULL) { zynq_err("%s kmalloc failed: sz=%zd.\n", __FUNCTION__, bufsz); return -1; } if (pdev != NULL) { zchan_buf->zchan_buf_dma = pci_map_single(pdev, bufp, bufsz, dmatype); if (pci_dma_mapping_error(pdev, zchan_buf->zchan_buf_dma)) { kfree(bufp); zynq_err("%s pci map failed: sz=%zd.\n", __FUNCTION__, bufsz); return -1; } } zchan_buf->zchan_bufp = bufp; } else { bufp = alloc_pages(GFP_KERNEL, get_order(bufsz)); if (bufp == NULL) { zynq_err("%s alloc_pages failed: sz=%zd.\n", __FUNCTION__, bufsz); return -1; } if (pdev != NULL) { zchan_buf->zchan_buf_dma = pci_map_page(pdev, bufp, 0, bufsz, dmatype); if (pci_dma_mapping_error(pdev, zchan_buf->zchan_buf_dma)) { __free_pages(bufp, get_order(bufsz)); zynq_err("%s pci map page failed: sz=%zd.\n", __FUNCTION__, bufsz); return -1; } if (zchan_buf->zchan_buf_dma & (bufsz - 1)) { zynq_err("%s dma addr is not bufsz %zd aligned." " virtual addr: 0x%p, dma addr: 0x%llx\n", __FUNCTION__, bufsz, page_address(bufp), zchan_buf->zchan_buf_dma); } } zchan_buf->zchan_buf_page = bufp; zchan_buf->zchan_bufp = page_address(zchan_buf->zchan_buf_page); } return (0); } static void zchan_free_buf(struct pci_dev *pdev, zchan_buf_t *zchan_buf, size_t bufsz, enum dma_data_direction dmatype) { if (dmatype == PCI_DMA_BIDIRECTIONAL) { zchan_free_consistent(pdev, zchan_buf->zchan_bufp, zchan_buf->zchan_buf_dma, bufsz); goto done; } if (bufsz < PAGE_SIZE) { if (pdev != NULL) { pci_unmap_single(pdev, zchan_buf->zchan_buf_dma, bufsz, dmatype); } kfree(zchan_buf->zchan_bufp); } else { if (pdev != NULL) { pci_unmap_page(pdev, zchan_buf->zchan_buf_dma, bufsz, dmatype); } __free_pages(zchan_buf->zchan_buf_page, get_order(bufsz)); } done: zchan_buf->zchan_buf_page = NULL; zchan_buf->zchan_bufp = NULL; zchan_buf->zchan_buf_dma = 0; } static int zchan_init_tx_ring(zynq_chan_t *zchan) { zynq_dev_t *zdev = zchan->zdev; zchan_tx_ring_t *zchan_tx = &zchan->zchan_tx_ring; zchan_buf_t *bufp; size_t size; int num_entries; int bufsz; int i; if (zchan->zchan_type == ZYNQ_CHAN_VIDEO || (zchan->zchan_type == ZYNQ_CHAN_CAN && !zdev->zcan_tx_dma)) { return 0; } bufsz = ZCHAN_BUF_SIZE; num_entries = ZCHAN_TX_ENTRIES_CAN; /* allocate tx descriptor ring */ size = num_entries * sizeof(zchan_tx_desc_t); zchan_tx->zchan_tx_descp = zchan_alloc_consistent(zdev->zdev_pdev, &zchan_tx->zchan_tx_dma, size); if (zchan_tx->zchan_tx_descp == NULL) { zynq_err("%d ch %d %s failed to alloc descriptor ring.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); return -1; } zchan_tx->zchan_tx_size = size; zchan_tx->zchan_tx_num = num_entries; /* allocate tx buffer array */ size = num_entries * sizeof(zchan_buf_t); bufp = kzalloc(size, GFP_KERNEL); if (bufp == NULL) { zchan_free_consistent(zdev->zdev_pdev, zchan_tx->zchan_tx_descp, zchan_tx->zchan_tx_dma, zchan_tx->zchan_tx_size); zynq_err("%d ch %d %s failed to alloc buffer array.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); return -1; } zchan_tx->zchan_tx_bufp = bufp; /* allocate tx buffers */ for (i = 0; i < num_entries; i++, bufp++) { if (zchan_alloc_buf(zdev->zdev_pdev, bufp, bufsz, PCI_DMA_TODEVICE)) { zynq_err("%d ch %d %s failed to alloc buf.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); goto fail; } } zchan_tx->zchan_tx_bufsz = bufsz; spin_lock_init(&zchan_tx->zchan_tx_lock); /* init Tx h/w */ zchan_reg_write(zchan, ZYNQ_CH_DMA_CONFIG, ZYNQ_CH_DMA_TX_EN); zchan_reg_write(zchan, ZYNQ_CH_TX_HEAD_HI, HI32(zchan_tx->zchan_tx_dma)); zchan_reg_write(zchan, ZYNQ_CH_TX_HEAD_LO, LO32(zchan_tx->zchan_tx_dma)); zchan_reg_write(zchan, ZYNQ_CH_TX_TAIL_HI, HI32(zchan_tx->zchan_tx_dma)); zchan_reg_write(zchan, ZYNQ_CH_TX_TAIL_LO, LO32(zchan_tx->zchan_tx_dma)); zchan_reg_write(zchan, ZYNQ_CH_TX_RING_SZ, zchan_tx->zchan_tx_size); zchan_reg_write(zchan, ZYNQ_CH_DMA_CONTROL, ZYNQ_CH_DMA_RD_START); zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s done.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); return 0; fail: while (i--) { bufp--; zchan_free_buf(zdev->zdev_pdev, bufp, bufsz, PCI_DMA_TODEVICE); } kfree(zchan_tx->zchan_tx_bufp); zchan_tx->zchan_tx_bufp = NULL; zchan_free_consistent(zdev->zdev_pdev, zchan_tx->zchan_tx_descp, zchan_tx->zchan_tx_dma, zchan_tx->zchan_tx_size); zchan_tx->zchan_tx_descp = NULL; return (-1); } static void zchan_fini_tx_ring(zynq_chan_t *zchan) { zynq_dev_t *zdev = zchan->zdev; zchan_tx_ring_t *zchan_tx = &zchan->zchan_tx_ring; zchan_buf_t *bufp; int i; if (zchan->zchan_type == ZYNQ_CHAN_VIDEO || (zchan->zchan_type == ZYNQ_CHAN_CAN && !zdev->zcan_tx_dma)) { return; } /* disable tx in h/w */ zchan_reg_write(zchan, ZYNQ_CH_DMA_CONTROL, ZYNQ_CH_DMA_RD_STOP); mdelay(10); zchan_reg_write(zchan, ZYNQ_CH_TX_RING_SZ, 0); zchan_reg_write(zchan, ZYNQ_CH_TX_HEAD_HI, 0); zchan_reg_write(zchan, ZYNQ_CH_TX_HEAD_LO, 0); zchan_reg_write(zchan, ZYNQ_CH_TX_TAIL_HI, 0); zchan_reg_write(zchan, ZYNQ_CH_TX_TAIL_LO, 0); /* free tx buffers */ bufp = zchan_tx->zchan_tx_bufp; for (i = 0; i < zchan_tx->zchan_tx_num; i++, bufp++) { zchan_free_buf(zdev->zdev_pdev, bufp, zchan_tx->zchan_tx_bufsz, PCI_DMA_TODEVICE); } kfree(zchan_tx->zchan_tx_bufp); zchan_tx->zchan_tx_bufp = NULL; zchan_free_consistent(zdev->zdev_pdev, zchan_tx->zchan_tx_descp, zchan_tx->zchan_tx_dma, zchan_tx->zchan_tx_size); zchan_tx->zchan_tx_descp = NULL; zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s done.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); } static int zchan_init_rx_tbl(zynq_chan_t *zchan) { zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; zynq_video_t *zvideo; struct pci_dev *pdev = zchan->zdev->zdev_pdev; enum dma_data_direction dmatype; u32 pdt_entries; size_t pdt_size; size_t bufsz; u64 *rx_pdtp; /* page directory table array */ zchan_rx_pt_t *rx_ptp; /* page table array */ u64 *rx_pt; /* page table */ zchan_buf_t *bufp; int i, j; zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: zchan=0x%p\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan); switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: if (!zchan->zdev->zcan_rx_dma) { zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: DMA mode is not supported\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); return 0; } dmatype = PCI_DMA_BIDIRECTIONAL; bufsz = ZCHAN_BUF_SIZE; pdt_entries = ZCHAN_RX_PDT_ENTRIES_CAN; break; case ZYNQ_CHAN_VIDEO: zvideo = (zynq_video_t *)zchan->zchan_dev; if (zynq_video_zero_copy) { /* * For zero-copy, the DMA buffers are not initialized * here. Instead they are initialized and mapped when * the streaming is started. */ return 0; } dmatype = PCI_DMA_FROMDEVICE; bufsz = ZCHAN_BUF_SIZE; pdt_entries = CEILING(zynq_video_buf_num * CEILING(zvideo->format.sizeimage, ZCHAN_BUF_SIZE), ZCHAN_RX_PT_ENTRIES); break; default: zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: unsupported channel type %d\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan->zchan_type); return 0; } /* allocate page directory table first */ pdt_size = pdt_entries * sizeof(u64); rx_pdtp = zchan_alloc_consistent(pdev, &zchan_rx->zchan_rx_pdt_dma, pdt_size); if (rx_pdtp == NULL) { zynq_err("%d ch %d %s failed to alloc page directory table.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); return -1; } zchan_rx->zchan_rx_pdt_num = pdt_entries; zchan_rx->zchan_rx_pdt = rx_pdtp; /* allocate the array of zchan_rx_pt_t */ rx_ptp = kzalloc(pdt_entries * sizeof(zchan_rx_pt_t), GFP_KERNEL); if (rx_ptp == NULL) { zchan_free_consistent(pdev, zchan_rx->zchan_rx_pdt, zchan_rx->zchan_rx_pdt_dma, pdt_size); zynq_err("%d ch %d, %s failed to alloc page table array.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); return -1; } zchan_rx->zchan_rx_ptp = rx_ptp; zchan_rx->zchan_rx_bufsz = bufsz; for (i = 0; i < zchan_rx->zchan_rx_pdt_num; i++, rx_pdtp++, rx_ptp++) { /* allocate each page table */ rx_pt = zchan_alloc_consistent(pdev, &rx_ptp->zchan_rx_pt_dma, ZCHAN_RX_PT_SIZE); if (rx_pt == NULL) { zynq_err("%d ch %d %s failed to alloc a page table.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); goto pt_alloc_fail; } rx_ptp->zchan_rx_pt = rx_pt; /* init the page directory table entry */ *rx_pdtp = rx_ptp->zchan_rx_pt_dma; /* allocate the array of zchan_buf_t */ bufp = kzalloc(ZCHAN_RX_PT_ENTRIES * sizeof(zchan_buf_t), GFP_KERNEL); if (bufp == NULL) { zchan_free_consistent(pdev, rx_ptp->zchan_rx_pt, rx_ptp->zchan_rx_pt_dma, ZCHAN_RX_PT_SIZE); zynq_err("%d ch %d %s failed to alloc a Rx buffer array" ".\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); goto pt_alloc_fail; } rx_ptp->zchan_rx_pt_bufp = bufp; rx_ptp->zchan_rx_pt_buf_num = ZCHAN_RX_PT_ENTRIES; /* allocate the buffer for each page entry */ for (j = 0; j < ZCHAN_RX_PT_ENTRIES; j++, rx_pt++, bufp++) { if (zchan_alloc_buf(pdev, bufp, bufsz, dmatype)) { zynq_err("%d ch %d %s failed to alloc a Rx " "buffer.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); goto buf_alloc_fail; } if (dmatype == PCI_DMA_FROMDEVICE) { pci_dma_sync_single_for_device( zchan->zdev->zdev_pdev, bufp->zchan_buf_dma, bufsz, PCI_DMA_FROMDEVICE); } /* init the page table entry */ *rx_pt = bufp->zchan_buf_dma; zynq_trace(ZYNQ_TRACE_BUF, "ch %d %s alloc Rx buffer " "%d = 0x%p(0x%llx)\n", zchan->zchan_num, __FUNCTION__, j, bufp->zchan_bufp, bufp->zchan_buf_dma); } } zchan_rx->zchan_rx_pt_entries = pdt_entries * ZCHAN_RX_PT_ENTRIES; zchan_rx->zchan_rx_size = pdt_entries * ZCHAN_RX_PT_ENTRIES * bufsz; zchan_rx->zchan_rx_pdt_shift = fls(ZCHAN_RX_PT_ENTRIES * bufsz) - 1; zchan_rx->zchan_rx_pt_shift = fls(bufsz) - 1; zchan_rx->zchan_rx_pt_mask = ZCHAN_RX_PT_ENTRIES - 1; zchan_rx->zchan_rx_buf_mask = bufsz - 1; spin_lock_init(&zchan_rx->zchan_rx_lock); zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s done: rx_bufsz=%zd, " "rx_buf_mask=0x%x, rx_pdt_num=0x%x, pt_entries=0x%x, rx_size=0x%x, " "rx_pdt_shift=%d, rx_pt_shift=%d, rx_pt_mask=0x%x.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, bufsz, zchan_rx->zchan_rx_buf_mask, zchan_rx->zchan_rx_pdt_num, zchan_rx->zchan_rx_pt_entries, zchan_rx->zchan_rx_size, zchan_rx->zchan_rx_pdt_shift, zchan_rx->zchan_rx_pt_shift, zchan_rx->zchan_rx_pt_mask); /* init Rx h/w */ if (zchan->zchan_type == ZYNQ_CHAN_CAN) { zchan_rx_start(zchan); } return 0; buf_alloc_fail: while (j--) { bufp--; zchan_free_buf(pdev, bufp, bufsz, dmatype); } kfree(rx_ptp->zchan_rx_pt_bufp); zchan_free_consistent(pdev, rx_ptp->zchan_rx_pt, rx_ptp->zchan_rx_pt_dma, ZCHAN_RX_PT_SIZE); pt_alloc_fail: while (i--) { rx_ptp--; bufp = rx_ptp->zchan_rx_pt_bufp; for (j = 0; j < ZCHAN_RX_PT_ENTRIES; j++, bufp++) { zchan_free_buf(pdev, bufp, bufsz, dmatype); } kfree(rx_ptp->zchan_rx_pt_bufp); zchan_free_consistent(pdev, rx_ptp->zchan_rx_pt, rx_ptp->zchan_rx_pt_dma, ZCHAN_RX_PT_SIZE); } kfree(zchan_rx->zchan_rx_ptp); zchan_rx->zchan_rx_ptp = NULL; zchan_free_consistent(pdev, zchan_rx->zchan_rx_pdt, zchan_rx->zchan_rx_pdt_dma, pdt_size); zchan_rx->zchan_rx_pdt = NULL; return -1; } static void zchan_fini_rx_tbl(zynq_chan_t *zchan) { zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; struct pci_dev *pdev = zchan->zdev->zdev_pdev; enum dma_data_direction dmatype; zchan_rx_pt_t *rx_ptp; zchan_buf_t *bufp; int i, j; zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: zchan=0x%p\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan); switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: if (!zchan->zdev->zcan_rx_dma) { return; } dmatype = PCI_DMA_BIDIRECTIONAL; break; case ZYNQ_CHAN_VIDEO: if (zynq_video_zero_copy) { return; } dmatype = PCI_DMA_FROMDEVICE; break; default: return; } /* disable rx in h/w */ zchan_rx_stop(zchan); rx_ptp = zchan_rx->zchan_rx_ptp; for (i = 0; i < zchan_rx->zchan_rx_pdt_num; i++, rx_ptp++) { bufp = rx_ptp->zchan_rx_pt_bufp; for (j = 0; j < rx_ptp->zchan_rx_pt_buf_num; j++, bufp++) { zchan_free_buf(pdev, bufp, zchan_rx->zchan_rx_bufsz, dmatype); } kfree(rx_ptp->zchan_rx_pt_bufp); zchan_free_consistent(pdev, rx_ptp->zchan_rx_pt, rx_ptp->zchan_rx_pt_dma, ZCHAN_RX_PT_SIZE); } kfree(zchan_rx->zchan_rx_ptp); zchan_rx->zchan_rx_ptp = NULL; zchan_free_consistent(zchan->zdev->zdev_pdev, zchan_rx->zchan_rx_pdt, zchan_rx->zchan_rx_pdt_dma, zchan_rx->zchan_rx_pdt_num * sizeof(u64)); zchan_rx->zchan_rx_pdt = NULL; zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s done.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__); } void zchan_rx_start(zynq_chan_t *zchan) { zynq_dev_t *zdev = zchan->zdev; zchan_rx_tbl_t *zchan_rx = &zchan->zchan_rx_tbl; zynq_video_t *zvideo; u32 ch_config; u32 ch_status; u32 last_pt_sz; u32 timeout; u32 i; zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: zchan=0x%p\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan); /* Reset DMA first */ zchan_reset(zchan); /* Setup frame size */ switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: /* Enable DMA mode */ if (zdev->zcan_rx_hw_ts) { ch_config = (ZYNQ_CH_DMA_CAN_HWTS | ZYNQ_CH_DMA_RX_EN); } else { ch_config = ZYNQ_CH_DMA_RX_EN; } zchan_reg_write(zchan, ZYNQ_CH_DMA_CONFIG, ch_config); break; case ZYNQ_CHAN_VIDEO: zvideo = (zynq_video_t *)zchan->zchan_dev; ch_config = zchan_reg_read(zchan, ZYNQ_CH_DMA_CONFIG); ch_config &= ~ZYNQ_CH_DMA_FRAME_SZ_MASK; ch_config |= (zvideo->format.sizeimage << ZYNQ_CH_DMA_FRAME_SZ_OFFSET) & ZYNQ_CH_DMA_FRAME_SZ_MASK; /* Enable frame buffer alignment */ ch_config |= ZYNQ_CH_DMA_FRAME_BUF_ALIGN; /* Enable DMA mode */ ch_config |= ZYNQ_CH_DMA_RX_EN; zchan_reg_write(zchan, ZYNQ_CH_DMA_CONFIG, ch_config); last_pt_sz = (zchan_rx->zchan_rx_pt_entries & zchan_rx->zchan_rx_pt_mask) * sizeof(u64); zchan_reg_write(zchan, ZYNQ_CH_WR_TABLE_CONFIG, last_pt_sz); break; default: return; } zchan_reg_write(zchan, ZYNQ_CH_RX_PDT_HI, HI32(zchan_rx->zchan_rx_pdt_dma)); zchan_reg_write(zchan, ZYNQ_CH_RX_PDT_LO, LO32(zchan_rx->zchan_rx_pdt_dma)); zchan_reg_write(zchan, ZYNQ_CH_RX_PDT_SZ, zchan_rx->zchan_rx_pdt_num * sizeof(u64)); zchan_reg_write(zchan, ZYNQ_CH_RX_TAIL, 0); zchan_reg_write(zchan, ZYNQ_CH_RX_HEAD, 0); zchan_rx->zchan_rx_head = 0; zchan_rx->zchan_rx_tail = 0; zchan_rx->zchan_rx_off = 0; /* Start Rx DMA */ zchan_reg_write(zchan, ZYNQ_CH_DMA_CONTROL, ZYNQ_CH_DMA_WR_START); /* Check DMA ready status */ timeout = zchan_rx->zchan_rx_pdt_num * 10; /* msec */ for (i = 0; i < timeout; i++) { mdelay(1); ch_status = zchan_reg_read(zchan, ZYNQ_CH_DMA_STATUS); if (GET_BITS(ZYNQ_CH_DMA_WR_STATE, ch_status) == ZYNQ_CH_DMA_READY) { zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: DMA ready, wait %ums\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, i); return; } } zynq_err("%d ch %d %s: WARNING! DMA not ready, timeout %ums\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, timeout); } void zchan_rx_stop(zynq_chan_t *zchan) { zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: zchan=0x%p\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan); /* Stop Rx DMA */ zchan_reg_write(zchan, ZYNQ_CH_DMA_CONTROL, ZYNQ_CH_DMA_WR_STOP); mdelay(10); zchan_reg_write(zchan, ZYNQ_CH_RX_PDT_HI, 0); zchan_reg_write(zchan, ZYNQ_CH_RX_PDT_LO, 0); zchan_reg_write(zchan, ZYNQ_CH_RX_PDT_SZ, 0); zchan_reg_write(zchan, ZYNQ_CH_RX_TAIL, 0); zchan_reg_write(zchan, ZYNQ_CH_RX_HEAD, 0); } void zchan_tx_done(zchan_tx_ring_t *zchan_tx) { u32 head, new_head, tx_mask; zchan_tx_desc_t *descp; int idx; head = zchan_tx->zchan_tx_head; new_head = zchan_tx_read_head(zchan_tx); if (head == new_head) { return; } tx_mask = zchan_tx->zchan_tx_num - 1; for (idx = head; idx != new_head; idx = (idx + 1) & tx_mask) { descp = zchan_tx->zchan_tx_descp + idx; descp->tx_addr = 0; } zchan_tx->zchan_tx_head = new_head; zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s done: tx_head=%d\n", ZYNQ_INST(zchan_tx->zchan), zchan_tx->zchan->zchan_num, __FUNCTION__, new_head); } static int zchan_init_dma(zynq_chan_t *zchan) { /* reset DMA first */ zchan_reset(zchan); /* init rx page directory table for Rx buffers */ if (zchan_init_rx_tbl(zchan)) { zynq_err("%d ch %d %s init rx table failed, zchan=0x%p.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan); return -1; } if (zchan->zchan_type == ZYNQ_CHAN_CAN) { /* init tx descriptor ring */ if (zchan_init_tx_ring(zchan)) { zynq_err("%d ch %d %s " "init tx ring failed, zchan=0x%p.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan); zchan_fini_rx_tbl(zchan); return -1; } } zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s done, zchan=0x%p.\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan); return 0; } static void zchan_fini_dma(zynq_chan_t *zchan) { /* disable DMA mode */ zchan_reg_write(zchan, ZYNQ_CH_DMA_CONFIG, 0); mdelay(10); zchan_fini_rx_tbl(zchan); if (zchan->zchan_type == ZYNQ_CHAN_CAN) { zchan_fini_tx_ring(zchan); } } static void zchan_stats_init(zynq_chan_t *zchan) { int i; for (i = 0; i < CHAN_STATS_NUM; i++) { zchan->stats[i].label = zchan_stats_label[i]; } } void zchan_watchdog_complete(zynq_chan_t *zchan) { complete(&zchan->watchdog_completion); } void zchan_err_mask(zynq_chan_t *zchan, uint32_t ch_err) { uint32_t mask_rx; uint32_t mask_tx; uint32_t i; /* Camera link change is never masked */ ch_err &= ~ZYNQ_CH_ERR_CAM_LINK_CHANGE; if (ch_err == 0) { return; } spin_lock(&zchan->zchan_lock); for (i = 0; i < 32; i++) { if ((ch_err & (1 << i)) && (zchan->ts_err[i] == 0)) { zchan->ts_err[i] = jiffies; } } mask_rx = zchan_reg_read(zchan, ZYNQ_CH_ERR_MASK_RX); mask_tx = zchan_reg_read(zchan, ZYNQ_CH_ERR_MASK_TX); zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: " "ch_err_mask_rx=0x%x, ch_err_mask_tx=0x%x, ch_err=0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, mask_rx, mask_tx, ch_err); mask_rx |= ch_err | ZYNQ_CH_ERR_MASK_RX_DEFAULT; mask_tx |= ch_err | ZYNQ_CH_ERR_MASK_TX_DEFAULT; zchan_reg_write(zchan, ZYNQ_CH_ERR_MASK_RX, mask_rx); zchan_reg_write(zchan, ZYNQ_CH_ERR_MASK_TX, mask_tx); zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: " "ch_err_mask_rx=0x%x, ch_err_mask_tx=0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, mask_rx, mask_tx); zchan->watchdog_interval = 100; spin_unlock(&zchan->zchan_lock); zchan_watchdog_complete(zchan); } static void zchan_err_unmask(zynq_chan_t *zchan) { uint32_t ch_err = 0; uint32_t mask_rx; uint32_t mask_tx; uint32_t i; spin_lock(&zchan->zchan_lock); for (i = 0; i < 32; i++) { if ((zchan->ts_err[i] != 0) && (jiffies >= (zchan->ts_err[i] + msecs_to_jiffies(ZCHAN_ERR_THROTTLE)))) { zchan->ts_err[i] = 0; ch_err |= 1 << i; } } if (ch_err == 0) { spin_unlock(&zchan->zchan_lock); return; } mask_rx = zchan_reg_read(zchan, ZYNQ_CH_ERR_MASK_RX); mask_tx = zchan_reg_read(zchan, ZYNQ_CH_ERR_MASK_TX); zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: " "ch_err_mask_rx=0x%x, ch_err_mask_tx=0x%x, ch_err=0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, mask_rx, mask_tx, ch_err); mask_rx &= ~ch_err; mask_rx |= ZYNQ_CH_ERR_MASK_RX_DEFAULT; mask_tx &= ~ch_err; mask_tx |= ZYNQ_CH_ERR_MASK_TX_DEFAULT; zchan_reg_write(zchan, ZYNQ_CH_ERR_MASK_RX, mask_rx); zchan_reg_write(zchan, ZYNQ_CH_ERR_MASK_TX, mask_tx); zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s: " "ch_err_mask_rx=0x%x, ch_err_mask_tx=0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, mask_rx, mask_tx); if ((mask_rx == ZYNQ_CH_ERR_MASK_RX_DEFAULT) && (mask_tx == ZYNQ_CH_ERR_MASK_TX_DEFAULT)) { zchan->watchdog_interval = 1000; } spin_unlock(&zchan->zchan_lock); } static int zchan_watchdog(void *arg) { zynq_chan_t *zchan = (zynq_chan_t *)arg; long result; while (!kthread_should_stop()) { result = wait_for_completion_interruptible_timeout( &zchan->watchdog_completion, msecs_to_jiffies(zchan->watchdog_interval)); if (result < 0) { break; } zchan_err_unmask(zchan); if (zchan->zchan_type == ZYNQ_CHAN_VIDEO) { zvideo_watchdog((zynq_video_t *)zchan->zchan_dev); } if (result > 0) { reinit_completion(&zchan->watchdog_completion); } } return 0; } static void zchan_watchdog_init(zynq_chan_t *zchan) { init_completion(&zchan->watchdog_completion); zchan->watchdog_interval = 1000; zchan->watchdog_taskp = kthread_run(zchan_watchdog, zchan, "zynq channel watchdog thread"); } static void zchan_watchdog_fini(zynq_chan_t *zchan) { complete(&zchan->watchdog_completion); if (zchan->watchdog_taskp) { kthread_stop(zchan->watchdog_taskp); zchan->watchdog_taskp = NULL; } } int zchan_init(zynq_chan_t *zchan) { zynq_can_t *zcan; zynq_video_t *zvideo; snprintf(zchan->prefix, ZYNQ_LOG_PREFIX_LEN, "%d ch%d", ZYNQ_INST(zchan), zchan->zchan_num); zchan_stats_init(zchan); zchan->zchan_reg = zchan->zdev->zdev_bar0 + ZYNQ_CHAN_REG_OFFSET * zchan->zchan_num; spin_lock_init(&zchan->zchan_lock); /* channel specific init */ switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: zcan = (zynq_can_t *)zchan->zchan_dev; if (zchan_init_dma(zchan)) { return -1; } if (zcan_init(zcan)) { zchan_fini_dma(zchan); return -1; } zchan_watchdog_init(zchan); break; case ZYNQ_CHAN_VIDEO: zvideo = (zynq_video_t *)zchan->zchan_dev; if (zvideo_init(zvideo)) { return -1; } if (zchan_init_dma(zchan)) { zvideo_fini(zvideo); return -1; } zchan_watchdog_init(zchan); break; default: break; } zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s done: zchan=%p\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan); return 0; } void zchan_fini(zynq_chan_t *zchan) { switch (zchan->zchan_type) { case ZYNQ_CHAN_CAN: zchan_watchdog_fini(zchan); zcan_fini(zchan->zchan_dev); zchan_fini_dma(zchan); break; case ZYNQ_CHAN_VIDEO: zchan_watchdog_fini(zchan); zvideo_fini(zchan->zchan_dev); zchan_fini_dma(zchan); break; default: break; } zynq_trace(ZYNQ_TRACE_CHAN, "%d ch %d %s done: zchan=%p\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, zchan); }
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_driver.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/init.h> #include <linux/module.h> #include <linux/version.h> #include "basa.h" static const int video_port_map_mr[] = { 1, 2, 3, 4, 5 }; static unsigned int zynq_mr_cnt = 0; zynq_dev_t *zynq_zdev_init(unsigned short zdev_did) { zynq_dev_t *zdev; int can_cnt, video_cnt, chan_cnt; unsigned long video_map, can_map; switch (zdev_did) { case PCI_DEVICE_ID_MOONROVER: chan_cnt = ZYNQ_DMA_CHAN_NUM_MR; video_map = ZYNQ_VIDEO_MAP_MR; can_map = ZYNQ_CAN_MAP_MR; break; default: zynq_err("%s: Unknown Device ID 0x%x\n", __FUNCTION__, zdev_did); return NULL; } if (zynq_fwupdate_param) { switch (zdev_did) { case PCI_DEVICE_ID_MOONROVER: chan_cnt = 0; can_map = 0; video_map = 0; break; default: break; } } video_cnt = hweight_long(video_map); can_cnt = hweight_long(can_map); zynq_trace(ZYNQ_TRACE_PROBE, "%s: chan_cnt = %d, video_cnt = %d, can_cnt = %d\n", __FUNCTION__, chan_cnt, video_cnt, can_cnt); ASSERT(chan_cnt >= (can_cnt + video_cnt)); /* allocate device and channel structure */ zdev = kzalloc(sizeof(zynq_dev_t) + chan_cnt * sizeof(zynq_chan_t) + can_cnt * sizeof(zynq_can_t) + video_cnt * sizeof(zynq_video_t), GFP_KERNEL); if (zdev == NULL) { return NULL; } zdev->zdev_chan_cnt = chan_cnt; zdev->zdev_can_cnt = can_cnt; zdev->zdev_video_cnt = video_cnt; zdev->zdev_can_map = can_map; zdev->zdev_video_map = video_map; zdev->zdev_chans = (zynq_chan_t *)((char *)zdev + sizeof(zynq_dev_t)); zdev->zdev_cans = (zynq_can_t *)((char *)zdev->zdev_chans + chan_cnt * sizeof(zynq_chan_t)); zdev->zdev_videos = (zynq_video_t *)((char *)zdev->zdev_cans + can_cnt * sizeof(zynq_can_t)); return (zdev); } void zynq_check_hw_caps(zynq_dev_t *zdev) { char code_name[ZYNQ_DEV_CODE_NAME_LEN] = { 0 }; const int *video_port_map = NULL; int hw_cap = 0; switch (zdev->zdev_did) { case PCI_DEVICE_ID_MOONROVER: hw_cap = ZYNQ_HW_CAP_CAN | ZYNQ_HW_CAP_GPS | ZYNQ_HW_CAP_TRIGGER | ZYNQ_HW_CAP_FW | ZYNQ_HW_CAP_I2C | ZYNQ_HW_CAP_VIDEO; if (ZDEV_PL_VER(zdev) >= 0x106) { hw_cap |= ZYNQ_HW_CAP_FPGA_TIME_INIT | ZYNQ_HW_CAP_GPS_SMOOTH; } video_port_map = video_port_map_mr; sprintf(code_name, "MoonRover"); break; default: break; } if (zynq_fwupdate_param) { switch (zdev->zdev_did) { case PCI_DEVICE_ID_MOONROVER: hw_cap = ZYNQ_HW_CAP_FW; break; default: break; } } if (zynq_enable_can_rx_dma) { zdev->zcan_rx_dma = 1; } else { zdev->zcan_rx_dma = 0; } if (zynq_enable_can_tx_dma) { zdev->zcan_tx_dma = 1; } else { zdev->zcan_tx_dma = 0; } zdev->zcan_rx_hw_ts = 1; zdev->zdev_hw_cap = hw_cap; zdev->zdev_video_port_map = video_port_map; memcpy(zdev->zdev_code_name, code_name, ZYNQ_DEV_CODE_NAME_LEN); } int zynq_create_cdev_all(zynq_dev_t *zdev) { char cdev_name[32]; unsigned int inst; if (zynq_fwupdate_param && (zdev->zdev_hw_cap & ZYNQ_HW_CAP_FW)) { /* create /dev/zynq_fw_xx */ switch (zdev->zdev_did) { case PCI_DEVICE_ID_MOONROVER: spin_lock(&zynq_g_lock); inst = zynq_mr_cnt++; spin_unlock(&zynq_g_lock); sprintf(cdev_name, ZYNQ_DEV_NAME_FW"_mr%u", inst); break; default: goto cdev_fail; break; } zdev->zdev_dev_fw = zynq_create_cdev(zdev, &zdev->zdev_cdev_fw, &zynq_fw_fops, cdev_name); if (zdev->zdev_dev_fw == 0) { goto cdev_fail; } } /* create /dev/zynq_reg%d */ sprintf(cdev_name, ZYNQ_DEV_NAME_REG"%d", zdev->zdev_inst); zdev->zdev_dev_reg = zynq_create_cdev(zdev, &zdev->zdev_cdev_reg, &zynq_reg_fops, cdev_name); if (zdev->zdev_dev_reg == 0) { goto cdev_fail; } /* create /dev/zynq_i2c%d */ if (zdev->zdev_hw_cap & ZYNQ_HW_CAP_I2C) { sprintf(cdev_name, ZYNQ_DEV_NAME_I2C"%d", zdev->zdev_inst); zdev->zdev_dev_i2c = zynq_create_cdev(zdev, &zdev->zdev_cdev_i2c, &zynq_i2c_fops, cdev_name); if (zdev->zdev_dev_i2c == 0) { goto cdev_fail; } } /* create /dev/zynq_trigger%d */ if (zdev->zdev_hw_cap & ZYNQ_HW_CAP_TRIGGER) { sprintf(cdev_name, ZYNQ_DEV_NAME_TRIGGER"%d", zdev->zdev_inst); zdev->zdev_dev_trigger = zynq_create_cdev(zdev, &zdev->zdev_cdev_trigger, &zynq_trigger_fops, cdev_name); if (zdev->zdev_dev_trigger == 0) { goto cdev_fail; } } /* create /dev/zynq_gps%d */ if (zdev->zdev_hw_cap & ZYNQ_HW_CAP_GPS) { sprintf(cdev_name, ZYNQ_DEV_NAME_GPS"%d", zdev->zdev_inst); zdev->zdev_dev_gps = zynq_create_cdev(zdev, &zdev->zdev_cdev_gps, &zynq_gps_fops, cdev_name); if (zdev->zdev_dev_gps == 0) { goto cdev_fail; } } return 0; cdev_fail: zynq_destroy_cdev_all(zdev); return -1; } void zynq_destroy_cdev_all(zynq_dev_t *zdev) { if (zdev->zdev_dev_gps) { zynq_destroy_cdev(zdev->zdev_dev_gps, &zdev->zdev_cdev_gps); } if (zdev->zdev_dev_trigger) { zynq_destroy_cdev(zdev->zdev_dev_trigger, &zdev->zdev_cdev_trigger); } if (zdev->zdev_dev_fw) { zynq_destroy_cdev(zdev->zdev_dev_fw, &zdev->zdev_cdev_fw); } if (zdev->zdev_dev_reg) { zynq_destroy_cdev(zdev->zdev_dev_reg, &zdev->zdev_cdev_reg); } if (zdev->zdev_dev_i2c) { zynq_destroy_cdev(zdev->zdev_dev_i2c, &zdev->zdev_cdev_i2c); } } /* Supported Sensor FPGA */ const struct pci_device_id zynq_pci_dev_tbl[] = { /* Vendor, Device, SubSysVendor, SubSysDev, Class, ClassMask, DrvDat */ /* MoonRover, Sensor Box */ { PCI_VENDOR_ID_BAIDU, PCI_DEVICE_ID_MOONROVER, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, { } /* terminate list */ }; MODULE_DEVICE_TABLE(pci, zynq_pci_dev_tbl); /* Sensor FPGA driver module load entry point */ static int __init basa_init(void) { return zynq_module_init(); } /* Sensor FPGA driver module remove entry point */ static void __exit basa_exit(void) { zynq_module_exit(); } module_init(basa_init); module_exit(basa_exit); MODULE_LICENSE("Dual BSD/GPL"); MODULE_AUTHOR("BAIDU USA, LLC"); MODULE_DESCRIPTION("basa: Baidu Sensor Aggregator Driver"); MODULE_VERSION(ZYNQ_MOD_VER);
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa.h
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _BASA_H_ #define _BASA_H_ #include <linux/types.h> #include <linux/pci.h> #include <linux/kernel.h> #include <linux/gfp.h> #include <linux/interrupt.h> #include <linux/cdev.h> #include <linux/fs.h> #include <linux/version.h> #include <linux/completion.h> #include <linux/hrtimer.h> #include <linux/mutex.h> #include <asm/uaccess.h> #include "linux/zynq_api.h" #include "basa_regs.h" #include "basa_debug.h" #include "basa_chan.h" #include "basa_video.h" #include "basa_cam_hci.h" #include "basa_can.h" #define ZYNQ_INTR_PROC_TASKLET #define ZDEV_VER(zdev) ((zdev)->zdev_version & 0x0FFF0FFF) #define ZDEV_PL_VER(zdev) ((zdev)->zdev_version & 0xFFF) #define ZDEV_PS_VER(zdev) (((zdev)->zdev_version >> 16) & 0xFFF) #define ZDEV_PL_DEBUG(zdev) \ (ZYNQ_FW_IMAGE_TYPE((zdev)->zdev_version) == 0xD) /* FPGA capabilities */ #define ZYNQ_HW_CAP_CAN (1 << 0) #define ZYNQ_HW_CAP_GPS (1 << 1) #define ZYNQ_HW_CAP_TRIGGER (1 << 2) #define ZYNQ_HW_CAP_FW (1 << 3) #define ZYNQ_HW_CAP_I2C (1 << 4) #define ZYNQ_HW_CAP_VIDEO (1 << 5) #define ZYNQ_HW_CAP_FPGA_TIME_INIT (1 << 6) #define ZYNQ_HW_CAP_GPS_SMOOTH (1 << 7) #define ZYNQ_CAP(zdev, cap) \ ((zdev)->zdev_hw_cap & ZYNQ_HW_CAP_ ## cap) /* Zynq device structure */ typedef struct zynq_dev { struct pci_dev *zdev_pdev; /* pci access data structure */ char zdev_name[ZYNQ_DEV_NAME_LEN]; char zdev_code_name[ZYNQ_DEV_CODE_NAME_LEN]; int zdev_inst; /* instance number */ unsigned int zdev_version; /* version number */ unsigned int zdev_hw_cap; struct cdev zdev_cdev_trigger; /* cdev for sensor trigger */ dev_t zdev_dev_trigger; struct cdev zdev_cdev_fw; /* cdev for zynq firmware update */ dev_t zdev_dev_fw; unsigned int zdev_fw_tx_cnt; atomic_t zdev_fw_opened; struct cdev zdev_cdev_gps; /* cdev for GPS time */ dev_t zdev_dev_gps; struct cdev zdev_cdev_reg; /* cdev for register access */ dev_t zdev_dev_reg; struct cdev zdev_cdev_i2c; /* cdev for i2c access */ dev_t zdev_dev_i2c; struct kobject zdev_kobj; spinlock_t zdev_lock; /* device-wide lock */ /* use a separated I2C access lock as the operation is very slow */ spinlock_t zdev_i2c_lock; u16 zdev_vid; u16 zdev_did; u8 __iomem *zdev_bar0; /* mapped kernel VA for BAR0 */ u8 __iomem *zdev_bar2; /* mapped kernel VA for BAR2 */ unsigned int zdev_bar0_len; unsigned int zdev_bar2_len; unsigned int zdev_chan_cnt; /* total # of channels */ unsigned int zdev_can_cnt; /* total # of CAN channels */ unsigned int zdev_video_cnt; /* total # of Video channels */ unsigned long zdev_can_map; /* mapping of CAN/DMA ch */ unsigned long zdev_video_map; /* mapping of Video/DMA ch */ const int *zdev_video_port_map; /* map of video ch/port */ unsigned int zdev_can_num_start; /* start global CAN IP # */ int zcan_tx_dma; int zcan_rx_dma; int zcan_rx_hw_ts; /* interrupt related */ int zdev_msi_num; int zdev_msi_vec; int zdev_msix_num; struct msix_entry *zdev_msixp; struct tasklet_struct zdev_ta[ZYNQ_INT_PER_CARD]; struct completion zdev_gpspps_event_comp; #if KERNEL_VERSION(4, 20, 0) > LINUX_VERSION_CODE struct timespec zdev_gps_ts_first; struct timespec zdev_gps_ts; /* last valid GPS timestamp */ #else struct timespec64 zdev_gps_ts_first; struct timespec64 zdev_gps_ts; /* last valid GPS timestamp */ #endif unsigned int zdev_gps_smoothing; unsigned int zdev_gps_cnt; long zdev_sys_drift; /* channels */ zynq_chan_t *zdev_chans; zynq_video_t *zdev_videos; zynq_can_t *zdev_cans; zynq_stats_t stats[DEV_STATS_NUM]; char prefix[ZYNQ_LOG_PREFIX_LEN]; struct zynq_dev *zdev_next; } zynq_dev_t; #define _GLOBAL_REGS_ADDR(zdev, off) ((zdev)->zdev_bar0 + (off)) #define _CHAN_REGS_ADDR(zchan, off) ((zchan)->zchan_reg + (off)) #define _CAN_IP_REGS_ADDR(zcan, off) ((zcan)->zcan_ip_reg + (off)) #define _VIDEO_REGS_ADDR(zvideo, off) ((zvideo)->reg_base + (off)) /* Zynq global register access */ #define ZDEV_G_REG32(zdev, off) \ (*((volatile u32 *)_GLOBAL_REGS_ADDR(zdev, off))) #define ZDEV_G_REG32_RD(zdev, off) ZDEV_G_REG32(zdev, off) /* BAR2 register access */ #define _BAR2_REGS_ADDR(zdev, off) ((zdev)->zdev_bar2 + (off)) #define ZDEV_BAR2_REG32(zdev, off) \ (*((volatile u32 *)_BAR2_REGS_ADDR(zdev, off))) #define ZDEV_BAR2_REG32_RD(zdev, off) ZDEV_BAR2_REG32(zdev, off) /* DMA channel register access */ #define ZCHAN_REG32(zchan, off) \ (*((volatile u32 *)_CHAN_REGS_ADDR(zchan, off))) #define ZCHAN_REG32_RD(zchan, off) ZCHAN_REG32(zchan, off) /* CAN channel (CAN IP) register access */ #define ZCAN_REG32(zcan, off) \ (*((volatile u32 *)_CAN_IP_REGS_ADDR(zcan, off))) #define ZCAN_REG32_RD(zcan, off) ZCAN_REG32(zcan, off) /* Video channel register access */ #define ZVIDEO_REG32(zvideo, off) \ (*((volatile u32 *)_VIDEO_REGS_ADDR(zvideo, off))) #define HI32(x) ((u32)((u64)(x) >> 32)) #define LO32(x) ((u32)(x)) /* Get the round-up integer result of x/y */ #define CEILING(x, y) (((x) + (y) - 1) / (y)) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #define ZDEV_IS_ERR(zdev) (ZDEV_G_REG32_RD((zdev), ZYNQ_G_VERSION) == -1) /* * Register read/write functions */ static inline u32 zynq_g_reg_read(zynq_dev_t *zdev, u32 reg) { u32 val = 0; if (!zynq_bringup_param) { val = ZDEV_G_REG32_RD(zdev, reg); } zynq_trace(ZYNQ_TRACE_REG, "%d %s: g_reg 0x%x = 0x%x\n", zdev->zdev_inst, __FUNCTION__, reg, val); return (val); } static inline void zynq_g_reg_write(zynq_dev_t *zdev, u32 reg, u32 val) { if (!zynq_bringup_param) { ZDEV_G_REG32(zdev, reg) = val; } zynq_trace(ZYNQ_TRACE_REG, "%d %s: write 0x%x to g_reg 0x%x\n", zdev->zdev_inst, __FUNCTION__, val, reg); } static inline u32 zynq_bar2_reg_read(zynq_dev_t *zdev, u32 reg) { u32 val = 0; if (!zynq_bringup_param) { val = ZDEV_BAR2_REG32_RD(zdev, reg); } zynq_trace(ZYNQ_TRACE_REG, "%d %s: bar2_reg 0x%x = 0x%x\n", zdev->zdev_inst, __FUNCTION__, reg, val); return (val); } static inline void zynq_bar2_reg_write(zynq_dev_t *zdev, u32 reg, u32 val) { if (!zynq_bringup_param) { ZDEV_BAR2_REG32(zdev, reg) = val; } zynq_trace(ZYNQ_TRACE_REG, "%d %s: write 0x%x to bar2_reg 0x%x\n", zdev->zdev_inst, __FUNCTION__, val, reg); } static inline u32 zchan_reg_read(zynq_chan_t *zchan, u32 reg) { u32 val = 0; if (!zynq_bringup_param) { val = ZCHAN_REG32_RD(zchan, reg); } zynq_trace(ZYNQ_TRACE_REG, "%d ch %d %s: ch_reg 0x%x = 0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, reg, val); return (val); } static inline void zchan_reg_write(zynq_chan_t *zchan, u32 reg, u32 val) { if (!zynq_bringup_param) { ZCHAN_REG32(zchan, reg) = val; } zynq_trace(ZYNQ_TRACE_REG, "%d ch %d %s: write 0x%x to ch_reg 0x%x\n", ZYNQ_INST(zchan), zchan->zchan_num, __FUNCTION__, val, reg); } static inline u32 zcan_reg_read(zynq_can_t *zcan, u32 reg) { u32 val = 0; if (!zynq_bringup_param) { val = ZCAN_REG32_RD(zcan, reg); } zynq_trace(ZYNQ_TRACE_REG, "%d CAN IP %d %s: can_ip_reg 0x%x = 0x%x\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, reg, val); return (val); } static inline void zcan_reg_write(zynq_can_t *zcan, u32 reg, u32 val) { if (!zynq_bringup_param) { ZCAN_REG32(zcan, reg) = val; } zynq_trace(ZYNQ_TRACE_REG, "%d CAN IP %d %s: write 0x%x to can_ip_reg 0x%x\n", ZYNQ_INST(zcan->zchan), zcan->zcan_ip_num, __FUNCTION__, val, reg); } static inline u32 zvideo_reg_read(zynq_video_t *zvideo, u32 reg) { u32 val = 0; if (!zynq_bringup_param) { val = ZVIDEO_REG32(zvideo, reg); } zynq_trace(ZYNQ_TRACE_REG, "%d video %d %s: reg 0x%x = 0x%x\n", ZYNQ_INST(zvideo->zchan), zvideo->index, __FUNCTION__, reg, val); return (val); } static inline void zvideo_reg_write(zynq_video_t *zvideo, u32 reg, u32 val) { if (!zynq_bringup_param) { ZVIDEO_REG32(zvideo, reg) = val; } zynq_trace(ZYNQ_TRACE_REG, "%d video %d %s: reg 0x%x = 0x%x\n", ZYNQ_INST(zvideo->zchan), zvideo->index, __FUNCTION__, reg, val); } /* function declareation */ extern zynq_dev_t *zynq_zdev_init(unsigned short zdev_did); extern int zynq_alloc_irq(zynq_dev_t *zdev); extern void zynq_free_irq(zynq_dev_t *zdev); extern void zynq_check_hw_caps(zynq_dev_t *zdev); extern int zynq_create_cdev_all(zynq_dev_t *zdev); extern void zynq_destroy_cdev_all(zynq_dev_t *zdev); extern void zdev_clear_intr_ch(zynq_dev_t *zdev, int ch); extern void zynq_gps_pps_changed(zynq_dev_t *zdev); extern void zynq_chan_err_proc(zynq_chan_t *zchan); extern void zynq_chan_rx_proc(zynq_chan_t *zchan); extern void zynq_chan_tx_proc(zynq_chan_t *zchan); extern void zynq_chan_proc(zynq_chan_t *zchan, int status); extern void zynq_chan_tasklet(unsigned long arg); extern void zynq_tasklet(unsigned long arg); extern dev_t zynq_create_cdev(void *drvdata, struct cdev *cdev, struct file_operations *fops, char *devname); extern void zynq_destroy_cdev(dev_t dev, struct cdev *cdev); extern int zynq_module_init(void); extern void zynq_module_exit(void); extern int zdev_i2c_read(zynq_dev_t *zdev, ioc_zynq_i2c_acc_t *i2c_acc); extern int zdev_i2c_write(zynq_dev_t *zdev, ioc_zynq_i2c_acc_t *i2c_acc); extern int zynq_sysfs_init(zynq_dev_t *zdev); extern void zynq_sysfs_fini(zynq_dev_t *zdev); extern void zynq_gps_init(zynq_dev_t *zdev); extern void zynq_gps_fini(zynq_dev_t *zdev); extern const struct pci_device_id zynq_pci_dev_tbl[]; extern struct file_operations zynq_fw_fops; extern struct file_operations zynq_gps_fops; extern struct file_operations zynq_reg_fops; extern struct file_operations zynq_i2c_fops; extern struct file_operations zynq_trigger_fops; extern unsigned int zynq_dbg_reg_dump_param; extern unsigned int zynq_fwupdate_param; extern unsigned int zynq_enable_can_rx_dma; extern unsigned int zynq_enable_can_tx_dma; extern spinlock_t zynq_g_lock; extern spinlock_t zynq_gps_lock; #endif /* _BASA_H_ */
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_cam_hci.h
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _BASA_CAM_HCI_H_ #define _BASA_CAM_HCI_H_ /* 8bit registers */ #define REG_MODE_SYNC_TYPE 0xC891 /* 16bit registers */ #define REG_MON_MAJOR_VERSION 0x8000 #define REG_MON_MINOR_VERSION 0x8002 #define REG_MON_RELEASE_VERSION 0x8004 #define REG_UNIQUE_ID 0x802C #define REG_SNSR_CFG_FRAME_LEN_LINES 0xC814 #define REG_SNSR_CFG_LINE_LEN_PCK 0xC816 #define REG_SNSR_CTRL_OPERATION_MODE 0xC844 #define SNSR_CTRL_EMBD_DATA_ENABLE 0x1000 /* 32bit registers */ #define REG_SNSR_CFG_PIXCLK 0xC80C /* Host Command Interface registers */ #define REG_COMMAND 0x0040 #define CMD_DOORBELL 0x8000 #define CMD_COMMAND_MASK 0x7FFF #define REG_PARAM_POOL_SIZE 256 /* Bytes */ #define REG_PARAM_POOL_BASE 0xFC00 #define CMD_ENOERR 0x00 #define CMD_ENOENT 0x01 #define CMD_EINTR 0x02 #define CMD_EIO 0x03 #define CMD_E2BIG 0x04 #define CMD_EBADF 0x05 #define CMD_EAGAIN 0x06 #define CMD_ENOMEM 0x07 #define CMD_EACCES 0x08 #define CMD_EBUSY 0x09 #define CMD_EEXIST 0x0A #define CMD_ENODEV 0x0B #define CMD_EINVAL 0x0C #define CMD_ENOSPC 0x0D #define CMD_ERANGE 0x0E #define CMD_ENOSYS 0x0F #define CMD_EALREADY 0x10 #define CMD_SYS_SET_STATE 0x8100 #define CMD_SYS_GET_STATE 0x8101 #define CMD_FLASH_GET_LOCK 0x8500 #define CMD_FLASH_LOCK_STATUS 0x8501 #define CMD_FLASH_RELEASE_LOCK 0x8502 #define CMD_FLASH_CONFIG 0x8503 #define CMD_FLASH_READ 0x8504 #define CMD_FLASH_WRITE 0x8505 #define CMD_FLASH_ERASE_BLOCK 0x8506 #define CMD_FLASH_ERASE_DEVICE 0x8507 #define CMD_FLASH_QUERY_DEVICE 0x8508 #define CMD_FLASH_STATUS 0x8509 #define CMD_FLASH_CONFIG_DEVICE 0x850A #define CMD_FLASH_VALIDATE 0x850D #define CMD_FLASH_VALIDATE_STATUS 0x850E #define CMD_FLASH_DEV_CMD 0x850F #define CMD_FLASH_DEV_CMD_RESPONSE 0x8510 /* System Manager Request State */ #define SYS_STATE_ENTER_CONFIG_CHANGE 0x28 /* System Manager Permanent State */ #define SYS_STATE_IDLE 0x20 #define SYS_STATE_STREAMING 0x31 #define SYS_STATE_SUSPENDED 0x41 #define SYS_STATE_SOFT_STANDBY 0x53 #define SYS_STATE_HARD_STANDBY 0x5B #define FLASH_PAGE_SIZE 32 #define FLASH_READ_LIMIT REG_PARAM_POOL_SIZE #define FLASH_WRITE_LIMIT (REG_PARAM_POOL_SIZE - 5) extern int zcam_reg_read(zynq_video_t *, zynq_cam_acc_t *); extern int zcam_reg_write(zynq_video_t *, zynq_cam_acc_t *); extern int zcam_check_caps(zynq_video_t *); extern int zcam_change_config(zynq_video_t *); extern int zcam_set_suspend(zynq_video_t *); extern int zcam_flash_get_lock(zynq_video_t *); extern int zcam_flash_release_lock(zynq_video_t *); extern int zcam_flash_lock_status(zynq_video_t *); extern int zcam_flash_query_device(zynq_video_t *); extern int zcam_flash_config_device(zynq_video_t *); extern int zcam_flash_read(zynq_video_t *, unsigned int, unsigned char *, unsigned int); extern int zcam_flash_write(zynq_video_t *, unsigned int, unsigned char *, unsigned int); #endif /* _BASA_CAM_HCI_H_ */
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_can.h
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _BASA_CAN_H_ #define _BASA_CAN_H_ /* create a kernel thread to handle Rx */ #undef PIO_RX_THREAD /* enable Rx interrupt to handle Rx */ #define PIO_RX_INTR struct zynq_dev; enum zynq_state { ZYNQ_STATE_INVAL, ZYNQ_STATE_RESET, ZYNQ_STATE_INIT, ZYNQ_STATE_START, ZYNQ_STATE_STOP }; /* CAN message format: 16 bytes */ typedef struct zcan_msg { /* first word */ union { struct { u32 cmsg_id_ertr:1; u32 cmsg_id_eid:18; u32 cmsg_id_ide:1; u32 cmsg_id_srtr:1; u32 cmsg_id_sid:11; }; u32 cmsg_id; }; /* second word */ union { struct { u32 cmsg_len_rsvd:28; u32 cmsg_len_len:4; }; u32 cmsg_len; }; /* third word */ u32 cmsg_data1; /* MSB: DB0 DB1 DB2 DB3 */ /* fourth word */ u32 cmsg_data2; /* MSB: DB4 DB5 DB6 DB7 */ } zcan_msg_t; #define CMSG_ID_EID_MASK 0x3FFFF /* 18-bit */ #define CMSG_ID_SID_MASK 0x7FF /* 11-bit */ #define CMSG_ID_SID_SHIFT 21 #define CMSG_LEN_MASK 0xF #define CMSG_LEN_SHIFT 28 enum zcan_ip_mode { ZCAN_IP_NORMAL, ZCAN_IP_LOOPBACK, ZCAN_IP_SLEEP }; #define ZCAN_IP_TXFIFO_MAX 64 /* up to 64 messages */ #define ZCAN_IP_TXHPB_MAX 1 /* Tx high priority buffer: 1 message only */ #define ZCAN_IP_RXFIFO_MAX 64 /* up to 64 messages */ #define ZCAN_TIMEOUT_MAX 0xffffffff #define ZCAN_IP_MSG_MIN 256 #define ZCAN_IP_MSG_MAX 65536 #define ZCAN_IP_MSG_NUM 2048 typedef struct zynq_can { struct zynq_dev *zdev; struct zynq_chan *zchan; /* FPGA CAN IP registers: 0x200 x N */ u8 __iomem *zcan_ip_reg; int zcan_ip_num; spinlock_t zcan_pio_lock; /* pio gen lock */ spinlock_t zcan_pio_tx_lock; /* pio tx lock */ spinlock_t zcan_pio_tx_hi_lock; /* pio tx hi lock */ spinlock_t zcan_pio_rx_lock; /* pio rx lock */ enum zynq_state zcan_pio_state; int zcan_pio_loopback; unsigned long zcan_tx_timeout; unsigned long zcan_rx_timeout; bcan_msg_t *zcan_buf_rx_msg; int zcan_buf_rx_num; int zcan_buf_rx_head; int zcan_buf_rx_tail; void __user *zcan_usr_buf; int zcan_usr_buf_num; int zcan_usr_rx_num; struct completion zcan_usr_rx_comp; struct task_struct *zcan_pio_rx_thread; int zcan_usr_rx_seq; int zcan_pio_rx_last_chk_head; int zcan_pio_rx_last_chk_tail; int zcan_pio_rx_last_chk_cnt; int zcan_pio_rx_last_chk_seq; struct cdev zcan_pio_cdev; /* cdev for CAN IP */ dev_t zcan_pio_dev; int zcan_pio_opened; unsigned long zcan_pio_baudrate; struct cdev zcan_cdev; /* cdev for CAN DMA channel */ dev_t zcan_dev; zynq_stats_t stats[CAN_STATS_NUM]; char prefix[ZYNQ_LOG_PREFIX_LEN]; } zynq_can_t; /* function declaration */ extern int zcan_init(zynq_can_t *zcan); extern void zcan_fini(zynq_can_t *zcan); extern int zcan_pio_init(zynq_can_t *zcan, enum zcan_ip_mode mode); extern void zcan_pio_fini(zynq_can_t *zcan); extern void zcan_pio_test(zynq_can_t *zcan, int loopback, int hi_pri, int msgcnt); extern void zcan_test(zynq_can_t *zcan, int loopback, int msgcnt); extern void zcan_rx_proc(zynq_can_t *zcan); extern void zcan_err_proc(zynq_can_t *zcan, int ch_err_status); extern zynq_can_t *can_ip_to_zcan(struct zynq_dev *zdev, u32 can_ip_num); extern void zynq_dbg_reg_dump_all(struct zynq_dev *zdev); extern void zcan_pio_dbg_reg_dump_ch(zynq_can_t *zcan); #endif /* _BASA_CAN_H_ */
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu
apollo_public_repos/apollo-contrib/baidu/src/kernel/drivers/baidu/basa/basa_i2c.c
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/delay.h> #include "basa.h" /* * I2C register access */ #define ZYNQ_I2C_WAIT_US 300 /* 100Kbps */ #define ZYNQ_I2C_RETRY 20 static u32 i2c_control_regs[ZYNQ_I2C_BUS_NUM] = { ZYNQ_G_I2C_CONTROL_0, ZYNQ_G_I2C_CONTROL_1, ZYNQ_G_I2C_CONTROL_2, ZYNQ_G_I2C_CONTROL_3 }; static u32 i2c_config_regs[ZYNQ_I2C_BUS_NUM] = { ZYNQ_G_I2C_CONFIG_0, ZYNQ_G_I2C_CONFIG_1, ZYNQ_G_I2C_CONFIG_2, ZYNQ_G_I2C_CONFIG_3 }; static int zdev_i2c_validate(zynq_dev_t *zdev, ioc_zynq_i2c_acc_t *i2c_acc) { if (!(zdev->zdev_hw_cap & ZYNQ_HW_CAP_I2C)) { zynq_err("%d %s: I2C is not supported on this device\n", zdev->zdev_inst, __FUNCTION__); return -EPERM; } if (i2c_acc->i2c_bus >= ZYNQ_I2C_BUS_NUM) { zynq_err("%d %s invalid i2c_bus=%d", zdev->zdev_inst, __FUNCTION__, i2c_acc->i2c_bus); return -EINVAL; } if (i2c_acc->i2c_id > ZYNQ_I2C_ID_MAX) { zynq_err("%d %s: invalid i2c_id=0x%x\n", zdev->zdev_inst, __FUNCTION__, i2c_acc->i2c_id); return -EINVAL; } return 0; } static int zdev_i2c_check_busy(zynq_dev_t *zdev, ioc_zynq_i2c_acc_t *i2c_acc) { u32 ctrl_reg; u32 ctrl_val; int i; ctrl_reg = i2c_control_regs[i2c_acc->i2c_bus]; for (i = 0; i < ZYNQ_I2C_RETRY; i++) { ctrl_val = zynq_g_reg_read(zdev, ctrl_reg); if (ctrl_val & ZYNQ_I2C_CMD_ERR) { zynq_err("%d %s error detected, " "i2c_bus=%d, i2c_ctrl=0x%x\n", zdev->zdev_inst, __FUNCTION__, i2c_acc->i2c_bus, ctrl_val); return -EFAULT; } if (!(ctrl_val & ZYNQ_I2C_CMD_BUSY)) { return 0; } /* wait and retry */ udelay(ZYNQ_I2C_WAIT_US); } zynq_err("%d %s busy wait timeout, i2c_bus=%d, i2c_ctrl=0x%x\n", zdev->zdev_inst, __FUNCTION__, i2c_acc->i2c_bus, ctrl_val); return -EAGAIN; } int zdev_i2c_read(zynq_dev_t *zdev, ioc_zynq_i2c_acc_t *i2c_acc) { u32 ctrl_reg; u32 ctrl_val = 0; u32 cfg_reg; u32 cfg_val = 0; int err = 0; err = zdev_i2c_validate(zdev, i2c_acc); if (err) { return err; } spin_lock(&zdev->zdev_i2c_lock); err = zdev_i2c_check_busy(zdev, i2c_acc); if (err == -EAGAIN) { goto done; } ctrl_reg = i2c_control_regs[i2c_acc->i2c_bus]; cfg_reg = i2c_config_regs[i2c_acc->i2c_bus]; if (i2c_acc->i2c_addr_16) { ctrl_val = ZYNQ_I2C_ADDR_16; /* set the higher 8-bit I2C address */ cfg_val = SET_BITS(ZYNQ_I2C_ADDR_HI, 0, i2c_acc->i2c_addr_hi); zynq_g_reg_write(zdev, cfg_reg, cfg_val); } /* do I2C reading */ ctrl_val |= ZYNQ_I2C_CMD_READ; ctrl_val = SET_BITS(ZYNQ_I2C_ID, ctrl_val, i2c_acc->i2c_id); ctrl_val = SET_BITS(ZYNQ_I2C_ADDR, ctrl_val, i2c_acc->i2c_addr); zynq_g_reg_write(zdev, ctrl_reg, ctrl_val); err = zdev_i2c_check_busy(zdev, i2c_acc); if (err) { goto done; } i2c_acc->i2c_data = (unsigned char) GET_BITS(ZYNQ_I2C_DATA, zynq_g_reg_read(zdev, ctrl_reg)); done: spin_unlock(&zdev->zdev_i2c_lock); if (err) { zynq_err("%d %s failed: i2c_id=0x%02x, i2c_addr_hi=0x%02x, " "i2c_addr=0x%02x, i2c_addr_16=%d, i2c_bus=%d\n", zdev->zdev_inst, __FUNCTION__, i2c_acc->i2c_id, i2c_acc->i2c_addr_hi, i2c_acc->i2c_addr, i2c_acc->i2c_addr_16, i2c_acc->i2c_bus); } else { zynq_trace(ZYNQ_TRACE_REG, "%d %s OK: i2c_id=0x%02x, " "i2c_addr_hi=0x%02x, i2c_addr=0x%02x, " "i2c_data=0x%02x, i2c_addr_16=%d, i2c_bus=%d\n", zdev->zdev_inst, __FUNCTION__, i2c_acc->i2c_id, i2c_acc->i2c_addr_hi, i2c_acc->i2c_addr, i2c_acc->i2c_data, i2c_acc->i2c_addr_16, i2c_acc->i2c_bus); } return err; } int zdev_i2c_write(zynq_dev_t *zdev, ioc_zynq_i2c_acc_t *i2c_acc) { u32 ctrl_reg; u32 ctrl_val = 0; u32 cfg_reg; u32 cfg_val = 0; int err = 0; err = zdev_i2c_validate(zdev, i2c_acc); if (err) { return err; } spin_lock(&zdev->zdev_i2c_lock); err = zdev_i2c_check_busy(zdev, i2c_acc); if (err == -EAGAIN) { goto done; } ctrl_reg = i2c_control_regs[i2c_acc->i2c_bus]; cfg_reg = i2c_config_regs[i2c_acc->i2c_bus]; if (i2c_acc->i2c_addr_16) { ctrl_val = ZYNQ_I2C_ADDR_16; /* set the higher 8-bit I2C address */ cfg_val = SET_BITS(ZYNQ_I2C_ADDR_HI, 0, i2c_acc->i2c_addr_hi); zynq_g_reg_write(zdev, cfg_reg, cfg_val); } /* do I2C writing */ ctrl_val = SET_BITS(ZYNQ_I2C_DATA, ctrl_val, i2c_acc->i2c_data); ctrl_val = SET_BITS(ZYNQ_I2C_ID, ctrl_val, i2c_acc->i2c_id); ctrl_val = SET_BITS(ZYNQ_I2C_ADDR, ctrl_val, i2c_acc->i2c_addr); ctrl_val &= ~ZYNQ_I2C_CMD_READ; zynq_g_reg_write(zdev, ctrl_reg, ctrl_val); err = zdev_i2c_check_busy(zdev, i2c_acc); done: spin_unlock(&zdev->zdev_i2c_lock); if (err) { zynq_err("%d %s failed: i2c_id=0x%02x, " "i2c_addr_hi=0x%02x, i2c_addr=0x%02x, " "i2c_data=0x%02x, i2c_addr_16=%d, i2c_bus=%d\n", zdev->zdev_inst, __FUNCTION__, i2c_acc->i2c_id, i2c_acc->i2c_addr_hi, i2c_acc->i2c_addr, i2c_acc->i2c_data, i2c_acc->i2c_addr_16, i2c_acc->i2c_bus); } else { zynq_trace(ZYNQ_TRACE_REG, "%d %s OK: i2c_id=0x%02x, " "i2c_addr_hi=0x%02x, i2c_addr=0x%02x, " "i2c_data=0x%02x, i2c_addr_16=%d, i2c_bus=%d\n", zdev->zdev_inst, __FUNCTION__, i2c_acc->i2c_id, i2c_acc->i2c_addr_hi, i2c_acc->i2c_addr, i2c_acc->i2c_data, i2c_acc->i2c_addr_16, i2c_acc->i2c_bus); } return err; } static long zynq_i2c_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { zynq_dev_t *zdev = filp->private_data; ioc_zynq_i2c_acc_t i2c_acc; int err = 0; switch (cmd) { case ZYNQ_IOC_REG_I2C_READ: if (copy_from_user(&i2c_acc, (void __user *)arg, sizeof(ioc_zynq_i2c_acc_t))) { zynq_err("%d ZYNQ_IOC_REG_I2C_READ: copy_from_user " "failed\n", zdev->zdev_inst); err = -EFAULT; break; } err = zdev_i2c_read(zdev, &i2c_acc); if (err) { break; } if (copy_to_user((void __user *)arg, &i2c_acc, sizeof(ioc_zynq_i2c_acc_t))) { zynq_err("%d ZYNQ_IOC_REG_I2C_READ: copy_to_user " "failed\n", zdev->zdev_inst); err = -EFAULT; } break; case ZYNQ_IOC_REG_I2C_WRITE: if (copy_from_user(&i2c_acc, (void __user *)arg, sizeof(ioc_zynq_i2c_acc_t))) { zynq_err("%d ZYNQ_IOC_REG_I2C_WRITE: copy_from_user " "failed\n", zdev->zdev_inst); err = -EFAULT; break; } err = zdev_i2c_write(zdev, &i2c_acc); break; default: err = -EINVAL; break; } zynq_trace(ZYNQ_TRACE_PROBE, "%d %s done: cmd=0x%x, error=%d\n", zdev->zdev_inst, __FUNCTION__, cmd, err); return err; } static int zynq_i2c_open(struct inode *inode, struct file *filp) { zynq_dev_t *zdev; zdev = container_of(inode->i_cdev, zynq_dev_t, zdev_cdev_i2c); filp->private_data = zdev; zynq_trace(ZYNQ_TRACE_PROBE, "%d %s done\n", zdev->zdev_inst, __FUNCTION__); return 0; } static int zynq_i2c_release(struct inode *inode, struct file *filp) { return 0; } struct file_operations zynq_i2c_fops = { .owner = THIS_MODULE, .unlocked_ioctl = zynq_i2c_ioctl, .open = zynq_i2c_open, .release = zynq_i2c_release };
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/include/uapi
apollo_public_repos/apollo-contrib/baidu/src/kernel/include/uapi/linux/bcan_defs.h
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BCAN_DEFS_H #define BCAN_DEFS_H #ifndef __KERNEL__ #include <sys/time.h> #else #include <linux/time.h> #endif #define BCAN_EXTENDED_FRAME 0x20000000 /* * Baidu CAN message definition */ typedef struct bcan_msg { unsigned int bcan_msg_id; /* source CAN node id */ unsigned char bcan_msg_datalen; /* message data len */ unsigned char bcan_msg_rsv[3]; unsigned char bcan_msg_data[8]; /* message data */ struct timeval bcan_msg_timestamp; } bcan_msg_t; /* * CAN error code */ enum bcan_err_code { BCAN_PARAM_INVALID = -12, BCAN_HDL_INVALID, BCAN_DEV_INVALID, BCAN_DEV_ERR, BCAN_DEV_BUSY, BCAN_TIMEOUT, BCAN_FAIL, BCAN_NOT_SUPPORTED, BCAN_NOT_IMPLEMENTED, BCAN_INVALID, BCAN_NO_BUFFERS, BCAN_ERR, BCAN_OK, /* 0 */ BCAN_PARTIAL_OK }; #endif
0
apollo_public_repos/apollo-contrib/baidu/src/kernel/include/uapi
apollo_public_repos/apollo-contrib/baidu/src/kernel/include/uapi/linux/zynq_api.h
/* * Apollo Sensor FPGA support * * Copyright (C) 2018 Baidu Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _ZYNQ_API_H_ #define _ZYNQ_API_H_ #include "bcan_defs.h" #define ZYNQ_DEV_NAME_FW "zynq_fw" #define ZYNQ_DEV_NAME_TRIGGER "zynq_trigger" #define ZYNQ_DEV_NAME_GPS "zynq_gps" #define ZYNQ_DEV_NAME_REG "zynq_reg" #define ZYNQ_DEV_NAME_CAN "zynq_can" #define ZYNQ_DEV_NAME_I2C "zynq_i2c" /* * ioctl argument defintion for CAN send/recv */ typedef struct ioc_bcan_msg { bcan_msg_t *ioc_msgs; unsigned int ioc_msg_num; unsigned int ioc_msg_num_done; int ioc_msg_err; int ioc_msg_rx_clear; } ioc_bcan_msg_t; /* * CAN error and status */ typedef struct ioc_bcan_status_err { unsigned int bcan_status; unsigned int bcan_err_status; unsigned int bcan_err_count; int bcan_ioc_err; } ioc_bcan_status_err_t; /* ioctl command list */ #define ZYNQ_IOC_MAGIC ('z' << 12 | 'y' << 8 | 'n' << 4 | 'q') enum ZYNQ_IOC_GPS_CMD { IOC_GPS_GET = 1, IOC_GPS_GPRMC_GET, IOC_GPS_CMD_MAX }; enum ZYNQ_IOC_TRIGGER_CMD { IOC_TRIGGER_DISABLE = IOC_GPS_CMD_MAX, IOC_TRIGGER_ENABLE_GPS, IOC_TRIGGER_ENABLE_NOGPS, IOC_TRIGGER_ENABLE_ONE_GPS, IOC_TRIGGER_ENABLE_ONE_NOGPS, IOC_TRIGGER_TIMESTAMP, IOC_TRIGGER_STATUS, IOC_TRIGGER_STATUS_GPS, IOC_TRIGGER_STATUS_PPS, IOC_TRIGGER_FPS_SET, IOC_TRIGGER_FPS_GET, IOC_TRIGGER_CMD_MAX }; enum ZYNQ_IOC_FW_CMD { IOC_FW_IMAGE_UPLOAD_START = IOC_TRIGGER_CMD_MAX, IOC_FW_IMAGE_UPLOAD, IOC_FW_PL_UPDATE, /* PL FPGA FW image update */ IOC_FW_PS_UPDATE, /* PS OS image update */ IOC_FW_GET_VER, /* get the image version */ IOC_FW_CMD_MAX }; enum ZYNQ_IOC_CAN_CMD { IOC_CAN_TX_TIMEOUT_SET = IOC_FW_CMD_MAX, /* in milli-seconds */ IOC_CAN_RX_TIMEOUT_SET, /* in milli-seconds */ IOC_CAN_DEV_START, IOC_CAN_DEV_STOP, IOC_CAN_DEV_RESET, IOC_CAN_ID_ADD, IOC_CAN_ID_DEL, IOC_CAN_BAUDRATE_SET, IOC_CAN_BAUDRATE_GET, IOC_CAN_LOOPBACK_SET, IOC_CAN_LOOPBACK_UNSET, IOC_CAN_RECV, IOC_CAN_SEND, IOC_CAN_SEND_HIPRI, IOC_CAN_GET_STATUS_ERR, IOC_CAN_CMD_MAX }; enum ZYNQ_IOC_REG_CMD { IOC_REG_READ = IOC_CAN_CMD_MAX, IOC_REG_WRITE, IOC_REG_I2C_READ, IOC_REG_I2C_WRITE, IOC_REG_GPSPPS_EVENT_WAIT, IOC_REG_CMD_MAX }; enum ZYNQ_IOC_TRIGGER_EXT_CMD { IOC_TRIGGER_INIT_USB = IOC_REG_CMD_MAX, IOC_TRIGGER_ENABLE_ONE, IOC_TRIGGER_DISABLE_ONE, IOC_TRIGGER_ENABLE, IOC_TRIGGER_DELAY_SET, IOC_TRIGGER_DELAY_GET, IOC_TRIGGER_DEV_NAME, IOC_TRIGGER_EXT_MAX }; enum ZYNQ_IOC_CAM_CMD { IOC_CAM_REG_READ = 100, IOC_CAM_REG_WRITE, IOC_CAM_FLASH_INIT, IOC_CAM_FLASH_FINI, IOC_CAM_FLASH_READ, IOC_CAM_FLASH_WRITE, IOC_CAM_CAPS, IOC_CAM_RESET }; enum ZYNQ_IOC_GPS_EXT_CMD { IOC_GPS_FPGA_INIT = 110, IOC_GPS_SYNC }; enum ZYNQ_IOC_FW_EXT_CMD { IOC_FW_QSPI_UPDATE = 120, /* QSPI flash image update */ IOC_FW_MMC_UPDATE, /* eMMC image update */ IOC_FW_SPI_UPDATE /* SPI flash image update */ }; enum ZYNQ_IOC_MISC_CMD { IOC_STATS_GET = 200 }; enum zynq_baudrate_val { ZYNQ_BAUDRATE_1M, ZYNQ_BAUDRATE_500K, ZYNQ_BAUDRATE_250K, ZYNQ_BAUDRATE_150K, ZYNQ_BAUDRATE_NUM }; /* Misc ioctl cmds */ #define ZYNQ_IOC_STATS_GET \ _IOWR(ZYNQ_IOC_MAGIC, IOC_STATS_GET, unsigned long) /* GPS update ioctl cmds */ #define ZYNQ_GPS_VAL_SZ 12 #define ZYNQ_IOC_GPS_GET \ _IOR(ZYNQ_IOC_MAGIC, IOC_GPS_GET, unsigned char *) #define ZYNQ_GPS_GPRMC_VAL_SZ 68 #define ZYNQ_IOC_GPS_GPRMC_GET \ _IOR(ZYNQ_IOC_MAGIC, IOC_GPS_GPRMC_GET, unsigned char *) #define ZYNQ_IOC_GPS_FPGA_INIT \ _IO(ZYNQ_IOC_MAGIC, IOC_GPS_FPGA_INIT) #define ZYNQ_IOC_GPS_SYNC \ _IO(ZYNQ_IOC_MAGIC, IOC_GPS_SYNC) /* Trigger ioctl cmds */ #define ZYNQ_IOC_TRIGGER_DISABLE \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_DISABLE, unsigned long) #define ZYNQ_IOC_TRIGGER_ENABLE_GPS \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_ENABLE_GPS, unsigned long) #define ZYNQ_IOC_TRIGGER_ENABLE_NOGPS \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_ENABLE_NOGPS, unsigned long) #define ZYNQ_IOC_TRIGGER_ENABLE_ONE_GPS \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_ENABLE_ONE_GPS, unsigned long) #define ZYNQ_IOC_TRIGGER_ENABLE_ONE_NOGPS \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_ENABLE_ONE_NOGPS, unsigned long) #define ZYNQ_IOC_TRIGGER_TIMESTAMP \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_TIMESTAMP, unsigned long) #define ZYNQ_IOC_TRIGGER_STATUS \ _IOR(ZYNQ_IOC_MAGIC, IOC_TRIGGER_STATUS, int *) #define ZYNQ_IOC_TRIGGER_STATUS_GPS \ _IOR(ZYNQ_IOC_MAGIC, IOC_TRIGGER_STATUS_GPS, int *) #define ZYNQ_IOC_TRIGGER_STATUS_PPS \ _IOR(ZYNQ_IOC_MAGIC, IOC_TRIGGER_STATUS_PPS, int *) #define ZYNQ_IOC_TRIGGER_FPS_SET \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_FPS_SET, int *) #define ZYNQ_IOC_TRIGGER_FPS_GET \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_FPS_GET, int *) #define ZYNQ_IOC_TRIGGER_INIT_USB \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_INIT_USB, unsigned long) #define ZYNQ_IOC_TRIGGER_ENABLE_ONE \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_ENABLE_ONE, unsigned long) #define ZYNQ_IOC_TRIGGER_DISABLE_ONE \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_DISABLE_ONE, unsigned long) #define ZYNQ_IOC_TRIGGER_ENABLE \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_ENABLE, unsigned long) #define ZYNQ_IOC_TRIGGER_DELAY_SET \ _IOW(ZYNQ_IOC_MAGIC, IOC_TRIGGER_DELAY_SET, unsigned long) #define ZYNQ_IOC_TRIGGER_DELAY_GET \ _IOWR(ZYNQ_IOC_MAGIC, IOC_TRIGGER_DELAY_GET, unsigned long) #define ZYNQ_IOC_TRIGGER_DEV_NAME \ _IOR(ZYNQ_IOC_MAGIC, IOC_TRIGGER_DEV_NAME, char *) /* Camera register I2C cmds */ #define ZYNQ_IOC_CAM_REG_READ \ _IOWR(ZYNQ_IOC_MAGIC, IOC_CAM_REG_READ, unsigned long) #define ZYNQ_IOC_CAM_REG_WRITE \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAM_REG_WRITE, unsigned long) #define ZYNQ_IOC_CAM_FLASH_INIT \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAM_FLASH_INIT, unsigned long) #define ZYNQ_IOC_CAM_FLASH_FINI \ _IO(ZYNQ_IOC_MAGIC, IOC_CAM_FLASH_FINI) #define ZYNQ_IOC_CAM_FLASH_READ \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAM_FLASH_READ, unsigned long) #define ZYNQ_IOC_CAM_FLASH_WRITE \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAM_FLASH_WRITE, unsigned long) #define ZYNQ_IOC_CAM_CAPS \ _IOWR(ZYNQ_IOC_MAGIC, IOC_CAM_CAPS, unsigned long) #define ZYNQ_IOC_CAM_RESET \ _IO(ZYNQ_IOC_MAGIC, IOC_CAM_RESET) #define ZYNQ_CAM_FW_BLOCK_SIZE 8 #define ZYNQ_CAM_FW_BLOCK_SIZE_MAX 250 typedef struct zynq_cam_fw { unsigned char *data; unsigned int size; unsigned int address; } zynq_cam_fw_t; #define ZYNQ_TRIGGER_DEV_NUM 4 #define ZYNQ_USB_FPS_MAX 30 #define ZYNQ_USB_FPS_DEFAULT 30 #define ZYNQ_USB_TRIG_NUM 5 #define ZYNQ_USB_TRIG_TOTAL ZYNQ_USB_TRIG_NUM * ZYNQ_TRIGGER_DEV_NUM #define ZYNQ_FPD_FPS_MAX 20 #define ZYNQ_FPD_FPS_DEFAULT 10 /* 10Hz default */ #define ZYNQ_FPD_TRIG_NUM 10 #define ZYNQ_FPD_TRIG_TOTAL ZYNQ_FPD_TRIG_NUM * ZYNQ_TRIGGER_DEV_NUM #define ZYNQ_FPD_CAM_NAME "FPD" #define ZYNQ_DEV_NAME_LEN 64 #define ZYNQ_DEV_CODE_NAME_LEN 32 #define ZYNQ_VDEV_NAME_LEN 56 /* * For USB cameras, we assign trigger IDs to designated trigger lines. * The user applications and kernel driver should always use the same * mappings: * 0: LI trigger * 1: GH trigger * 2: BB trigger * 3: LB trigger * 4: Test trigger * For FPD-link cameras, the trigger id mapping is always fixed: * 0: 1st FPD-link * 1: 2nd FPD-link * ... */ typedef struct zynq_trigger { unsigned char id; /* Trigger id */ unsigned char fps; /* Frame-Per-Second */ unsigned char internal; /* 1: Internal PPS; 0: GPS PPS */ unsigned char enabled; /* 1: Enabled; 0: Disabled */ unsigned int trigger_delay; unsigned int exposure_time; /* Video number, e.g. 0 for /dev/video0 */ int vnum; /* Camera name, e.g. AR023ZWDR(Rev663) */ char name[ZYNQ_VDEV_NAME_LEN]; } zynq_trigger_t; /* * Camera trigger delay, currently used by sensor_sync */ typedef struct zynq_trigger_delay { int vnum; unsigned int trigger_delay; unsigned int exposure_time; } zynq_trigger_delay_t; /* FW update ioctl cmds */ #define ZYNQ_FW_PADDING 0x00000000 #define ZYNQ_FW_MSG_SZ 16 typedef struct ioc_zynq_fw_upload { /* * image data size must be multiple of 4 as each polling transfer is in * 16-byte, so padding the data if needed. */ unsigned int *ioc_zynq_fw_data; unsigned int ioc_zynq_fw_num; unsigned int ioc_zynq_fw_done; int ioc_zynq_fw_err; } ioc_zynq_fw_upload_t; #define ZYNQ_IOC_FW_IMAGE_UPLOAD_START \ _IOW(ZYNQ_IOC_MAGIC, IOC_FW_IMAGE_UPLOAD_START, unsigned long) #define ZYNQ_IOC_FW_IMAGE_UPLOAD \ _IOW(ZYNQ_IOC_MAGIC, IOC_FW_IMAGE_UPLOAD, ioc_zynq_fw_upload_t *) #define ZYNQ_IOC_FW_PL_UPDATE \ _IOW(ZYNQ_IOC_MAGIC, IOC_FW_PL_UPDATE, unsigned long) #define ZYNQ_IOC_FW_PS_UPDATE \ _IOW(ZYNQ_IOC_MAGIC, IOC_FW_PS_UPDATE, unsigned long) #define ZYNQ_IOC_FW_GET_VER \ _IOW(ZYNQ_IOC_MAGIC, IOC_FW_GET_VER, unsigned int *) #define ZYNQ_IOC_FW_QSPI_UPDATE \ _IOW(ZYNQ_IOC_MAGIC, IOC_FW_QSPI_UPDATE, unsigned long) #define ZYNQ_IOC_FW_MMC_UPDATE \ _IOW(ZYNQ_IOC_MAGIC, IOC_FW_MMC_UPDATE, unsigned long) #define ZYNQ_IOC_FW_SPI_UPDATE \ _IOW(ZYNQ_IOC_MAGIC, IOC_FW_SPI_UPDATE, unsigned long) /* CAN channel ioctl cmds */ #define ZYNQ_IOC_CAN_TX_TIMEOUT_SET \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_TX_TIMEOUT_SET, unsigned long) #define ZYNQ_IOC_CAN_RX_TIMEOUT_SET \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_RX_TIMEOUT_SET, unsigned long) #define ZYNQ_IOC_CAN_DEV_START \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_DEV_START, unsigned long) #define ZYNQ_IOC_CAN_DEV_STOP \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_DEV_STOP, unsigned long) #define ZYNQ_IOC_CAN_DEV_RESET \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_DEV_RESET, unsigned long) #define ZYNQ_IOC_CAN_ID_ADD \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_ID_ADD, unsigned long) #define ZYNQ_IOC_CAN_ID_DEL \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_ID_DEL, unsigned long) #define ZYNQ_IOC_CAN_BAUDRATE_SET \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_BAUDRATE_SET, unsigned long) #define ZYNQ_IOC_CAN_BAUDRATE_GET \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_BAUDRATE_GET, unsigned long) #define ZYNQ_IOC_CAN_LOOPBACK_SET \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_LOOPBACK_SET, unsigned long) #define ZYNQ_IOC_CAN_LOOPBACK_UNSET \ _IOW(ZYNQ_IOC_MAGIC, IOC_CAN_LOOPBACK_UNSET, unsigned long) #define ZYNQ_IOC_CAN_RECV \ _IOWR(ZYNQ_IOC_MAGIC, IOC_CAN_RECV, ioc_bcan_msg_t *) #define ZYNQ_IOC_CAN_SEND \ _IOWR(ZYNQ_IOC_MAGIC, IOC_CAN_SEND, ioc_bcan_msg_t *) #define ZYNQ_IOC_CAN_SEND_HIPRI \ _IOWR(ZYNQ_IOC_MAGIC, IOC_CAN_SEND_HIPRI, ioc_bcan_msg_t *) #define ZYNQ_IOC_CAN_GET_STATUS_ERR \ _IOR(ZYNQ_IOC_MAGIC, IOC_CAN_GET_STATUS_ERR, \ ioc_bcan_status_err_t *) /* register read/write ioctl cmds */ typedef struct ioc_zynq_reg_acc { unsigned int reg_bar; unsigned int reg_offset; unsigned int reg_data; } ioc_zynq_reg_acc_t; /* I2C ID definitions */ #define ZYNQ_I2C_ID_JANUS 0x5c #define ZYNQ_I2C_ID_MAX 0x7f /* 7-bit */ typedef struct ioc_zynq_i2c_acc { unsigned char i2c_id; /* 7-bit */ unsigned char i2c_addr_hi; unsigned char i2c_addr; unsigned char i2c_data; unsigned char i2c_addr_16; unsigned char i2c_bus; } ioc_zynq_i2c_acc_t; typedef struct zynq_cam_acc { unsigned short addr; unsigned short data_sz; unsigned int data; } zynq_cam_acc_t; #define ZYNQ_IOC_REG_READ \ _IOR(ZYNQ_IOC_MAGIC, IOC_REG_READ, ioc_zynq_reg_acc_t *) #define ZYNQ_IOC_REG_WRITE \ _IOW(ZYNQ_IOC_MAGIC, IOC_REG_WRITE, ioc_zynq_reg_acc_t *) #define ZYNQ_IOC_REG_I2C_READ \ _IOR(ZYNQ_IOC_MAGIC, IOC_REG_I2C_READ, ioc_zynq_i2c_acc_t *) #define ZYNQ_IOC_REG_I2C_WRITE \ _IOW(ZYNQ_IOC_MAGIC, IOC_REG_I2C_WRITE, ioc_zynq_i2c_acc_t *) /* wait for GPS/PPS status change event notification */ #define ZYNQ_IOC_REG_GPSPPS_EVENT_WAIT \ _IOW(ZYNQ_IOC_MAGIC, IOC_REG_GPSPPS_EVENT_WAIT, unsigned long) #define ZVIDEO_EXT_MARKER 0xFE12 #define ZVIDEO_EXT_ERR_FRAME_FORMAT 0x01 #define ZVIDEO_EXT_ERR_SHORT_FRAME 0x02 #define ZVIDEO_EXT_ERR_LONG_FRAME 0x04 #define ZVIDEO_EXT_ERR_ALL 0x07 #define ZVIDEO_EXT_ERR_INVALID 0xFF #define ZVIDEO_FRAME_CORRUPTED(ext) \ ((ext->marker[0] != ZVIDEO_EXT_MARKER) || \ (ext->marker[1] != ZVIDEO_EXT_MARKER) || \ (ext->marker[2] != ZVIDEO_EXT_MARKER) || \ (*(unsigned int *)ext->rsv1) || \ (*(unsigned int *)&ext->rsv2[0]) || \ (*(unsigned int *)&ext->rsv2[3]) || \ (ext->error & ~(unsigned char)ZVIDEO_EXT_ERR_ALL)) typedef struct zynq_video_ext_meta_data { unsigned int trigger_cnt; struct { unsigned int usec:20; unsigned int :12; unsigned int sec; } time_stamp; unsigned char rsv1[4]; struct { unsigned short us_cnt:12; unsigned short sec:4; } debug_ts; unsigned short marker[3]; unsigned char rsv2[7]; unsigned char error; } zynq_video_ext_meta_data_t; /* Code name */ #define CAM_CAP_CODENAME_ARGUS 0 #define CAM_CAP_CODENAME_SHARPVISION 1 /* Trigger mode */ #define CAM_CAP_TRIGGER_STANDARD 0 #define CAM_CAP_TRIGGER_DETERMINISTIC 1 #define CAM_CAP_TRIGGER_SLAVE_STANDARD 2 #define CAM_CAP_TRIGGER_SLAVE_SHUTTER_SYNC 3 /* Timestamp type */ #define CAM_CAP_TIMESTAMP_FPGA 0 #define CAM_CAP_TIMESTAMP_TRIGGER 1 #define CAM_CAP_TIMESTAMP_FORMATION 2 #define CAM_CAP_TIMESTAMP_HOST 3 /* Camera feature */ #define CAM_CAP_FEATURE_FLASH_ADDR_16 0x1 /* 0 for 24b */ /* Interface type */ #define CAM_CAP_INTERFACE_PARALLEL 0 #define CAM_CAP_INTERFACE_MIPI 1 /* Camera capabilities */ typedef struct zynq_camera_capabilities { char name[ZYNQ_VDEV_NAME_LEN]; unsigned short unique_id; union { struct { unsigned char position; unsigned char project; }; unsigned short major_version; }; union { struct { unsigned char version:4; unsigned char :2; unsigned char feature:2; unsigned char vendor:5; unsigned char code_name:3; }; unsigned short minor_version; }; unsigned char timestamp_type:2; unsigned char trigger_mode:2; unsigned char embedded_data:1; unsigned char interface_type:1; unsigned char pin_swap:1; unsigned char :1; unsigned char link_up; unsigned short frame_len_lines; unsigned short line_len_pck; unsigned int pixel_clock; } zynq_cam_caps_t; enum zynq_dev_stats { DEV_STATS_INTR = 0, DEV_STATS_INTR_INVALID, DEV_STATS_GPS_UNLOCK, DEV_STATS_NUM }; enum zynq_chan_stats { CHAN_STATS_RX_INTR = 0, CHAN_STATS_TX_INTR, CHAN_STATS_RX_ERR_INTR, CHAN_STATS_TX_ERR_INTR, CHAN_STATS_RX_DROP, CHAN_STATS_RX, CHAN_STATS_TX, CHAN_STATS_NUM }; enum zynq_video_stats { VIDEO_STATS_FRAME = 0, VIDEO_STATS_RESET, VIDEO_STATS_TRIG_PULSE_ERR, VIDEO_STATS_LINK_CHANGE, VIDEO_STATS_DMA_RX_BUF_FULL, VIDEO_STATS_DMA_RX_FIFO_FULL, VIDEO_STATS_TRIG_COUNT_MISMATCH, VIDEO_STATS_META_COUNT_MISMATCH, VIDEO_STATS_FRAME_GAP_ERR, VIDEO_STATS_FRAME_FORMAT_ERR, VIDEO_STATS_FRAME_SHORT, VIDEO_STATS_FRAME_LONG, VIDEO_STATS_FRAME_CORRUPT, VIDEO_STATS_FRAME_DROP, VIDEO_STATS_FRAME_DROP_1, VIDEO_STATS_FRAME_DROP_2, VIDEO_STATS_FRAME_DROP_M, VIDEO_STATS_NO_VIDEO_BUF, VIDEO_STATS_NUM }; enum zynq_can_stats { CAN_STATS_PIO_RX = 0, CAN_STATS_PIO_TX, CAN_STATS_PIO_TX_HI, CAN_STATS_USR_RX_WAIT, CAN_STATS_USR_RX_WAIT_INT, CAN_STATS_USR_RX_TIMEOUT, CAN_STATS_USR_RX_PARTIAL, CAN_STATS_BUS_OFF, CAN_STATS_STATUS_ERR, CAN_STATS_RX_IP_FIFO_OVF, CAN_STATS_RX_USR_FIFO_OVF, CAN_STATS_TX_TIMEOUT, CAN_STATS_TX_LP_FIFO_FULL, CAN_STATS_RX_USR_FIFO_FULL, CAN_STATS_TX_HP_FIFO_FULL, CAN_STATS_CRC_ERR, CAN_STATS_FRAME_ERR, CAN_STATS_STUFF_ERR, CAN_STATS_BIT_ERR, CAN_STATS_ACK_ERR, CAN_STATS_NUM }; /* channel type definition */ enum zynq_chan_type { ZYNQ_CHAN_INVAL, ZYNQ_CHAN_CAN, /* CAN channel */ ZYNQ_CHAN_VIDEO, /* Video channel */ ZYNQ_CHAN_TYPE_NUM }; #define ZYNQ_CHAN_MAX 16 #define ZYNQ_STATS_MAX 32 typedef struct ioc_zynq_stats { struct { enum zynq_chan_type type; unsigned int devnum; unsigned long stats[ZYNQ_STATS_MAX]; } chs[ZYNQ_CHAN_MAX + 1]; } ioc_zynq_stats_t; /* Fixed embedded data header: 00 0A 00 AA 00 30 00 A5 00 00 00 5A */ #define EM_HDR_LEN 12 #define EM_HDR_DWORD0 0xAA000A00 #define EM_HDR_DWORD1 0xA5003000 #define EM_HDR_DWORD2 0x5A000000 #define EM_HDR_MASK 0xFFFF00FF #define EM_REG_CHIP_VER 0x3000 /* Common */ #define EM_REG_FRAME_CNT_HI 0x2000 /* AR0231 only */ #define EM_REG_EXP_T1_ROW 0x2020 /* AR0231 only */ /* AR0230, single register group from 0x3000 */ #define EM_REG_OFFSET_BASE_230 0x0004 #define EM_REG_OFFSET_FRAME_LNS_230 0x0034 /* Register 0x300A */ #define EM_REG_OFFSET_LINE_PCK_230 0x003C /* Register 0x300C */ #define EM_REG_OFFSET_COARSE_INT_230 0x0054 /* Register 0x3012 */ #define EM_REG_OFFSET_FRAME_CNT_230 0x00F4 /* Register 0x303A */ /* AR0231, register group 0x2000 - 0x2018 */ #define EM_REG_OFFSET_BASE1_231 0x0004 #define EM_REG_OFFSET_FRAME_CNT_HI_231 0x000C /* Register 0x2000 */ #define EM_REG_OFFSET_FRAME_CNT_LO_231 0x0014 /* Register 0x2002 */ /* AR0231, register group 0x2020 - 0x2050 */ #define EM_REG_OFFSET_BASE2_231 0x0074 #define EM_REG_OFFSET_EXP_T1_ROW_231 0x007C /* Register 0x2020 */ #define EM_REG_OFFSET_EXP_T2_ROW_231 0x0084 /* Register 0x2028 */ #define EM_REG_OFFSET_EXP_T3_ROW_231 0x008C /* Register 0x2030 */ #define EM_REG_OFFSET_EXP_T1_CLK_HI_231 0x009C /* Register 0x2028 */ #define EM_REG_OFFSET_EXP_T1_CLK_LO_231 0x00A4 /* Register 0x202A */ #define EM_REG_VAL_MSB(buf, x) \ (*((unsigned char *)(buf) + (x) + 1)) #define EM_REG_VAL_LSB(buf, x) \ (*((unsigned char *)(buf) + (x) + 5)) #define EM_REG_VAL(buf, x) \ ((EM_REG_VAL_MSB(buf, x) << 8) + EM_REG_VAL_LSB(buf, x)) #define EM_REG_VAL_230(buf, x) \ EM_REG_VAL(buf, EM_REG_OFFSET_ ## x ## _230) #define EM_REG_VAL_231(buf, x) \ EM_REG_VAL(buf, EM_REG_OFFSET_ ## x ## _231) #define EM_DATA_VALID(buf) \ ((((unsigned int *)(buf))[0] == EM_HDR_DWORD0) && \ ((((unsigned int *)(buf))[1] & EM_HDR_MASK) == \ (EM_HDR_DWORD1 & EM_HDR_MASK)) && \ ((((unsigned int *)(buf))[2] & EM_HDR_MASK) == \ (EM_HDR_DWORD2 & EM_HDR_MASK))) #define DEFAULT_FRAME_LINES_230 1112 #define DEFAULT_LINE_PCK_230 2876 #define DEFAULT_PIXCLK_230 64000000 #define DEFAULT_FRAME_LINES_231 1238 #define DEFAULT_LINE_PCK_231 2580 #define DEFAULT_PIXCLK_231 64000000 #endif /* _ZYNQ_API_H_ */
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/esd/CHANGELOG
CHANGELOG for esd CAN driver ================================================================================== Copyright (c) 1996 - 2016 by esd electronic system design gmbh This software is copyrighted by and is the sole property of esd gmbh. All rights, title, ownership, or other interests in the software remain the property of esd gmbh. This software may only be used in accordance with the corresponding license agreement. Any unauthorized use, duplication, transmission, distribution, or disclosure of this software is expressly forbidden. This Copyright notice may not be removed or modified without prior written consent of esd gmbh. esd gmbh, reserves the right to modify this software without notice. electronic system design gmbh Tel. +49-511-37298-0 Vahrenwalder Str 207 Fax. +49-511-37298-68 30165 Hannover http://www.esd.eu Germany sales@esd.eu ================================================================================== Nomenclature: I20-cards: CAN-PCI/331, CPCI-CAN/331, CAN-ISA/331, CAN-PC104/331, CAN-PCI/360, CPCI-CAN/331, PMC-CAN/331, CAN-USB/331 (aka CAN-USB/Mini) SJA1000: CAN-PCI/200, CPCI-CAN/200, CAN-ISA/200, CAN-PC104/200, CAN-PCI/266, PMC-CAN/266, CAN-PCIe/200, CAN-PCI104/200 (C200 is used synonymically) REMOTE-I/F: CAN-PCI/405 (C405 is used synonymically) 82527: CAN-PC104/200-I MSCAN: - none, yet (embedded devices, only) PCI400: CAN-PCI/400, CPCI-CAN/400, PMC-CAN/400, CAN-PCIe/400 (C400 is used synonymically) PCIe402: CAN-PCIe/402, CAN-PCI/402, CPCIserial-CAN/402 (C402 is used synonymically) AMC4: AMC-CAN/4 USB400: CAN-USB/400 (U400 is used synonymically) ================================================================================== Note: The most recent version of the esd CAN driver may vary with your hardware. ================================================================================== VERSION | DATE | CHANGES | INITIALS ================================================================================== 3.10.4 11.05.2016 Release of 3.10.4 for PCIe402 for Linux (x86, x86_64) STM 10.05.2016 Release of 3.10.4 for PCI400 for Linux (x86, x86_64) STM Integrated FPGA image 00.63 (00.3F HEX). See below. 3.10.3 28.04.2016 Release of 3.10.3 for C400 for Windows OT Updated FPGA image to 00.63 (00.3F HEX). WB - Fixed issue on spartan 3e - Fixed busmaster DMA operation could not be disabled 26.04.2016 PCI400/PCIe402: MK Fix reported bitrate for ESDACC baudrates without CANIO_NO_IMPLICIT_CLK_DIV. 3.10.2 02.02.2016 Release of 3.10.2 for C402 for Windows OT 3.10.2 29.01.2016 Release of 3.10.2 for C400 for Windows OT 4.0.2 26.01.2016 Release of 4.0.2 for USB400 for Windows OT Updated FPGA image to 00.62 (00.3E HEX) WB - Added BM Statistics feature and disable register for irq counter updates which reduces protocol overhead and improves performance. 3.10.0 20.01.2016 Release of 3.10.0 for C402 for RTX and RTX64 2014 OT Release of 3.10.0 for C200 for RTX and RTX64 2014 OT 3.10.0 19.01.2016 Release of 3.10.0 for C400 for RTX and RTX64 2014 OT 3.10.0 10.12.2015 Release of 3.10.0 for PCIe402 for Windows OT 3.10.3 02.12.2015 Release of 3.10.3 for amc825 for Linux (x86, x86_64) STM 02.12.2015 Release of 3.10.3 for PCI400 for Linux (x86, x86_64) STM 02.12.2015 Release of 3.10.3 for PCIe402 for Linux (x86, x86_64) STM Updated FPGA image to 00.61 (00.3D HEX). Got small changes to fix defects for timing corner cases found during the certification process. This version is now certified to conform to "ISO 16845:2004". 02.12.2015 Linux, QNX, VxWorks on PCI400/PCIe402: STM Added support for NTCAN_RESET_CTRL_EC in library and driver. 3.10.2 18.11.2015 Release of 3.10.2 for AIM AMC825 for WB Linux (x86, x86_64) 18.11.2015 Linux: WB Fixed hangup in canSend when sending synchronous event. 3.10.1 18.09.2015 Release of 3.10.1 for pci405 (c405) for VxWorks 6.x STM as VxBus (Rev. 4) UP and SMP driver (ARCH=pentium) 16.09.2015 VxWorks: STM Added support for NTCAN_IOCTL_GET_INFO in library and driver. 3.10.0 04.09.2015 Release of 3.10.0 for PCI405 for QNX6 TA 3.10.0 02.09.2015 Release of 3.10.0 for c405 for RTX 2009/2011/2012 OT 3.10.1 28.08.2015 Full range of Linux driver / library releases to STM switch library to version 4.x (libntcan.so.4). This version of the library is binary incompatible with the old version 3.x releases and requires recompilation of all applications. The new version also introduces symbol versioning. 28.08.2015 Release of 3.10.1 for AMC4 for Linux (x86, x86_64) STM 28.08.2015 Release of 3.10.1 for amc825 for Linux (x86, x86_64) STM 28.08.2015 Release of 3.10.1 for ISA200 for Linux (x86, x86_64) STM The x86_64 variant can't be testet due to lack of a 64-bit capable ISA system. 28.08.2015 Release of 3.10.1 for ISA331 for Linux (x86, x86_64) STM The x86_64 variant can't be testet due to lack of a 64-bit capable ISA/PC104 system. 28.08.2015 Release of 3.10.1 for PCI200 for Linux (x86, x86_64) STM 28.08.2015 Release of 3.10.1 for PCI331 for Linux (x86, x86_64) STM 28.08.2015 Release of 3.10.1 for PCI360 for Linux (x86, x86_64) STM 28.08.2015 Release of 3.10.1 for PCI400 for Linux (x86, x86_64) STM 28.08.2015 Release of 3.10.1 for PCI405 for Linux (x86, x86_64) STM 28.08.2015 Release of 3.10.1 for PCIe402 for Linux (x86, x86_64) STM Updated FPGA image to 00.58 (00.3A HEX). Got small changes to fix defects for timing corner cases found during the certification process. 3.10.0 24.08.2015 Release of 3.10.0 for c405 for Windows OT 18.08.2015 Nucleus/PCI405 TA Fixed crash on enabled SmartDisconnect with PCI405. 3.10.2 29.06.2015 Release for PCI400 for LynxOS(x86/DRM) TA 23.06.2015 LynxOS: Changes needed for static driver option 22.06.2015 LynxOS Bugfix: canSend returns error but sent frames 3.10.1 12.06.2015 First Release for PCI400 for LynxOS(x86/DRM) TA 11.06.2015 LynxOS Bugfixes: TA Driver does only work on 100 hz System(ADDON detection) >= 2 threads on 1 handle can crash the kernel in close canRead can crash the kernel 09.06.2015 Nucleus: TA canIdRegionAdd/Delete with inv. para does not clr count 08.06.2015 LynxOS Bugfixes: TA TX obj mode can crash the kernel Timestamed tx window default not working NTCAN_IOCTL_GET_INFO is missing Internal driver sleeps do not wait long enough Legacy filter canIdAdd/Delete with inv. para ret OK 3.10.0 04.06.2015 First Beta Release for PCI400 for LynxOS(x86/DRM) TA 3.10.0 04.06.2015 Release for amc825 for VxWorks 6.x STM as "esdcan"(legacy) and DKM (UP+SMP) (ARCH=ppc/CPU=PPC32) 3.10.0 04.06.2015 Release for amc825 for VxWorks 5.5 STM as DKM (UP driver only) (ARCH=ppc) 3.10.0 04.06.2013 Release for pci400 (c400) for VxWorks 6.x STM as VxBus (Rev. 4) UP and SMP driver (ARCH=pentium) 3.10.0 04.06.2015 Release for pci400 (c400) for VxWorks 5.4 STM as DKM (UP driver only) (ARCH=ppc) (built only) 03.06.2015 From now on we have support for good old LynxOS TA 3.10.0 03.06.2015 Release for pci400 (c400) for VxWorks 6.x STM as "esdcan"(legacy) and DKM (UP+SMP) (ARCH=ppc/CPU=PPC32) 3.10.0 03.06.2015 Release for pci400 (c400) for VxWorks 5.5 STM as DKM (UP driver only) (ARCH=ppc) 4.0.0 02.06.2015 Release of 4.0.0 for USB400 for Windows OT 3.10.0 27.03.2015 Release of 3.10.0 for PCI200 for QNX6 TA Release of 3.10.0 for PCI400 for QNX6 TA Release of 3.10.0 for PCIe402 for QNX6 TA 3.9.80 30.01.2015 Release of 3.9.80 for PCI400 for RTX64 2014 OT 4.0.0 26.01.2015 Release of 4.0.0 for PCIe402 for Windows OT 4.0.0 26.01.2015 Release of 4.0.0 for PCI400 for Windows OT 3.10.0 20.01.2015 Release of 3.10.0 for PCI400 for Windows OT 3.10.0 13.01.2015 Release of 3.10.0 for PCIe402 for Linux (x86, x86_64) STM 3.10.0 13.01.2015 Release of 3.10.0 for PCI400 for Linux (x86, x86_64) STM 13.01.2015 PCI400, PCIe402: Updated to FPGA release 00.54 STM This fixes the deadlock for reenabling bus-error IRQs (see Mantis #2481 below) on FPGA level. This fixes the possible transmission of an old CAN ID from the standard TX FIFO when a frame is waiting for transmission in the TS (Time Stamped) TX FIFO on FPGA level. 13.01.2015 Added IOCTL_ESDCAN_GET_INFO on driver level. STM Only accessible with NTCAN library 3.5.3 and up. 3.9.84 19.12.2014 Release of 3.9.84 for PCI400 for Windows OT 3.9.6 24.11.2014 Release of 3.9.6 for PCIe402 for RTX64 2014 OT 3.9.6 31.10.2014 Release of 3.9.6 for PCIe402 for Linux (x86, x86_64) STM 3.9.5 31.10.2014 Release of 3.9.5 for AMC4 for Linux (x86, x86_64) STM 3.9.83 31.10.2014 Release of 3.9.83 for PCI400 for Linux (x86, x86_64) STM 31.10.2014 AMC4, PCI400, PCIe402: Work around deadlock that occurs STM when enabling again bus-error IRQs after IRQ throttle caused in error-passive state (see Mantis #2481). This work around is not enabled in the trunk. 31.10.2014 Linux: Fix hang in canClose() after STM NTCAN_CONTROLLER_BUSY (see Mantis #2461) 31.10.2014 AMC4, PCI400, PCIe402: Fix driver blocked on node lock STM polling for controller recovery after bus-off condition (see Mantis #2461) 3.9.5 24.09.2014 Release of 3.9.5 for PCIe402 for RTX64 2013 OT 3.9.3 07.08.2014 Release of 3.9.3 for Sitara/DCAN for Linux MF 3.9.82 22.07.2014 Release of 3.9.82 for PCI400 for Linux STM 3.9.4 10.07.2014 Release of version 3.9.4 for isa331 for Linux STM 3.9.4 30.06.2014 Release of 3.9.4 for AMC4 for Linux (x86, x86_64) STM 3.9.02 14.05.2014 Release of version 3.9.02 for pci360 for QNX6 TA 12.05.2014 Fix unwanted use of different tx queues in cpci-360 MK 3.9.6 07.04.2014 Release of 3.9.6 for PCIe402 for Windows OT 3.9.01 01.04.2014 Release of version 3.9.01 for pci360 for QNX6 TA 26.03.2014 PCI331: Avoid PCI write buffer issue with IRQ reset STM (see Mantis #2329) 05.02.2014 PCIxxx, QNX: TA Added IRQ Overload Option for buggy pci-XXX Servers in some QNX BSP's. 3.9.4 04.02.2014 Release of 3.9.4 for PCI331 for Linux BL 3.9.3 03.02.2014 Release of 3.9.3 for PCI200 for Linux BL 3.9.81 03.02.2014 Release of 3.9.81 for PCI400 for Linux BL 3.9.5 03.02.2014 Release of 3.9.5 for PCIe402 for Linux BL PCI400, Linux: Added IRIG-B library (for PMC-CAN/400-4I) to release archive PCIe402, Linux: Firmware updater added to archive 3.9.81 20.12.2013 Release of 3.9.81 of amc825 for VxWorks 6.x STM as "esdcan"(legacy) and DKM (UP+SMP= driver (ARCH=ppc) 3.9.4 20.12.2013 Release of 3.9.4 for pci200 (c200) for VxWorks 6.x STM as "esdcan"(legacy) and DKM (UP+SMP= driver (ARCH=ppc) 3.9.3 20.12.2013 Release of 3.9.3 for pci331 (c331) for VxWorks 6.x STM as "esdcan"(legacy) and DKM (UP+SMP= driver (ARCH=ppc) 3.9.81 20.12.2013 Release of 3.9.81 for pci400 (c400) for VxWorks 6.x STM as "esdcan"(legacy) and DKM (UP+SMP= driver (ARCH=ppc) 3.9.3 05.12.2013 Release of 3.9.3 for pci200 (c200) for VxWorks 6.x STM as VxBus (Rev. 4) UP and SMP driver (ARCH=pentium) 3.9.2 05.12.2013 Release of 3.9.2 for pci331 (c331) for VxWorks 6.x STM as VxBus (Rev. 4) UP and SMP driver (ARCH=pentium) 3.9.80 05.12.2013 Release of 3.9.80 for pci400 (c400) for VxWorks 6.x STM as VxBus (Rev. 4) UP and SMP driver (ARCH=pentium) 3.9.5 05.12.2013 Release of 3.9.5 for pcie402 (c402) for VxWorks 6.x STM as VxBus (Rev. 4) UP and SMP driver (ARCH=pentium) 3.9.2 05.12.2013 Release of 3.9.2 for pci405 (c405) for VxWorks 6.x STM as VxBus (Rev. 4) UP and SMP driver (ARCH=pentium) 3.9.6 19.11.2013 Release of 3.9.6 for pcie402 for QNX6 TA 3.9.80 19.11.2013 Release of 3.9.80 for pci400 for QNX6 TA 3.9.2 31.10.2013 Release of 3.9.2 for pci200 for VxWorks >= 6.7 STM as VxBus (Rev. 4) UP and SMP driver (ARCH=pentium) PCIe402: BL Fixed: Slightly wrong hardware timer speed Fixed: MSI not working depending on given address PCI400/PCIe402: BL Fixed: In rare conditions TX Acknowledgte got lost after Bus Off (leading to application not exiting correctly) Fixed: After bus off it was possible to receive a frame, which transmitted by the same node before bus off 3.9.5 21.10.2013 Release of 3.9.5 for pci405 for Linux BL 3.9.5 09.10.2013 Release of 3.9.5 for PCIe402 for RTX OT 3.9.79 30.09.2013 Release of 3.9.79 for c400 for VxWorks (ppc) 5.5, 6.9 STM 3.9.4 19.09.2013 Release of 3.9.4 for pcie402 for QNX6 TA 3.9.79 13.09.2013 Release of 3.9.79 for amc825 for VxWorks 5.5, 6.6 (ppc) BL 3.9.79 13.09.2013 Release of 3.9.79 for amc825 for Windows BL 3.9.3 13.09.2013 Release of 3.9.3 for c200 for RTX 2009/2011/2012 OT 3.9.79 13.09.2013 Release of 3.9.79 for c400 for RTX 2009/2011/2012 OT 3.9.79 12.09.2013 Release of 3.9.79 for amc825 for Linux BL PCIe402: BL Added new autobaud method, faster and more reliable results PCI400: BL Autobaud slightly improved (new mode is still PCIe402, only, but will follow on CAN-PCI/400 soon) PCI400+PCIe402: BL Fixed a bug with bit errors leading to active error frames occurring while controller is in listen-only-mode Fixed a problem with resynchronisation on CAN busses with bad signal conditions and slow baudrates Linux: BL+MK Tested up to kernel 3.10 Bugfix: canTake() returning NTCAN_PENDING_READ under certain conditions Changed: Startup banner cleanup and less text by default, more may be selected via verbose option 3.9.3 11.09.2013 Release of 3.9.3 for c405 for RTX 2009/2011/2012 OT Release of 3.9.3 for c331 for RTX 2009/2011/2012 3.9.4 30.08.2013 Release of 3.9.4 for PCIe402 for RTX64 2013 OT 3.9.4 30.08.2013 Release of 3.9.4 for PCIe402 for RTX OT 3.9.77 16.08.2013 Release of 3.9.77 for amc825 for VxWorks 5.5, 6.6 (PPC) BL 3.9.77 14.08.2013 Release of 3.9.77 for PCI400 (CAN/400) for Windows OT 3.9.4 14.08.2013 Release of 3.9.4 for pcie402 for Linux BL 3.9.5 13.08.2013 Release of 3.9.5 for pci405 for Windows OT 3.9.3 12.08.2013 Release of 3.9.3 for PCIe402 for Windows OT 3.9.3 02.08.2013 Release of 3.9.3 for pcie402 for Linux BL PCI400: BL Driver option to select the point of timestamping on RX traffic (EOF (default, same as before) and SOF) Hardware support for "Timestamped TX" (see NTCAN-API man ual) Bugfix: Race condition on SMP systems fixed (caused lagging TX) Linux: BL Bugfix: Wrongly returned len-parameter on canWrite() in succesion of canSend() 3.9.2 18.07.2013 Release of 3.9.2 for PCIe402 for RTX 2012 OT 3.9.2 12.07.2013 Release of 3.9.2 for PCIe402 for RTX64 2013 OT 3.9.2 08.07.2013 Release of 3.9.2 for pci405 for RTX 8.x / 2009 /2011 OT 3.9.74 08.07.2013 Release of 3.9.74 for PCI400 (CAN/400) for RTX 8.x / 2009 /2011 OT 3.9.2 28.06.2013 Release of 3.9.2 for PCIe402 for Windows OT 3.9.74 13.06.2013 Release of 3.9.74 for PCI400 (CAN/400) for Linux BL 3.9.74 31.05.2013 Release of 3.9.2 for c200 for RTX64 2013 OT 3.9.2 31.05.2013 Release of 3.9.74 for c400 for RTX64 2013 OT 3.9.74 21.03.2013 Release of 3.9.71 for pci400 for VxWorks >= 6.7 OT as VxBus (Rev. 4) UP and SMP driver 3.9.1 21.03.2013 Release of 3.9.1 for pci200 for VxWorks >= 6.7 OT as VxBus (Rev. 4) UP and SMP driver 3.9.1 21.03.2013 Release of 3.9.1 for pci331 for VxWorks >= 6.7 OT as VxBus (Rev. 4) UP and SMP driver 3.9.1 21.03.2013 Release of 3.9.1 for pci405 for VxWorks >= 6.7 OT as VxBus (Rev. 4) UP and SMP driver 3.9.1 04.03.2013 Release of 3.9.1 for PCI400 based CAN on PMC-CPU/440 OT as part of the VxWorks 6.8/6.9 BSP (no VxBus) 3.9.72 04.02.2013 Release of 3.9.72 for PCI400 (CAN/400) for Windows OT 3.9.4 28.01.2013 Release of 3.9.4 for pci405 for Windows OT 3.9.71 11.01.2013 Release of 3.9.71 for PCI400 (CAN/400) for Windows OT Support for feature "Timestamped Tx" aka canSendT 3.9.71 12.12.2012 Release of 3.9.71 for PCI400 (CAN/400) for Linux BL PCI400: Automatic AddOn detection for CAN-PCI(e)/400 on driver startup 3.9.4 03.12.2012 Release of 3.9.4 for pci405 for QNX6 TA 3.9.3 03.12.2012 Release of 3.9.3 for pci200 for QNX6 TA 3.9.2 03.12.2012 Release of 3.9.2 for isa200 for QNX6 TA 29.11.2012 PCI405: TA Firmware Version 3.8.25 SJA1000: TA Bugfix: Under rare conditions can error handling can stall TX 3.9.70 20.11.2012 Release of 3.9.70 for pci400 for VxWorks >= 6.7 OT as VxBus (Rev. 4) UP and SMP driver 3.9.0 20.11.2012 Release of 3.9.0 for pci200 for VxWorks >= 6.7 OT as VxBus (Rev. 4) UP and SMP driver 3.9.0 20.11.2012 Release of 3.9.0 for pci331 for VxWorks >= 6.7 OT as VxBus (Rev. 4) UP and SMP driver 3.9.0 20.11.2012 Release of 3.9.0 for pci405 for VxWorks >= 6.7 OT as VxBus (Rev. 4) UP and SMP driver 3.9.4 25.10.2012 Release of 3.9.4 for pci405 for Linux BL 25.10.2012 Linux: BL Tested with kernels up to 3.6 3.9.71 22.10.2012 Release of 3.9.71 for amc825 for VxWorks 6.6 (x86) OT with VxBus (Rev. 3) 3.9.0 18.10.2012 Release of 3.9.0 for PCI400 based CAN on PMC-CPU/440 OT as part of the VxWorks 6.8/6.9 BSP (no VxBus) 3.9.70 29.08.2012 Release of 3.9.70 for pci400 for QNX6 TA 3.9.3 29.08.2012 Release of 3.9.3 for pci405 for QNX6 TA 3.9.2 29.08.2012 Release of 3.9.2 for pci331 for QNX6 TA 3.9.2 29.08.2012 Release of 3.9.2 for pci200 for QNX6 TA 3.9.1 29.08.2012 Release of 3.9.1 for isa200 for QNX6 TA 3.9.1 29.08.2012 Release of 3.9.1 for isa331 for QNX6 TA 28.08.2012 BUGFIX: SET_BUSLOAD_INTERVAL causes crash of pci405-firmware. TA 19.04.2012 QNX6: Bugfix: Workerthread for initphase may only receive pulses!! TA 3.9.70 27.03.2012 Release of 3.9.70 for PCI400 for VxWorks 5.4 OT 3.9.03 13.03.2012 Release of version 3.9.03 for pci405 for Windows OT 3.9.69 08.03.2012 Release of 3.9.69 for PCI400 for Linux BL 3.9.2 06.03.2012 Release of 3.9.2 for pci405 for QNX6 TA 02.03.2012 SJA1000: TA Bugfix: can error handling can stall the tx engine 01.03.2012 QNX6: TA Bugfix: Under rare conditions, timeout handling can occur at a wrong point in time. 28.02.2012 QNX6: TA Bugfix: canStatus does not initialize controller type 17.01.2012 All: TA Bugfix: Received CAN frame order can differ from physical order on the bus, if interaction comes into play. 3.9.68 27.12.2011 Release of 3.9.68 for amc825 for Linux, Win, VxWorks BL 3.9.1 22.12.2011 Release of 3.9.1 for pci331 for QNX6 TA 3.9.1 22.12.2011 Release of 3.9.1 for pci200 for QNX6 TA 3.9.0 22.12.2011 Release of 3.9.0 for isa200 for QNX6 TA 3.9.0 22.12.2011 Release of 3.9.0 for isa331 for QNX6 TA 3.9.67 21.12.2011 Release of 3.9.67 for pci400 for QNX6 TA 3.9.67 14.11.2011 Release of 3.9.67 for PCI400 for Linux BL 3.9.03 01.11.2011 Release of 3.9.03 for pci405 for Linux BL 01.11.2011 Linux: BL Tested with kernels up to 3.0.4 31.10.2011 Linux: BL Merged "preempt_rt" branch. Rewritten synchronization for canRead(), canWrite() and canClose(), which is used for all kernels > 2.6.20 from now on NOTE: From now on, the x86 32-Bit drivers for Linux kernels >= 2.6.0 are compiled for "i686" architecture. For x86_64 "k8" is chosen as target architecture. NOTE: These are the latest drivers available for 2.4.x kernels. esd will release updates for 2.4.x drivers only on special customer request. 3.9.02 18.10.2011 Release of version 3.9.02 for pci200 for Linux BL 3.9.01 23.09.2011 Release of version 3.9.01 for cpci405/cterm for QNX6 TA 22.08.2011 QNX6 BUGFIX: - PPC405 borads with >= 2 CAN-Nodes with dedicated IRQ's can get frozen 3.9.64 03.08.2011 Release of version 3.9.64 for pci400 for RTX 8.x/2009 OT 3.9.01 03.08.2011 Release of version 3.9.01 for pci405 for RTX 8.x/2009 OT Release of version 3.9.01 for pci331 for RTX 8.x/2009 Release of version 3.9.01 for pci200 for RTX 8.x/2009 03.08.2011 RTX Bugfix: - Disabled Rx timeout with previous 3.9.x release. 3.9.63 07.07.2011 Release of version 3.9.63 for pci400 for Windows (x64) OT 3.9.2 07.07.2011 Release of version 3.9.2 for pci405 for Windows (x64) OT 3.9.63 06.07.2011 Release of version 3.9.63 for pci400 for RTX 8.x/2009 OT 06.07.2011 RTX: OT Missing IoCtls added: NTCAN_IOCTL_RESET_CAN_ERROR_CNT Missing API-Functions added: canIdRegionAdd canIdRegionDelete Bugfix: - Removed trigger of timeout for IOCTL_CAN_SEND and IOCTL_CAN_TAKE. 3.9.01 15.12.2010 Release of version 3.9.01 for pci200 for Linux BL 3.9.04 13.12.2010 Release of version 3.9.00 for amc825 for vxWorks TA 13.12.2010 Bugfix: TX_OBJ Mode broken for 20b id's since TA merge of smart id filter 3.9.00 02.12.2010 Release of version 3.9.00 for isa331 for Linux BL 3.9.01 26.11.2010 Release of version 3.9.01 for pci405 for QNX6 TA 3.9.00 26.11.2010 Release of version 3.9.00 for pci360 for QNX6 TA 3.9.00 08.11.2010 Release of version 3.9.00 for pci331 for Linux BL 3.9.01 15.10.2010 Release of version 3.9.01 for pci405 for Windows TA 15.10.2010 Bugfix: pci405 load/unload could freeze System(#1149) MF+TA 3.9.00 22.09.2010 Release of version 3.9.00 for pci200 for Linux BL 20.09.2010 Linux: BL Changes to work with kernels up to 2.6.35 3.9.00 08.07.2010 Release of version 3.9.00 for pci405 for QNX6 TA Release of version 3.9.00 for pci331 for QNX6 Release of version 3.9.00 for pci200 for QNX6 17.06.2010 QNX: Bugfix: Coredump from _GET_BUSLOAD_INTERVAL, TA _GET_ERROR_COUNTER,_GET_BITRATE_DETAILS 16.06.2010 Smart ID Filter merged in TA 3.8.21 23.06.2010 Linux: BL Release rebuilt on different system to check incompatibility with customer system 3.8.20 14.06.2010 Linux: BL Fixes for RT patched Linux kernel 2.6.31-9-rt (Xubuntu): Timeouts work correctly now. 3.8.19 09.06.2010 Linux: BL Special release for kernel 2.6.31-9-rt (Xubuntu) 3.8.19 14.05.2010 Release of version 3.8.19 for pci331 for Linux BL 12.05.2010 Linux: Removed redundant include directory in BL release Makefile 3.8.19 21.04.2010 Release of version 3.8.19 for pci405 for RTX 8.x OT 21.04.2010 Release of version 3.8.19 for pci331 for RTX 8.x OT 21.04.2010 Release of version 3.8.19 for pci200 for RTX 8.x OT 21.04.2010 RTX: New Features: Support for canIoctl commands: NTCAN_IOCTL_SET_BUSLOAD_INTERVAL NTCAN_IOCTL_GET_BUSLOAD_INTERVAL NTCAN_IOCTL_GET_BUS_STATISTIC NTCAN_IOCTL_RESET_BUS_STATISTIC NTCAN_IOCTL_GET_CTRL_STATUS NTCAN_IOCTL_GET_BITRATE_DETAILS 3.8.19 29.04.2010 Release of version 3.8.19 for pci405 for Linux BL 16.04.2010 QNX: Bugfix: Driver can crash with delayed close. TA canClose does not block anymore. 22.03.2010 Bugfix: Busload event could crash under certain BL+MK conditions 16.03.2010 Linux+VxWorks: BL Added: Possibility to use NTCAN_HANDLEs in combination with select() 3.8.18 11.03.2010 Release of version 3.8.18 for pci200 for Linux BL 10.03.2010 Bugfix: Possibility to block in canClose(), TA if multiple handles are used on same net 3.8.17 23.02.2010 Release of version 3.8.17 for pci200 for Linux BL 22.02.2010 Linux: Changes to work with kernels up to 2.6.32 3.8.17 01.02.2010 Release of version 3.8.17 for pci405 for QNX6 TA Release of version 3.8.17 for pci331 for QNX6 Release of version 3.8.17 for pci200 for QNX6 25.01.2010 QNX performance update TA Less kernel calls for rx and tx. 3.8.16 14.12.2009 Release of version 3.8.16 for pci405 for QNX6 TA 10.12.2009 Bugfix: pci405 firmware could crash with TA NTCAN_IOCTL_GET_BUS_STATISTIC or NTCAN_IOCTL_GET_BITRATE_DETAILS 08.12.2009 QNX: TA Missing IoCtls added: NTCAN_IOCTL_ABORT_RX NTCAN_IOCTL_ABORT_TX NTCAN_IOCTL_SET_RX_TIMEOUT NTCAN_IOCTL_SET_TX_TIMEOUT NTCAN_IOCTL_SET_BUSLOAD_INTERVAL NTCAN_IOCTL_GET_BUSLOAD_INTERVAL NTCAN_IOCTL_GET_BUS_STATISTIC NTCAN_IOCTL_GET_CTRL_STATUS NTCAN_IOCTL_GET_BITRATE_DETAILS Missing API-Functions added: canIdaRangeAdd canIdRangeDelete 3.8.16 02.12.2009 Release of version 3.8.16 for pci405 for Linux AB 01.12.2009 Fixed: CAN-20b Autoanswer mode TA Remote-I/F: Fixed: Interaction in combination with autoanswer 3.8.10 16.10.2009 Release of version 3.8.10 for pci405 for QNX6 TA 3.8.10 16.10.2009 Release of version 3.8.10 for pci331 for QNX6 TA 16.10.2009 QNX: TA New -t option for thread pool size Senseless pulses from irq level removed. 15.10.2009 QNX: TA Several fixes, to make the driver thread save 09.10.2009 QNX: TA Resource-Manager is multithreaded from now on 08.10.2009 QNX: TA Resource-Manager will daemonize from now on 3.8.14 20.08.2009 Release of version 3.8.14 for pci405 for Linux AB 20.08.2009 Linux: AB Tested with kernels up to 2.6.30 19.08.2009 Fixed: Bug in AutoRTR feature AB If RTR was sent on the same net, where another handle has configured the AutoRTR object, multiple RTR replies were generated. 06.07.2009 Linux: AB Changes to keep track with and profit of general linux kernel changes. 3.8.12 23.06.2009 Release of version 3.8.12 for pci405 for Linux AB 18.06.2009 Linux: Fixed bug introduced with 3.8.11 3.8.8 17.06.2009 Release of version 3.8.8 for pci405 for QNX6 TA 23.04.2009 QNX6: Bugfix: Coredump on driver error exit TA Bugfix: -c Option does not work in pci405 driver Compiled with gcc 4.2.4 from now on 3.8.11 22.04.2009 Release of version 3.8.11 for pci405 for Linux AB 22.04.2009 Linux: AB Fixed: Another fix for canRead() in a multithreaded environment. 3.8.10 19.03.2009 Rerelease of version 3.8.9 AB (gcc-3 for x86 libraries) 3.8.9 17.03.2009 Release of version 3.8.9 for pci405 for Linux AB 03.03.2009 Linux: MK Fixed canIoctl commands (always returned with EINVAL): NTCAN_IOCTL_ABORT_RX NTCAN_IOCTL_ABORT_TX 3.8.8 27.02.2009 Release of version 3.8.8 for pci405 for Linux AB 26.02.2009 New Features: AB New canIoctl commands: NTCAN_IOCTL_GET_BUS_STATISTIC NTCAN_IOCTL_GET_CTRL_STATUS NTCAN_IOCTL_GET_BITRATE_DETAILS Fixed: Small bug in bitrate calculation (if bitrate was specified numerically, there was a possibility, that the resulting TSEG2 was too small) Linux: Fixed: Under certain conditions blocking calls (canRead(), canWrite()) did not work correctly, when interrupted by signals 02.02.2009 Linux: AB Fixed: Small glitch in BTR table introduced with 3.8.6 (regarding undocumented, customer specific indeces) 3.8.6 10.12.2008 Release of version 3.8.6 for pci200 for Linux AB 3.8.6 10.12.2008 Release of version 3.8.6 for pci360 for Linux AB 3.8.6 09.12.2008 Release of version 3.8.6 for pci331 for Linux AB 04.12.2008 Fixed: Close/Abortion of an autobaud handle AB Change: Autobaud can be combined with LOM, now Change: Autobaud got optimized (faster detection) SJA1000: Change: Small changes to predefined baudrates to increase maximum possible cable length Fixed: No more error events, while autobaud USB331: Fixed: Baudrate change event PCI405/Linux: Fixed: Possibility for a crash on driver load on SMP systems (this had no consequences for runtime) Linux: Fixed: Build issues up to 2.6.28-RC7 3.8.5 07.10.2008 Release of version 3.8.5 for mecp52 for QNX6 TA 07.10.2008 Support for 16/33/66 Mhz MSCAN Clock TA QNX: - New option -C for controller clock overriding. 3.8.0 02.10.2008 Release of version 3.8.0 for pci331 for RTX 7.x OT 3.8.4 23.07.2008 Release of version 3.8.4 for pci331 for QNX6 TA 23.07.2008 The change of the maximum supported card instances now works under QNX and is tested with 5 pci331 boards TA 3.8.3 22.07.2008 Release of version 3.8.3 for pci331 for QNX6 TA 22.07.2008 Maximum supported card instances changed from 4 to 16 TA 3.8.3 06.06.2008 Release of version 3.8.3 for usb331 for Linux AB NOTE FOR CAN-USB-Mini CUSTOMERS: esdcan-usb331 supports kernels <= 2.6.24 Kernel 2.6.25 and following can not be supported right now! We're working on a new solution for kernels > 2.6.25, unfortunately this is not available, yet. PCI, PCIe or ISA drivers are NOT affected. 05.06.2008 Linux, Kernel 2.6.x: AB Hopefully fixed all build issues with kernels >= 2.6.24 05.06.2008 Linux (x86_64 kernels < 2.6.10): AB Bugfix: busload IOCTLs didn't work 04.06.2008 Linux (Kernels > 2.6.10): AB Bugfix: Certain IOCTLs (FLUSH_RX_FIFO, PURGE_TX_FIFO, SCHEDULE_START, SCHEDULE_STOP, SET_ALT_RTR_ID) did not work, when used in a 32-Bit application in combination with a x86_64 kernel and driver 04.06.2008 Linux: MK Fixed false load statistics of driver in xosview and top. This fixes watchdog warnings on kernels > 2.6.25, too 03.06.2008 usb331, Linux: MK Bugfix: System freeze on certain system/kernel combinations 3.8.2 23.05.2008 Release of version 3.8.2 for pci200 for QNX6 TA Release of version 3.8.2 for pci405 for QNX6 Release of version 3.8.2 for pci360 for QNX6 Release of version 3.8.2 for isa200 for QNX6 Release of version 3.8.2 for isa331 for QNX6 3.8.2 23.05.2008 Release of version 3.8.2 for pci405 for Linux AB 23.05.2008 Linux: Fixed timeouts influencing canSend() AB 3.8.2 23.05.2008 Release of version 3.8.2 for pci331 for QNX6 TA QNX: TA - Bugfix: Disarm of timer does not work and causes a immediate timer run. - Bugfix: After disarm/change timer expiry a just queued pulse causes a spurious timer run. - Better verbose messages 22.05.2008 Linux: Small fix for new kbuild trees MK (kernels > 2.6.24) 3.8.0 20.03.2008 Release of version 3.8.0 for pci405 for Linux AB 19.03.2008 Linux: Tested with kernels up to 2.6.25 AB 3.8.1 19.03.2008 Release of version 3.8.1 for pci405 for W2K/XP TA 3.8.1 19.03.2008 Release of version 3.8.1 for pci405 for QNX6 TA 19.03.2008 pci405: TA Bugfix: In rare occasions host driver wasn't loaded successfully. 3.8.0 12.03.2008 Release of version 3.8.0 for pci405 for QNX6 TA 3.8.0 12.03.2008 Release of version 3.8.0 for isa200 for QNX6 TA 3.8.0 12.03.2008 Release of version 3.8.0 for pci2xx for QNX6 TA 3.8.0 12.03.2008 Release of version 3.8.0 for pci331 for QNX6 TA 12.03.2008 QNX6: Bugfix: backend prio is limited to 63 3.8.0 08.03.2008 Release of version 3.8.0 for pci405 for RTX 7.x OT 08.03.2008 RTX: New feature: Scheduling (drivers for other systems had this before) Bugfix: Prevent handle buffer overrun for Tx I/O 3.8.0 29.02.2008 Release of version 3.8.0 for pci405 for W2K/XP TA 3.8.0 28.02.2008 Major update on scheduling feature: TA - increased accuracy - automatic data changes (counters, etc.) Please refer to ntcan.h for now. CAN-API documentation will follow soon. - Order of frames with same schedule relates to their CAN priorities - Bugfix: "bursts of CAN frames" 3.7.4 27.02.2008 Release of version 3.7.4 for pci331 for QNX6 TA 26.02.2008 I20 firmware update added to QNX6 driver TA 05.11.2008 Added feature: AB New commands for canIoctl() for generation of busload statistics, please refer to CAN-API manual. 3.7.5 11.07.2007 Release of version 3.7.5 for pci405 for W2K/XP TA 3.7.6 09.07.2007 Release of version 3.7.6 for pci2xx for QNX6 TA 3.7.7 05.06.2007 Release of version 3.7.7 for pci2xx for Linux AB 05.06.2007 Linux: New format of release archives: AB Old format (gzipped tar archives (.tgz)) was changed into password protected zip-archives (.zip) containing a tar-archive Password: esdCAN2007 04.06.2007 SJA1000: Added evaluation of VPD AB => e.g. canStatus() can show serial number Boards currently supporting this feature: CAN-PCI104/200, CAN-PCIe/200, CAN-PMC/266 01.06.2007 Added support for CAN-PMC/266 AB 3.7.4 29.05.2007 Release of version 3.7.4 for pci405 for Windows TA 28.05.2007 Windows: TA Bugfix: After first installation of the wdm pci405 driver you get wrong net numbers in the settings dialog of the device manager Bugfix: The first diver start under Vista fails 24.05.2007 Bugfix: New data is not transmitted TA at the first schedule event after an UPDATE call but at the second event 23.05.2007 pci405: TA Bugfix: firmware scheduling durations are wrong on fast systems (Firmware=3.7.2,Driver=3.7.3). 3.7.6 16.05.2007 Release of version 3.7.6 for pci200 for Linux AB 3.7.4 14.05.2007 Release of version 3.7.4 for pci200 for RTX 6.x OT 12.05.2007 Corrected name: CAN-PCIe/2000 -> CAN-PCIe/200 AB 10.05.2007 pci331: Optimized PCI access TA 10.05.2007 pci200: Fixed "Lost TX interrupts on Host-Retry" TA On certain systems a TX-Done interrupt could get lost, resulting in an inability to send CAN frames 3.7.4 10.05.2007 Release of version 3.7.4 for pci360 for Linux AB 02.05.2007 Fixed CAN-PCI/360 firmware (0.C.22) problem with RA nets 2+3, which was introduced with release 3.7.3 3.7.3 05.04.2007 Release of version 3.7.3 for pci360 for Linux AB 3.7.5 04.04.2007 Release of version 3.7.5 for pci200 TA x86/ppcbe QNX6 New card option "sdid=xxx" Support of PCI104-200 01.04.2007 Linux drivers tested up to kernel.org 2.6.20.4 AB 27.03.2007 Linux: Fixed typo which affected compilation on AB Linux kernels < 2.6.10 on x86_64 3.7.4 22.02.2007 Release of version 3.7.4 for pci405 for TA x86/ppcbe QNX6 3.7.4 25.01.2007 Release of version 3.7.4 for pci331 for AB PPC-Linux 2.6.x 3.7.3 15.01.2007 Release of version 3.7.3 for pci405 for Linux AB 3.7.4 09.01.2007 Release of version 3.7.4 for pci200 for QNX6 TA 08.01.2007 QNX6: buffer overflow fixed in ntcan library TA QNX6: timeout handling fixed in driver, to use only one of the 128 pulse codes. Now this no longer limits the maximal open count in the driver 3.7.3 05.01.2007 Release of version 3.7.3 for isa200 for Linux AB 3.7.3 04.01.2007 Release of version 3.7.3 for pci2xx for Linux AB 3.7.3 04.01.2007 Release of version 3.7.3 for pci331 for Linux AB 03.01.2007 Added PMC331 (3,3V) to the list of the supported AB I20 boards 02.01.2007 pci331: Small changes to increase robustness in AB case of hardware defects 3.7.3 22.12.2006 Release of version 3.7.3 for usb331 for Linux AB 21.12.2006 Linux: Fixed compatibility issues with AB kernels up to 2.6.19 3.7.3 06.12.2006 Release of version 3.7.3 for pci405 for Windows TA 3.7.3 28.11.2006 Release of version 3.7.3 for pci405 for RTX 6.x OT RTX: Fixed possible block in driver calling canClose() RTX: Improved debug output of PCI bus scan. 3.7.3 23.11.2006 Release of version 3.7.3 for isa200 for QNX 6 TA 3.7.3 23.11.2006 Release of version 3.7.3 for isa331 for QNX 6 TA 3.7.3 23.11.2006 Release of version 3.7.3 for pci200 for QNX 6 TA 3.7.3 23.11.2006 Release of version 3.7.3 for pci331 for QNX 6 TA 20.11.2006 Support for new bootloader on PCI405 board. MF New FPGA image for PCI405 to improve hardware timstamping and to support a different way to signal interrupts to the firmware (without using PCI configuration cycles). The bootloader if updated through the host driver. After update the host driver will fail to load and a reboot of the PC is required! After the update the PCI405 boards do not work with any versions before 3.7.2 of the host driver. 16.11.2006 Linux, Windows, QNX: Fixed RX-Object mode AB+MT+OT 3.7.0 30.10.2006 Release of version 3.7.0 for isa331 for Linux AB 27.10.2006 Fixed small problem with net 1 in ISA331 firmware MK Please use provided updisa331 tool 3.7.0 13.10.2006 Release of version 3.7.0 for cpci405(ab), c405_20m MF 3.7.0 12.10.2006 Release of version 3.7.0 for pci331 for Linux AB 3.7.0 12.10.2006 Release of version 3.7.0 for pci405 for Linux AB 3.7.0 12.10.2006 Release of version 3.7.0 for pci2xx for Linux AB 11.10.2006 Added PCIe2000 (coming SJA1000 based PCIe-board) AB 11.10.2006 Linux: Fix for compilation problem with SuSE > 10.0 AB 29.09.2006 Corrections to BTR calculation AB 29.09.2006 Fixed endianess problem in baudrate change event AB (REMOTE-I/F, USB331) 28.09.2006 Various bugfixes in TX-scheduling MK 3.6.0 14.09.2006 Release of version 3.6.0 for pci266 for QNX 6 MT 3.6.1 14.09.2006 Release of version 3.6.1 for pci405 for QNX 6 MT 3.6.0 14.09.2006 Release of version 3.6.0 for pci331 for QNX 6 MT 04.07.2006 Numerical setting of baudrate for USB331 and 82527 AB 29.06.2006 Linux-Bugfix: Under certain bus error conditions AB it was possible, that a canWrite() returned too early (reporting zero frames sent) and a subsequent canWrite() reported too many sent frames (the ones from the job before). This bug did _not_ lead to unsent frames or lost data. 29.06.2006 SJA1000-Bugfix: Under certain bus error conditions AB it was possible, that an old frame was sent, although user job was already aborted. 29.06.2006 Added features: AB - Autobaud (automatic baudrate detection) Currently usable with: SJA1000 REMOTE-I/F MSCAN - Baudrate change event - Numerical setting of baudrate (calculation of BTR values) Currently usable with: I20 (all except USB331) SJA1000 REMOTE-I/F MSCAN - Extended error information event Currently generated by: SJA1000 REMOTE-I/F NOTE: This feature adds some load to your system in error conditions (should be negligible, though). The behaviour in error conditions has changed (frames might get aborted before timeout due to bus errors). New error code NTCAN_CONTR_ERR_PASSIVE. NOTE: Under Linux this feature can be disabled with errorinfo=0 as module load parameter. - Type of CAN-controller is reported in upmost byte of board_status (canStatus()) 3.6.1 19.06.2006 Release of version 3.6.1 for isa200 for QNX 6 MT 3.6.3 16.06.2006 Release of version 3.6.3 for pci331 for Linux AB 3.6.0 02.05.2006 Release of version 3.6.0 for usb331 for Linux AB 28.04.2006 USB331: AB - added use of hardware timestamping with firmwares > 0.C.4E 28.04.2006 Linux USB331: AB - output of serial number is supported, now - changed to work with kernels >= 2.6.14 24.04.2006 Changes for Linux kernel > 2.6.10: AB - use of compat_ioctl (needed for 32-Bit appplications on 64-Bit systems) - use of unlocked_ioctl (might result in performance advantage on SMP systems) 3.6.3 21.03.2006 Release of version 3.6.3 for pci200 for RTX 6.x OT 3.6.3 20.03.2006 Release of version 3.6.3 for pci360 for RTX 6.x OT 3.6.3 16.03.2006 Release of version 3.6.3 for pci331 for RTX 6.x OT 3.6.3 13.03.2006 Release of version 3.6.3 for pci405 for RTX 6.x OT 3.6.0 08.03.2006 Release of version 3.6.0 for isa200 for QNX 6 MT 3.6.0 17.02.2006 Release of version 3.6.0 for pci405 for QNX 6 MT 3.6.0 02.03.2006 Release of version 3.6.0 for cpci750 MF 3.6.2 14.02.2006 Release of version 3.6.2 for cpci405 MF 14.02.2006 Fixed some compiler warnings when using gcc 4.x MF with Linux (on PPC/cpci405: esdcan.c) Pass ARCH=... to kernel make process to allow cross compilation with 2.6 kernels 3.6.1 26.01.2006 Release of version 3.6.1 for cpci405, c405_20m MF 3.6.2 06.12.2005 Release of version 3.6.2 for pci331 for Linux AB 06.12.2005 I20-Bugfix: Possible deadlock on driver unload AB This bug needed several things to occurr simultaneously: - slow host system - multiple PCI331 - high load directly before unloading the driver 3.6.2 05.12.2005 Release of version 3.6.2 for pci331 for RTX 6.x OT 3.6.2 05.12.2005 Release of version 3.6.2 for pci405 for RTX 6.x OT 3.6.0 08.11.2005 Release of version 3.6.0 for isa200 for Linux AB 3.6.1 03.11.2005 Release of version 3.6.1 for pci200 for Linux AB 3.6.2 03.11.2005 Release of version 3.6.2 for pci405 for Linux AB 03.11.2005 Fixed reinitialization of CAN-controller, if AB canSetBaudrate() is called twice with the same baudrate (bug was introduced with last release, version 3.6.1 of pci405 appeared in public, only) 3.6.1 01.11.2005 Release of version 3.6.1 for pci405 for Linux AB 31.10.2005 Fixed 800kBit baudrate for SJA1000. AB 31.10.2005 Minor bugfix. When driver was used in "smart AB disconnect" mode (driver load option), the driver removes a controller from the CAN-bus, if there were no more open handles. Nevertheless canGetBaudrate() delivered the last configured baudrate. This is fixed. 27.10.2005 Linux: AB Added support for NTCAN_IOCTL_GET_SERIAL Added support for NTCAN_IOCTL_SET_RX_TIMEOUT Added support for NTCAN_IOCTL_SET_TX_TIMEOUT 27.10.2005 Fixed bug with CAN-frames with length greater eight AB 82527 boards. 21.10.2005 Some internal changes concerning future extensions MF+MT of the CAN driver (no influence on existing features). 20.10.2005 Linux and pci405 all platforms: Fixed bug in 20B-Filter (introduced with 3.6.0 release) MT 14.09.2005 Fixed bug with CAN-frames with length greater eight MK for SJA1000 boards. Such frames shouldn't be used, but nevertheless the CAN specification allows such frames and thus these are correctly supported. 3.6.1 30.08.2005 Release of version 3.6.1 for pci331 (Linux64) AB 29.08.2005 Fixed small bug in PCI-hotplug layer (introduced AB with release 3.6.0 of PCI360), concerning mapping of unwanted IO-spaces on pci200 and pci331 3.6.0 23.08.2005 Release of version 3.6.0 for pci360 (Linux) AB 22.08.2005 NEW TYPE for CAN handles: NTCAN_HANDLE. AB HANDLE is deprecated from now on! This change got necessary to keep ntcan-library on all systems compatible with ntcan-library for vxWorks. 22.08.2005 Fixed bug in PCI-hotplug layer concerning disabled AB memory spaces (affecting pci360, only) (Linux) 22.08.2005 Small bugfix concerning canIdDelete (Linux) AB 3.6.0 16.08.2005 Release of version 3.6.0 for pci331 (Linux) AB 3.6.0 16.08.2005 Release of version 3.6.0 for pci405 (Linux) AB 3.6.2 10.08.2005 Release of version 3.6.2 for pci405 (Windows) MT 10.08.2005 Deleting id's (canIdDelete) now working again (Windows) MT 3.6.0 26.07.2005 Release of verson 3.6.0 for (c)pci200/266 (Linux) AB 3.6.0 26.07.2005 Release of verson 3.6.0 for isa331 (Linux) AB 26.07.2005 Major changes in system abstraction layer for linux AB - PCI driver is hotplug driver, now (driver didn't receive interrupts at all on certain ACPI systems) - Cleaned the entire layer and made it more modular 26.07.2005 Minor bugfix for Linux/ISA drivers (better validation AB of IO-address) 26.07.2005 Minor bugfix in ISA initialization AB Problem occurred only with severeal address spaces (which we currently don't have on any hardware) 19.07.2005 One driver-binary can serve different hardware now AB (Used for sja1000 derivates under linux at the moment: PCI200 driver serves for PCI200, PCI266 and CPCI200) 3.6.0 18.07.2005 Release of version 3.6.0 for pci405 (Windows) MF 14.07.2005 New 20B-Filter MT Note: 20B filtering was possible before, this corresponds to a more sophisticated way of filtering with two masks ("as one wants it to have"), see CAN-API manual. 13.07.2005 Internal changes, preparation of new features (3.6.x) MT+MF 3.5.0 04.07.2005 Release of version 3.5.0 for pci405, pci331 and OT pci360 (RTX 5.x) 3.5.0 01.05.2005 Release of version 3.5.0 for (c)pci360 (Linux) AB 3.5.0 30.04.2005 Release of version 3.5.0 for (c)pci331 (Linux) AB 3.5.0 30.04.2005 Release of version 3.5.0 for (c)pci200 (Linux) AB 28.04.2005 Board names changed (match old driver arch.) AB 3.5.0 19.04.2005 Release of version 3.5.0 for pci266 (Linux) AB 19.04.2005 Linux drivers are 64-Bit ready (3.5.x) AB 3.4.1 06.04.2005 Release of version 3.4.1 for isa331 (QNX 6) MT 3.4.0 06.04.2005 Release of version 3.4.0 for pci331 (QNX 6) MT 06.04.2005 Thread pool switched off for i20 cards => MT At the moment no Firmware-Update possible (this comment refers to QNX, only!!!) 3.4.0 05.04.2005 Release of version 3.4.0 for isa331 (QNX 6) MT 3.4.0 22.03.2005 Release of version 3.4.0 for pci405+pci405fw2 (Linux) MF 3.4.0 04.02.2005 Release of version 3.4.0 for cpci200 (Linux) AB 3.4.0 28.02.2005 Release of version 3.4.0 for usb331 (Linux) AB 22.02.2005 Fixed firmware update for i20-cards AB 21.02.2005 Abort mechanism fixed for i20-cards AB 15.02.2005 Internal interface changes (3.4.x) MT+MF 3.3.2 11.02.2005 Release of version 3.3.2 for c405_20m, cpci405 MF 3.3.4 07.12.2004 Release of version 3.3.4 for pci266 (Linux k. 2.6) MT 3.3.2 07.12.2004 Release of version 3.3.2 for pci200 (Linux k. 2.6) MT 3.3.13 02.12.2004 Release of version 3.3.13 for pci405 (IRIX) SR 22.11.2004 Added SMART_DISCONNECT-Mode for passive SJA1000 targets MF 3.3.1 15.11.2004 Release of version 3.3.1 for cpci750 MF 15.11.2004 Added new driver "cpci750" MF 3.3.12 10.11.2004 Release for pci405 MT 3.3.2 10.11.2004 Release for usb331 and isa331 MT 10.11.2004 Compilable with versioned symbols again MT 3.3.11 09.11.2004 Release for pci405 MT 3.3.1 09.11.2004 Release for usb331 and isa331 MT 3.3.1 29.10.2004 Release of version 3.3.1 for cpci405, cpci405ab and c405_20m MF 29.10.2004 canSendT and canWriteT in DEFERRED_TX mode now use real timestamps instead of ticks MF 3.3.0 01.10.2004 Release of version 3.3.0 for usb331 (Linux k. 2.4) AB 01.10.2004 Use timestamp latch when possible else use current free running timestamp MF 3.3.3 17.08.2004 Release of version 3.3.3 for pci266 (Linux k. 2.6) AB 16.08.2004 Fixed termination of dpc thread MT 3.3.1 05.08.2004 BETA-release of version 3.3.1 for pci360 (Linux k. 2.6) AB 3.3.1 20.07.2004 BETA-release of version 3.3.1 for pci200 (Linux k. 2.6) AB 3.3.4 20.07.2004 BETA-release of version 3.3.4 for pci331 (Linux k. 2.6) AB 3.3.3 01.07.2004 Release of version 3.3.3 for isa200 (Linux k. 2.6) MT 01.07.2004 Fixed regparm-bug in SJA1000(Linux) MT 3.3.1 17.06.2004 Release of version 3.3.1 for cpci405, cpci405ab, c405_20m MF 3.3.2 04.06.2004 Release of version 3.3.2 for pci266 (Linux k. 2.6) MT 3.3.1 28.05.2004 3rd Beta-release of ver. 3.3.1 for PCI331 (Linux k. 2.6)MT 3.3.1 27.05.2004 Beta-release of ver. 3.3.1 for PCI266 (Linux k. 2.6) MT 3.3.1 26.05.2004 2nd Beta-release of ver. 3.3.1 for PCI331 (Linux k. 2.6)MT 3.3.1 14.05.2004 Beta-release of ver. 3.3.1 for PCI331 (Linux k. 2.6) AB 3.3.7 13.05.2004 Beta-release of ver. 3.3.7 for PCI405 (Linux k. 2.6) AB 13.05.2004 Fixes in osif-layer for linux for kernel>=2.6.6 AB 3.3.6 11.05.2004 Beta-release of ver. 3.3.6 for pci405 (Linux k. 2.6) AB 3.3.5 11.05.2004 Release of version 3.3.5 for pci405 (IRIX) SR 07.05.2004 Merge with linux kernel 2.6 dev-tree (Linux k. 2.6) AB+MT 07.05.2004 Reworked hwgraph handling (IRIX) SR 03.05.2004 Switched back to busmastering on PCI405 (IRIX) SR 3.3.5 29.04.2004 Release of version 3.3.5 for pci405 (Linux) AB+MF 3.3.1 29.04.2004 Release ov version 3.3.1 for isa200 (Linux) AB 3.3.0 29.04.2004 Release of version 3.3.0 for I20-Linux (except USB331) AB 3.3.0 29.04.2004 Release of version 3.3.0 for pci266+pci200 (Linux) AB 28.04.2004 Fixed bug with deadlock on AutoRTR for all I20-cards AB 28.04.2004 Fixed bug in upstream-buffer-handling (pci405) MF 22.04.2004 Fixed bug in nucleus id filtering, if more than 14 receivers enable the same id. MT 22.04.2004 Fixed bug in ioctl-return values in ntcan-lib (Linux) AB 20.04.2004 Improved memory allocation on pci405 MF 3.3.0 15.04.2004 Release of version 3.3.0 for all cards(QNX 6) MT 3.3.0 13.04.2004 Release of version 3.3.0 for isa200 (Linux) MT 3.3.0 08.04.2004 Release of version 3.3.0 for pci405 (Linux) AB 3.3.0 08.04.2004 Release of version 3.3.0 for pci405fw MF 07.04.2004 Changed major for 82527-cards (Linux) AB 07.04.2004 Fixed bug in nucleus id handling MT 03.04.2004 Minor busmaster-fix for PCI405 (Linux) AB 3.3.0 31.03.2004 Release of version 3.3.0 for PCI405 (IRIX) SR 31.03.2004 Cosmetic changes for clean compile on IRIX (PCI405) SR 31.03.2004 Bring IRIX port up to date (mostly lib changes) SR 31.03.2004 IOCTL's NTCAN_IOCTL_FLUSH_RX_FIFO and NTCAN_IOCTL_GET_RX_MSG_COUNT fully implemented MT+SR 24.03.2004 CPCI405AB only: Add time-server functionalty to lateral can for test purposes SR 3.2.0 19.03.2004 Release of version 3.2.0 for 82527-cards (Linux) AB 3.2.0 19.03.2004 Release of version 3.2.0 for SJA1000 (Linux) AB 3.2.0 19.03.2004 Release of version 3.2.0 for PCI405 (Linux) AB 3.2.0 15.03.2004 Release of version 3.2.0 for Linux/PPC Embedded Boards (cpci405, c405_20m, cpci405ab) MF 15.03.2004 DEFERRED_TX_MODE is now enabled by default. For internal use, only! MF 14.03.2004 Bugfix for bus-error handling of 82527-cards AB 14.03.2004 Bugfix in abortion of tx-jobs for 82527-cards AB 12.03.2004 added DEFERRED_TX_MODE for internal use. This new feature is used by canWriteT/canSendT. MF 3.1.1 05.03.2004 Release of version 3.1.1 for PCI405/Linux AB 05.03.2004 Corrected AutoRTR-handling (all platforms) AB+MT 05.03.2004 ntcan-Library v3 (one library for old and new driver) AB 05.03.2004 read+write changed to ioctls (linux) MF+MT 3.1.1 24.02.2004 Release of version 3.1.1 for QNX 6 MT Sending of rtr frames possible again canTxObj now works, needed for canOpen 3.1.0 04.02.2004 Release of 3.1.0 for I20-Linux (except USB331) AB 04.02.2004 Corrected return-code of blocking calls (read+write) after signal (ERESTARTSYS) (Linux) AB 3.1.0 02.02.2004 Release of version 3.1.0 for QNX 6 MT 1st Release with time-stamped canRead/Take 02.02.2004 Workaround in i20 interrupt-check for QNX MT 29.01.2004 new option "-p prio" for qnx MT 07.01.2004 Changed timestamp code from period to frequency handling MF 06.01.2004 Fixed bug in signal handling (all) MF 06.01.2004 Do not touch frontpanel LEDs on cpci405ab boards during driver load MF 06.01.2004 Added event-msg generation for SJA1000 cards MF (canReadEvent now reports bus status changes) 17.12.2003 "Ghost-msg-losts" fixed for all cards and systems MT 17.12.2003 Added pci266-support AB 3.0.4 02.12.2003 Release of version 3.0.4 for I20-Linux (except USB331) AB 01.12.2003 Fixed OSIF_IRQ_MUTEX_CREATE for SP-systems (Linux) AB+MT 01.12.2003 Prepared i20-cards for new baudrate-definitions (firmware needs to follow) AB 01.12.2003 Fixed canClose for isa331 and usb331 AB 3.0.3 13.11.2003 Release of version 3.0.3 for I20-Linux (except USB331) AB 13.11.2003 OSIF_TIMER as DPC MT 13.11.2003 Reduced board-parts to boardrc for I20-cards AB 13.11.2003 Reduced time on interrupt-level for all I20-cards AB + MT to minimum 13.11.2003 Bugfix (Linux): - Deadlocks on abort and timeout AB + MT - Problems on highspeed (Multi-GHz) and/or "fast-clock-tick"-systems 11.11.2003 Fixed SMP-problems with I20-cards AB + MT 11.11.2003 Added USB331-support (Hotplugging still instable) AB 05.11.2003 Removed upd.c (I20), now using updx.c from candev AB 05.11.2003 Fixed PCI360 (Detection of CPCI360 failed) AB (Added support for four subvendor and subsystem-IDs (Linux)) 27.10.2003 Corrected usage of output macros (All) AB 3.0.2 08.10.2003 Release of version 3.0.2 for CPCI405/AB, C405_20M MF 08.10.2003 Added timestamps for CMSGs received through interaction MF (all boards with direct SJA1000 access) 08.10.2003 Clean up of SJA1000 error handling in ISR MF (all boards with direct SJA1000 access) 3.0.2 06.10.2003 Release of version 3.0.2 for PCI-405 IRIX SR 30.09.2003 Fix memory leak in pci405 irix port (occured upon canClose) SR 29.09.2003 canTake internal return value changed from EIO to OSIF_OK (Linux & IRIX) SR 29.09.2003 esdcan_read/write_common (Linux & IRIX): called with node-mutex already already locked SR 29.09.2003 Corrected canSend return code to NTCAN_CTRL_BUSY when TX-queue is full (instead of NTCAN_INSUFICIENT_RESOURCES). MF 19.09.2003 Single DPC thread for all nodes. MT 3.0.1 10.09.2003 Internal Release SR Code merge of IRIX port with esdcan main source tree 3.0.0 01.08.2003 Initial release AB+MF
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/esd/Makefile
######################################################################### # FILE NAME Makefile # # BRIEF MODULE DESCRIPTION # Makefile for ESDCAN-release-package # # # History: # # 22.01.2016 - some cleanup, 32 & 64 bit builds for cantest mj # 23.07.2002 - initial version (based on MFs-makefiles in esdcan) ab # ######################################################################### # Copyright (c) 1996 - 2016 by electronic system design gmbh # # This software is copyrighted by and is the sole property of # esd gmbh. All rights, title, ownership, or other interests # in the software remain the property of esd gmbh. This # software may only be used in accordance with the corresponding # license agreement. Any unauthorized use, duplication, transmission, # distribution, or disclosure of this software is expressly forbidden. # # This Copyright notice may not be removed or modified without prior # written consent of esd gmbh. # # esd gmbh, reserves the right to modify this software without notice. # # electronic system design gmbh Tel. +49-511-37298-0 # Vahrenwalder Str 207 Fax. +49-511-37298-68 # 30165 Hannover http://www.esd-electronics.com # Germany sales@esd-electronics.com # ######################################################################### include ./config.mk ifeq ($(TARGET_ARCH),ppc) ifdef CROSS_COMPILE CROSS = $(CROSS_COMPILE) else CROSS = ppc_4xx- endif endif CC = $(CROSS)gcc LD = $(CROSS)ld STRIP = $(CROSS)strip BLD_PATH = ./src/ BLDOBJECTS = *.o *.mod.c *.ko.cmd *.ko .tmp_versions .*.cmd *.order *.symvers VPATH = $(BLD_PATH) INCL = -I./include CFLAGS += -Wall -Wstrict-prototypes -fomit-frame-pointer CFLAGS += -O2 ifeq ($(TARGET_ARCH),ppc) CFLAGS += -DOSIF_ARCH_PPC -I$(KERNELPATH)/arch/$(TARGET_ARCH) # kernel 2.6 cross compilation requires ARCH= argument # do not forget to set CROSS_COMPILE correctly! # Note: export ARCH in your shell before building! KERNELARCH = endif ifeq ($(TARGET_ARCH),x86) CFLAGS += -DOSIF_ARCH_X86 endif ifeq ($(TARGET_ARCH),arm) CFLAGS += -DOSIF_ARCH_ARM endif PWD := $(shell pwd) all: $(MAKE) -C $(KERNELPATH) $(KERNELARCH) SUBDIRS=$(PWD)/src ESDCAN_FLAGS=$(ESDCAN_FLAGS) modules @echo "Please do not forget to create nodes for the can-device in /dev/!" BITSLIST:=$(subst lib,,$(wildcard lib*)) NTC_LIB_MAJOR=$(basename $(basename $(NTC_LIB_VERSION))) cantest: $(foreach BITS,$(BITSLIST),bin$(BITS)/cantest) cantest_static: $(foreach BITS,$(BITSLIST),bin$(BITS)/cantest_static) ifneq (,$(findstring 32,$(BITSLIST))) liblinks32: @cd ./lib32; \ test -L libntcan.so.$(NTC_LIB_MAJOR) || ln -s ./libntcan.so.$(NTC_LIB_MAJOR).* ./libntcan.so.$(NTC_LIB_MAJOR); \ test -L libntcan.so || ln -s ./libntcan.so.$(NTC_LIB_MAJOR) ./libntcan.so bin32/cantest: example/cantest.c include/ntcan.h liblinks32 $(CC) $(CFLAGS) -m32 -L./lib32 $(INCL) -o $@ $< -lntcan bin32/cantest_static: example/cantest.c include/ntcan.h lib32/libntcan.a $(CC) $(CFLAGS) -static -m32 -L./lib32/ $(INCL) -o $@ $< -lntcan endif ifneq (,$(findstring 64,$(BITSLIST))) liblinks64: @cd ./lib64; \ test -L libntcan.so.$(NTC_LIB_MAJOR) || ln -s ./libntcan.so.$(NTC_LIB_MAJOR).* ./libntcan.so.$(NTC_LIB_MAJOR); \ test -L libntcan.so || ln -s ./libntcan.so.$(NTC_LIB_MAJOR) ./libntcan.so bin64/cantest: example/cantest.c include/ntcan.h liblinks64 $(CC) $(CFLAGS) -m64 -L./lib64 $(INCL) -o $@ $< -lntcan bin64/cantest_static: example/cantest.c include/ntcan.h lib64/libntcan.a $(CC) $(CFLAGS) -static -m64 -L./lib64/ $(INCL) -o $@ $< -lntcan endif clean: for t in $(BLDOBJECTS); do \ rm -rfv $(BLD_PATH)$${t}; \ done show: @echo "KERNELPATH=$(KERNELPATH)" @echo "NTC_LIB_VERSION=$(NTC_LIB_VERSION)" @echo "NTC_LIB_MAJOR=$(NTC_LIB_MAJOR)" @echo "BITSLIST=$(BITSLIST)" FORCE:
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/esd/README
Driver for esd CAN_CARDS Version > 3.10.0 20.08.2015 ------------------------------------------------------------------------------ Table of Contents ------------------ 0) Introduction 1) File-List 2) Card-ID's and default driver-parameters 3) Installation 3.b) Alternate installation using DKMS 4) Driver parameters 5) Driver's thread priorities 6) CAN-API 7) Sample-Programm "cantest" 8) Binary incompatibilities on libntcan level !!!!!!!!!!!! 9) Known Issues *************** 0) Introduction *************** The files contained in this archive belong to esd's new CAN-driver. It is developed with a wide variety of operating-systems and architectures in mind and is flexible enough to meet the requirements of future CAN-protocols. Attention must be paid if you are upgrading from older drivers with version numbers below 3.0.0 (e.g. 2.5.x). With version 3.0.0 esd now supports an additional dynamic version of the ntcan API library. It is recommended to link applications against the new dynamic library. If you want to use an application that has been linked against the older static library please recompile this application and link against the new library. Please note: ------------ Linux driver is delivered in different versions, please use the correct archive. For kernels 2.4.x there're two versions, depending on the compiler, which was used to compile the kernel: GCC 2.X: esdcan-<card-id>-linux_2_4_x-<arch>-<ver>-gcc2.zip GCC 3.X: esdcan-<card-id>-linux_2_4_x-<arch>-<ver>-gcc3.zip (use this for GCC 4.X, too) For kernels 2.6.x and 3.x: On 32-Bit x86 systems: esdcan-<card-id>-linux_2_6_x-<arch>-<ver>.zip (GCC 2.x is no longer supported for kernels 2.6.x) On 64-Bit x86 systems: esdcan-<card-id>-linux_2_6_x-<arch>-<ver>.zip (GCC 2.x and kernels 2.4.x are no longer supported for 64-Bit systems) Please see section 2) for card-ids and naming scheme of driver archives. ************ 1) File-List ************ Example file tree for a 64-bit release. In a 32-bit only release the bin64 and lib64 directories and their content is not present. release/esdcan-isa331-linux-2.6.x-x86_64-3.10.1 β”œβ”€β”€ bin32 β”‚ β”œβ”€β”€ cantest β”‚ └── updisa331 β”œβ”€β”€ bin64 β”‚ β”œβ”€β”€ cantest β”‚ └── updisa331 β”œβ”€β”€ example β”‚ └── cantest.c β”œβ”€β”€ include β”‚ └── ntcan.h β”œβ”€β”€ lib32 β”‚ β”œβ”€β”€ libntcan.a β”‚ └── libntcan.so.4.0.0 β”œβ”€β”€ lib64 β”‚ β”œβ”€β”€ libntcan.a β”‚ └── libntcan.so.4.0.0 β”œβ”€β”€ src β”‚ β”œβ”€β”€ miscelleaneous sources ... β”‚ β”œβ”€β”€ : β”‚ : β”œβ”€β”€ CHANGELOG β”œβ”€β”€ config.mk β”œβ”€β”€ Makefile └── README File Description ------------------------- CHANGELOG : This file lists all changes and bugfixes sorted by version. config.mk : The configuration-file for the compile-process. You might need to edit this file, in order to suit any peculiarities of your system. (mainly the KERNELPATH, you'll see later) Makefile : Lets you build the driver without any programming-knowledge and without the need to touch any of the source-files. README : This file lib(32|64)/libntcan.a : The ntcan library as static-link-library. DON'T use it unless you know what you're doing! lib(32|64)/libntcan.so.v.mv.r : The ntcan library as dynamic-shared-library (.so). Note on dynamic-shared-library: The .so-suffix is followed by three dot-separated numbers (.v.mv.r). These are version (.v), minor-version (.mv, which has _nothing_ to do with a device's minor-number) and a release-number (.r). Version (.v) changes, if there're incompatible changes in the library's interface. We at esd think this shouldn't change at all, providing you as a user with a consistent interface. Minor-version (.mv) will be changed, if there are major changes in functionality or additional features. Bugfixes will lead to an increasing release-number (.r). WARNING: See section 8) below for a binary incompatibility issue. include/ntcan.h : Header for the ntcan-api/library THIS IS THE ONLY HEADER, YOU SHOULD INCLUDE IN YOUR APPLICATIONS (with the exception of irigb.h, see below). PLEASE DO NOT USE ANY DEFINES LOCATED IN ANY OF THE OTHER HEADERS, IN ORDER TO KEEP YOUR APPLICATIONS WORKING WITH FUTURE VERSIONS OF THE DRIVER. example/cantest.c : Source of example-application bin(32|64)/cantest : The 32-bit and the 64-bit variants of cantest were built from the same source file provided as example/cantest.c. Binary of example-programm, see section 7) for further explanation. (NOTE: cantest needs the libntcan.so, please assure, that it is able to find the correct version by either following the installation-notes below or setting your LD_LIBRARY_PATH-env-variable correctly. In both cases you need to assure, that there's not an older version of the library prior to the latest version in the library-search-path). src/* : Source / object / config files: This driver is released as a combination of binary-objects (*.o) and source-files (*.c and *.h). This way esd can provide a CAN-driver working with many different linux-kernels. The source files are NOT under the GPL!!! You're not allowed to modify, redistribute or sell the files. They are intellectual property of esd-electronics GmbH. BEWARE: Don't try to use any defines or data-structures located in these files in your own sources. This will lead to non-working applications in the future. bin(32|64)/upd<card-id> : The optional firmware update tool. With some boards this tool can be used to switch between CAN-2.0-A / CAN-2.0-B firmware mode. This tool is only delivered with boards that have an updateable firmware. Such boards are for example CAN-PCIe/402, CAN-(C)PCI/331, CAN-(C)PCI/360 and CAN-ISA/331. Replace <card-id> with the appropriate card-id from the table in section 2) to derive the program's name (e.g. it's called updpci331 for a CAN-PCI/331). NOTE: Use this tool in combination with the delivered driver, only! This tool can also be used to switch the firmware mode of cards (only (c)pci331, (c)pci360 and isa331 need such switching) between CAN-2.0-A-firmware (processes CAN-messages with 11-bit-identifiers, only) and CAN-2.0-B-firmware (processes both CAN-messages with 11-bit- and 29-bit-identifiers) mode. USAGE examples: Switch a CAN-PCI/331 between 2.0a and 2.0b mode: "updpci331 -t<x> <net>" Replace <x> with "a" or "b" depending on the firmware, you want to use Replace <net> with a net-number assigned to your CAN-PCI/331 NOTE: This mode switching is needed only on CAN-(C)PCI/331, CAN-(C)PCI/360 and CAN-ISA/331. It is not possible nor needed on CAN-PCIe/402. Firmware update of a CAN-PCI/331: "updpci331 net" replace net with a net-number assigned to your CAN-PCI/331 NOTE for users of CAN-PCI/360: Normally you'll use the tool as described above. There's one exception: With certain old CAN-CPCI/360 boards the update might fail and you end up with a CAN board with only one CAN-net. For this case there's a second version of the update tool with the suffix "rt". The update will take significantly longer, but this will fix the problem. Only old driver releases for CAN-PCI/400 (especially PMC-CAN/400-4I) contained the IRIG-B library. But current driver archives don't contain the IRIG-B libary any more. It's provided as an extra download or on the CAN CD. You'll only need the IRIG-B library, if you have a IRIG-B capable CAN-board, like PMC-CAN/400-4I. For reference only the provided files are listed below. include/irigb.h Header for the IRIG-B-API library lib(32|64)/libirigb.so.v.mv.r IRIG-B-Library as dynamic-shared-library (.so)) See "Note on dynamic-shared-library" on libntcan.so above. doc/irigb_esd.html API manual for IRIG-B library. ****************************************** 2) Card-ID's and default driver-parameters ****************************************** Card-IDs are used in the naming scheme of driver archives. esd-can-Card(s) card-id major io irq ----------------------------------------------------------------- AMC-CAN4 amc4 54 - - CAN-CPCI/331 pci331 50 - - CAN-PCI/331 pci331 50 - - CAN-PMC/331 pci331 50 - - CAN-ISA/331 isa331 52 0x1e0 5 * CAN-USB-Mini usb331 50 - - Support dropped CAN-PCI/360 pci360 51 - - CAN-CPCI/360 pci360 51 - - CAN-ISA/200 isa200 53 0x1e8 5 CAN-CPCI/200 pci200 54 - - CAN-PCI/200 pci200 54 - - CAN-PCI/266 pci200 54 - - CAN-CPCI/405 pci405 53 - - CAN-PCI/405 pci405 53 - - CAN-PC104/200-I pc104_200i 54 0x1e8 5 CAN-PC104/331 isa331 52 0x1e0 5 CAN-PCI/400 esdaccbm 55 - - CAN-PCIe/400 esdaccbm 55 - - CPCI-CAN/400 esdaccbm 55 - - PMC-CAN/400 esdaccbm 55 - - CAN-PCIe/402 pcie402 52 - - You can overwrite the defaults with the insmod-command.(See next chapter) *************** 3) Installation *************** - Extract the driver from the archive: All drivers released after July 2012 are delivered in a TGZ archive instead of a password protected ZIP file. TGZ archive Untar the driver directory: "tar -xzf esdcan-crd-os-arch-ver-ext.tgz" with crd = card-id (e.g.: crd=pci200 or crd=cpci405 ...) os = host-operation-system (e.g.: os=linux-2.4.x) arch = host-architecture (e.g.: arch=x86 or arch=x86_64) ver = driver version (e.g.: ver=3.7.2) ext = extension (applicable to certain cards only, e.g.: ext=gcc2) You'll end up with a directory named as the archive. ZIP archive A1) Unzip the archive: "unzip esdcan-crd-os-arch-ver-ext.zip" with crd = card-id (e.g.: crd=pci200 or crd=cpci405 ...) os = host-operation-system (e.g.: os=linux-2.4.x) arch = host-architecture (e.g.: arch=x86 or arch=x86_64) ver = driver version (e.g.: ver=3.7.2) ext = extension (applicable to certain cards only, e.g.: ext=gcc2) You'll be prompted for a password. Password: esdCAN2007 Resulting file: "esdcan-crd-os-arch-ver-ext.tar" A2) Untar the driver directory: "tar -xvf esdcan-crd-os-arch-ver-ext.tar" with crd = card-id (e.g.: crd=pci200 or crd=cpci405 ...) os = host-operation-system (e.g.: os=linux-2.4.x) arch = host-architecture (e.g.: arch=x86 or arch=x86_64) ver = driver version (e.g.: ver=3.7.2) ext = extension (applicable to certain cards only, e.g.: ext=gcc2) You'll end up with a directory named as the archive. Alternatively the above can be accomplished in a single step: B) Unzip and untar in a single step: "unzip -p esdcan-crd-os-arch-ver-ext.zip | tar -xv" You'll be prompted for a password. Password: esdCAN2007 - Compile the driver: "cd ./esdcan-<crd>-<os>-<arch>-<ver>-<ext>" In some cases you need to edit a configuration-file for the compilation: In config.mk you need to set the variable KERNELPATH correctly. Normally the default-path /usr/src/linux should be correct. If your linux configration differs from the standard, correct the line accordingly: KERNELPATH = /your-path-to-the-kernel-source !!! NOTE FOR LINUX KERNEL > 2.6.0: You might need to be "root" to compile the driver. Compiling the driver is simple by typing: "make" For some card's there're warnings like "COMPILING FOR xxx". These can be ignored and will be removed in future versions. Now, you've a file called as described below, which is the actual driver-module in the same directory: esdcan-<crd>-<os>-<arch>-<kver> : Dynamic loadable driver-file crd = card-id. (e.g.: crd=pci200 or crd=cpci405) os = host-operation-system. (e.g.: os=linux) arch = host-architecture. (e.g.: arch=x86) kver = target-version-information. (e.g.: kver=2.4.18 (for linux the kernel-version is coded here, because the compiled version is kernel-specific!!!)) Example: For a CAN-PCI/331 for 32-Bit-x86-Linux with 2.4.21-99-smp kernel the driver file (driver version 3.6.1) is called: "esdcan-pci331-linux-x86-3.6.1-2.4.21-99-smp" !!! NOTE FOR LINUX KERNEL > 2.6.0: The driver file is called "esdcan-<crd>.ko" and is generated inside of the "src"- subdirectory. Example: For the above mentioned CAN-PCI/331 the driver file is called: "esdcan-pci331.ko" (and is located in ./src subdirectory) - File locations: The driver-module should be placed somewhere in /lib/modules/kernel-version/ . kernel-version has to be replaced by the according string of your system, which you can get by (it should be equivalent to the os-string in the driver's name (see above)): "uname -a" The dynamic-shared-library "libntcan.so" should be placed in /usr/local/lib/ or an equivalent path, which is contained in your LD_LIBRARY_PATH env-variable. NOTE: On 64-Bit systems, there're two versions of "libntcan.so". One in ./lib32 and one in ./lib64. The first belongs into /usr/local/lib on most Linux distributions. The later should be kept together with other 64-Bit libraries, e.g. in /usr/local/lib64. The static version of the library "libntcan.a" can be kept wherever you want. Here at esd we prefer to keep it with the sources of a project, on the other hand, one might like to install it with the shared-lib at /usr/local/lib/ . Installation-note: The shared library should belong to user and group root with the following file access permissions: u=rwx, g=rx, o=rx After installation of the library, the root-user should call: "ldconfig -n /usr/local/lib" (if installed to this directory) Afterwards there's a link libntcan.so.v --> libntcan.so.v.mv.r . For your own convenience it is advised to generate another link in your library-directory: libntcan.so --> libntcan.so.v The static-library, when installed in /usr/local/lib/, should also belong to user/group root, but it doesn't need (and shouldn't have) the executable-flag. Leading to the following fileaccess permissions: u=rw, g=r, o=r - Make the inodes(as superuser): "cd /dev" "mknod --mode=a+rw can0 c x 0" "mknod --mode=a+rw can1 c x 1" with x=major of driver.(See previous chapter) NOTE: On modern systems inodes in "/dev" vanish after reboot. You can work around by creating the inodes in "/lib/udev/devices". So, instead of "cd /dev" go "cd /lib/udev/devices" before calling mknod. - Load the Driverfile (as superuser): Syntax: "insmod ./esdcan-crd-os-arch-ver [major=MA] [verbose=V] [mode=MO]" with: MA = major number (e.g. major=77, default see table above) V = verbose mask (e.g. verbose=0x00000003, default 0x00000000) MO = mode flags (e.g. mode=0x20000000, default 0x00000000) Have a look at "Compile the driver" for the filename-description. - Look in /var/log/messages for any messages of the driver! ************************************** 3.b) Alternate installation using DKMS ************************************** With some Linux distributions (tested with Debian/Ubuntu) you may be able to build and install the driver using the DKMS framework. This will have the benefit that on a kernel update the driver will automatically compiled and installed for the new kernel. Start with unpacking the driver release archive as described in the "3) Installation" section. Then change into the directory that was created by the unpacking action: "cd ./esdcan-<crd>-<os>-<arch>-<ver>-<ext>" For the next steps you need to be *root*. In the mentioned directory enter the command "dkms add ./src" which utilizes the "./src/dkms.conf" file to add a new package to the DKMS framework. The next step should build the driver which uses from "dkms.conf" the "PACKAGE_NAME" as <pkg-name> parameter and "PACKAGE_VERSION" as <pkg-ver> parameter. "dkms build <pkg-name>/<pkg-ver>" # example: dkms build esdcan-pcie402-linux-2.6.x-x86_64/3.9.6 The next step is to install the driver in the "/lib/modules" tree by issuing this command: "dkms install <pkg-name>/<pkg-ver> # example: dkms install esdcan-pcie402-linux-2.6.x-x86_64/3.9.6 This should also do any further installation work as "depmod". The installation directory for the kernel module depends on the configuration of the DKMS framework. The installation of the user space programs and libraries has still to be done as mentioned before. If you want to get rid of the installed driver for all kernel versions then issue the following command: "dkms remove <pkg-name>/<pkg-ver> --all" # example: dkms remove esdcan-pcie402-linux-2.6.x-x86_64/3.9.5 --all ******************** 4) Driver parameters ******************** major ----- May be used to set a non-default major number for the driver. If you don't know, what major numbers are or have no problems loading the driver and/or using the driver, then leave this parameter alone. Normally the default value should be ok. verbose ------- By setting the verbose mask (value range 0x00000000 to 0x000000FF) you can influence the amount of messages the driver writes to your message log on startup. The value is interpreted bitwise, every additional bit may add more output. mode ---- This parameter is hardware dependent. Do not set any bits, not valid for your hardware, as this might lead to unexpected result. On most CAN boards there should be no need to set any bit at all. 0x00000040 - Force LOM (off by default) 0x00000080 - Smart disconnect (off by default) All boards with esdACC controller: 0x20000000 - Select RX Timestamping mode (firmware version > 0.34) (0: EOF (default), 1: SOF) 0x02000000 - Select autobaud mode (firmware version > 0.47) (0: Rounded bitlength (default), 1: Table based) CPCI-CAN/400-4I-PXI: 0x10000000 - May be used to choose the timestamp source on driver startup (0: IRIG-B (default), 1: PXI) 0x08000000 - May be used to invert the Star-Trigger-Input *********************************** 5) Driver's thread priorities *********************************** Basic information on the driver's kernel thread ----------------------------------------------- The driver starts a kernel thread (dpc-thread) that distributes the received CAN frames to the user handles. If a process is waiting (in a canRead() for example) it is also released from its wait state. The driver's kernel thread gets its name derived from the name of the kernel module that contains the driver for your board. Examples: esdcan-amc4.ko kesdcan_amc4 esdcan-esdaccbm.ko kesdcan_esdaccbm esdcan-pci405.ko kesdcan_pci405 esdcan-<card-id> kesdcan_<card-id> If you install three cards of the same type you will still have a single kernel thread. But if you install different types of boards you will get a different named kernel thread for each type of board. The different names make it easier to distinguish which thread is responsible for which group of cards (of the same type). Old drivers used always the name "dpc thread" for their kernel threads (with a literal blank in the name). Advice for priority selection for the driver's kernel thread ------------------------------------------------------------ The default configuration of our CAN driver's kernel thread (dpc-thread) is to give it no special priority. So it runs with the default priority as all other user processes in the time shared class (nice NI=0, priority PRI=19 under x86 Linux). This is suitable for a desktop system that only monitors some CAN buses. If you want to do some control business you may need better priorities. As a rule of thumb the dpc-thread should have a better priority than any of the user processes that do CAN I/O. Especially this is true if your user processes run in the FIFO scheduler class. Every control application is different. Therefore you have to fine tune the priority of the "dpc thread" so that it fits to your needs. You can do that with the Linux command line tools "ps", "renice" and "chrt". To get a sorted by priority list of threads you can enter the following command at the root prompt: # ps -eo pid,tid,class,rtprio,ni,pri,psr,pcpu,stat,wchan:24,comm Oy Identify the dpc-thread and your user program in the list. To only increase the priority in the TimeSharing class you may use commands like these: # ps -e | grep "kesdcan_pci405" 897 ? 00:00:00 kesdcan_pci405 # renice -n -15 -p 897 897 (process ID) old priority 0, new priority -15 If you need to reach the FIFO scheduling class you can use the chrt tool. An example to change the thread's priority to FIFO priority 12 see below: # chrt -v -p -f 12 897 pid 897's current scheduling policy: SCHED_OTHER pid 897's current scheduling priority: 0 pid 897's new scheduling policy: SCHED_FIFO pid 897's new scheduling priority: 12 Be aware of the fact that the given priorities are valid only in the selected "scheduler class" and the kernel's priority is also dependend from the "base priority" for a scheduler class. The "ps" command cited before gives you a by priority sorted list of threads and a good overview of the priority layout currently in use. This should enable you to adjust the priorities as needed. The necessary priority adjustment command can be embedded in one of the system's start scripts. ********** 6) CAN-API ********** - After successful installation you can access the CAN-Bus with the ntcan-API (link "libntcan.so" with your application). ***************************************** 7) Sample-Programm "cantest" ***************************************** Pay attention: The enclosed binary version of cantest needs to be able to find the dynamic-shared-library libntcan.so. Please, assure, that your LD_LIBRARY_PATH is set correctly. Syntax: "cantest test-number [net id-first id-last count txbuf rxbuf txtout rxtout baud testcount data0 data1 ... data8]" If called without parameters all available can-devices and version-numbers will be shown and a short help-screen is printed! parameter description default --------------------------------------------------------------- net logical net-number(canOpen()) 0 id-first enabled can-id's start-id 0 id-last enabled can-id's stop-id 0 count count of CMSG-packets 1 txbuf tx-queue-size of handle(canOpen) 10 rxbuf rx-queue-size of handle(canOpen) 100 txtout tx-timeout of handle 1000 rxtout rx-timeout of handle 5000 baud baudrate-index 2 (500 kbit/s) testcount count of ntcan-API-Calls 10 (-1 => forever) databyte0 Up to 8 databytes for Test 0 or 1 8-Byte-Frames with . 32-Bit Counters . . databyte7 test description --------------------------------------------------------------- 0 sending can-frames without wait (canSend) 1 sending can-frames with wait (canWrite) 2 reading can-frames without wait (canTake) 3 reading can-frames with wait (canRead) 4 reading events (canReadEvent) 5 sending events (canSendEvent) ************************************************************* 8) Binary incompatiblities on libntcan level !!!!!!!!!! ************************************************************* Starting with this release we deliver the libntcan.so.4, i. e. a NTCAN library with a version of 4. This change was enforced because we had to change some NTCAN_IOCTL_* values which make the versions before and after that change binary incompatible! Find the details in the last paragraph of this section ("Incompatibility details"). The change had to be done in preparation of the upcoming CAN-FD support. Because the binary incompatiblity can not be detected at runtime we were forced to change the library version of libntcan. From this release on the shared library will also use symbol versioning! To assist you with the administration of the <ntcan.h> headers new headers will contain a comment line like below to show that they belong to a libntcan.so.4 release. /* Released with libntcan.so.4.0.0 */ What does that mean for you on your host (development) system and on your target system? ----- In the easy and recommended case, you migrate completely to the new driver and libntcan.so.4. Then do the following: - On your host system remove all instances of the old <ntcan.h> file. - On your host system remove all instances of the libntcan.so.3* files. - On your host system install the new <ntcan.h> and the libntcan.so.4* files at the appropriate places. - If needed install the current releases of esd libraries that depend on libntcan.so and are also needed by your application (see "Optional Libaries" below). - Rebuild your application. - Install the new driver kernel module on the target system (and optionally on the development system). - Install libntcan.so.4* (+optional libaries) and your rebuilt application on the target system. - You're done. ----- You need the new driver but don't need any extensions of later libntcan versions and you're not willing or capable to rebuild your application. - On your host system keep the old <ntcan.h> and the old libntcan.so.3* files. - Do NOT install any of the new <ntcan.h> and libntcan.so.4* files! - Install the new driver kernel module on the target system (and optionally on the development system). - You're done. ----- The complicated case. You need to support target systems with old libntcan.so.3 and want to use the current release libntcan.so.4 on new designs. Be warned that this is error prone and can lead to silent failures of your application. Then do the following: - On your host system rename all instances of the old <ntcan.h> file to the new name <ntcan3.h>. - Remove all symbolic links libntcan.so that point to a libntcan.so.3* library. - On your host system install the new <ntcan.h> and the libntcan.so.4* files at the appropriate places. - Run ldconfig. If not already there create a symbolic link libntcan.so that points to the symbolic link libntcan.so.4 to make libntcan.so.4 the library version to be linked with by default. - Install the new driver kernel module and the old libntcan.so.3 or new libntcan.so.4 on the target systems as needed. To use the new version 4 library simply rebuild your application and install it on the target which has the new libntcan.so.4 installed. To use the old version 3 library you have to do some additional tasks. - Add a code snippet like below to your source code to include the old <ntcan3.h> for sure: #include "ntcan3.h" - Link explicitely with the old library version by adding the following link option when linking your application: "-l:libntcan.so.3" This tells the linker to explitely link with version 3 of libntcan. Please observe the colon ":" that marks the beginning of an explicit name. - Then you can install your application on the target system with the libntcan.so.3. NOTE: You MUST NOT build an application with <ntcan3.h> and link with libntcan.so.4 or vice versa. This may lead to silent malfunctions!! ---- Optional Libaries There are some esd libraries that depend directly on the libntcan.so and are linked against either version 3 or 4. Therefore a matching version of the optional libraries needs to be installed on your host (development) system and your target system. The directly depending libraries are: libirigb.so Access IRIG-B time data with CAN boards that support it. libcalcan.so CAN base libarary for the esd CANopen master / slave. If you're using the libntcan.so also directly in your application make sure that you use a library version of the optional libraries that is linked against the same libntcan.so version that you're using for your application! You may diplay the link dependencies of the libary by using "ldd" or "objdump -x". ---- Incompatibility details The following NTCAN_IOCTL_* defines changed their values from libntcan.so.3 to libntcan.so.4: #define NTCAN_IOCTL_SET_TX_TS_WIN 0x001B #define NTCAN_IOCTL_GET_TX_TS_WIN 0x001C #define NTCAN_IOCTL_SET_TX_TS_TIMEOUT 0x001D #define NTCAN_IOCTL_GET_TX_TS_TIMEOUT 0x001E #define NTCAN_IOCTL_SET_HND_FILTER 0x001F If you use these old defines on a new libntcan.so.4 implementation you will get malfunctions because these values mean different things in the libntcan.so.4 implementation. The big deal is that using such a old define could change something completely different on the new implemenation even without provoking the return of an error code. This way the malfunction is SILENTLY triggered and the application has no means to detect it! **************** 9) Known Issues **************** - When loading the module, kernels with version > 2.4.9 generate a warning about a tainted kernel: "Warning: loading ./esdcan-xyz will taint the kernel: no license" This isn't an error message and doesn't concern the functionality of CAN-driver or kernel. - Install-script is still missing
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/esd/config.mk
TARGET_OS=linux TARGET_ARCH=x86_64 BOARD=pcie402 NTC_LIB_VERSION=4.0.1 KERNELPATH=/lib/modules/`uname -r`/build #KERNELPATH=/usr/src/linux
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/esd/readme-Apollo.md
Please refer to Apollo Installation Guide and documentations that come with Apollo kernel on how to use ESD CAN with Apollo software stack.
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/esd/license.txt
/************************************************************************ * * Copyright (c) 1996 - 2014 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd-electronics.com * Germany sales@esd-electronics.com * *************************************************************************/ Distributed with Apollo with permission from ESD. For any copyright & licensing agreement of using ESD contributed code/programs, please contact ESD (electronic system design gmbh) directly.
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/example/cantest.c
/************************************************************************/ /* */ /* Test/Demonstration program for CAN driver with NTCAN-API */ /* */ /* Copyright 1997 - 2016 esd - electronic system design gmbh */ /*----------------------------------------------------------------------*/ /* */ /* Filename: cantest.c */ /* Date: 09.11.99 */ /* Language: ANSI C */ /* Targetsystem: Win NT/2K/XP/Vista/7/8+, Win 9x/ME, WinCE, QNX, */ /* UNIX, VxWorks, Linux (RTAI/RT), NET+OS, RTOS-UH, */ /* RTX/RTX64, OnTime RTOS-32 */ /* */ /* Purpose: Test and demonstration for drivers which support */ /* NTCAN-API */ /*----------------------------------------------------------------------*/ /* Revision history: */ /*----------------------------------------------------------------------*/ /* 2C6,16feb16,ot * Fixed MinGW (GCC) warnings */ /* 2C5,20apr15,mk * Fixed transceiver constants */ /* 2C4,08feb15,ot * Decode CAN transceiver type returned in NTCAN_INFO */ /* * and indicate required FW update in help() */ /* 2C3,26jan15,mk * Retry canOpen without NTCAN_MODE_FD */ /* 2C2,25aug14,ot * Added support for evaluation of NTCAN_INFO and */ /* * extended features. */ /* 2C1,21aug14,mk * Adapted to new NTCAN macro names */ /* 2C0,19jun14,mt * New tests 60-63, 66, 72, 73, 82, 100, 110 */ /* * to support the NTCAN API functions based on */ /* * CMSG_X (CAN-FD ready) messages. */ /* 2B7,12dec13,mk * Added dummy signal handler for SIGUSR1 (unix only) */ /* 2B6,15jul13,ju * Fix for NTCAN_IOCTL_GET_TX_TS_WIN: TX counter in */ /* * CAN data accidentally was incremented by two */ /* 2B5,17may13,stm * Crude fix for the output of the fraction of the */ /* * TimestampFreq. */ /* 2B4,26apr13,bl * Changed SLEEP macros for Linux and QNX */ /* 2B3,11jan13,ot * Support to dynamically load canSendT()/canWriteT() */ /* 2B2,10jan13,ot * Decode features IRIG-B and TIMESTAMPED_TX */ /* 2B1,16nov12,ot * New test -3 like -2 with decoded feature flags */ /* * Added controller state information in overview */ /* 2B0,14aug12,ot * Allocated test context instead of using of global */ /* * variables to support more than one instance on */ /* * operating systems with common global namespace */ /* * Fixed canOverlappedT() and canFormatError() not */ /* * loaded dynamically which breaks compatibility to */ /* * very old versions of NTCAN library on Windows */ /* 2A5,24may12,fj * Added support for RTOS-32 (#define RTOS32) */ /* 2A4,23mar12,ot * Show timestamp frequency and timestamp in overview */ /* * correctly without 64-Bit support in printf() */ /* 2A3,11aug11,ot * Added test 50 and use Tx timeout in canSend test */ /* * as delay between bursts. */ /* 2A2,22jun11,ot * Tweak some defaults according to test type */ /* 2A1,22mar11,ot * Allow special constants "auto", "disable", "no" */ /* * for parameter baudrate to configure auto baudrate */ /* * disable device or no baudrate change */ /* * Display CAN controller clock in device overview */ /* 2A0,23jul10,mk * Added -1 for baudrate does not set baudrate */ /* * Added negative test numbers lead to help output */ /* * Test -2 leads to shorter output (no cmdline help) */ /* 29F,06jul10,ot * Added plain text for some more controller types */ /* * Support extended EVMSG union in print_event() */ /* 29E,21may10,mk * Added use of canFormatEvent */ /* 29D,15apr10,bl * Changed CAN node information output a bit */ /* * Changed output of CMSGs a bit */ /* 29C,08apr10,ot * Different output format in print_cmsg() for */ /* * object mode results and support for interaction */ /* * marking in FIFO mode */ /* * A negative value for 'count' will open the handle */ /* * in 'mark interaction' mode for blocking Rx tests */ /* * A value of 0 for 'count' will open the handle */ /* * in 'no interaction' mode for blocking Rx tests */ /* * A negative value for 'count' will send RTR instead */ /* * of data frames for blocking/non-blocking Tx tests */ /* * Decode CAN controller type in 'boardstatus' */ /* * Textual description of extended error events */ /* 29B,13jan10,ot * Fixed canTest() called without args with VxWorks */ /* * does not always shows the expected behaviour. */ /* 29A,26aug09,mk * Removed tests from d3xtest */ /* 299,25aug09,mk * Prevent deprecated warning for d3xtest (for DDK) */ /* 298,10jun09,stm * Made compilable again under RTOS-UH for driver */ /* * release 2.2.4. */ /* 297,05feb09,ot * Support to configure bus load event period */ /* 296,12sep08,mk * Repaired busload event decoding to work again */ /* 295,21aug08,ot * New entry print_event() as common code to decode */ /* * events */ /* 294,03jan08,ot * Test 4 and test 5 are changed to avoid using the */ /* * obsolete API calls canReadEvent()/canSendEvent() */ /* * New test 16 to check Win32 overlapped canReadT() */ /* * Moved code to create event for overlapped I/O to */ /* * the initialization part of the test. */ /* * Added missing cleanup code for overlapped tests. */ /* * Moved boilerplate code to get timestamp frequency */ /* * into get_timestamp_freq() */ /* * Moved boilerplate code to enable a CAN identifier */ /* * into common set_can_id() */ /* 293,21jan08,mt * New test 43 for timestamp sanity check. */ /* * Test 100 changed to test sched disable/enable */ /* * feature and sched counters */ /* 292,09nov07,mk * Added nice busload output for test 23 */ /* * Baudrate is now set after adding event ids */ /* 291,15aug07,ot * Check if hardware/driver supports timestamps */ /* * before performing related tests. */ /* * Adapted to changes in Windows CE 6.x environment */ /* 290,19jul07,ot * Try loading ntcan64.dll dynamically in addition to */ /* * ntcan.dll if running on Windows 64-Bit */ /* 25may07,mt * Sending 0 byte-frames if 1st data arg is -1 */ /* 289,22feb07,fj * Fixed some compiler warnings (linux, gcc-4.1) */ /* 288,31jan07,ot * Support for canFormatError() */ /* * Changed duration time unit for Win32 from ms to us */ /* 287,13oct06,ot * Changed preprocessor check if scheduling is */ /* * supported. */ /* 286,17feb06,mk * Added test 54 to check closing of duped handles */ /* 285,11oct06,bl * Added detailed output of baudrate change event */ /* * to event read test (4) */ /* 284,31jul06,stm * To be compiled successfully under VW54 (rel 2.4.1) */ /* * the variable <udtTimestampFreq> also needs to be */ /* * excluded using the define NTCAN_IOCTL_GET_TIMESTAMP*/ /* 283,05jul06,ot * Wait configured tx timeout after test 0 before */ /* * closing the handle, to prevent driver discarding */ /* * pending messages if delayed close is unsupported. */ /* 282,12jun06,ot * Force thread affinity to one processor or core for */ /* * Win32 kernel with SMP support to prevent wrong */ /* * time differences caused by CPU TSCs out of sync. */ /* 281,14mar06,ot * Support for dynamically loaded entries for Win32 */ /* * to make current version run with old NTCAN lib */ /* 280,03feb06,ot * Changed test 22 to 32 to be orthogonal with read */ /* * Added test 22 canTakeT() and 42 canTakeT() in */ /* * object mode */ /* * Different output format in print_cmsg_t() for */ /* * object mode results. */ /* 275,23nov05,ot * Time difference in print_cmsg_t() calculated and */ /* * displayed for each frame type. */ /* 274,23nov05,mk * Added test 53 to check NTCAN_IOCTL_GET_TIMESTAMP */ /* 273,21nov05,mf * Mask idstart for 20B filter */ /* 272,12sep05,ot * New entries print_cmsg() and print_cmsg_t() to */ /* * remove redundant code */ /* 271,08sep05,ot * Added auto RTR test (8) */ /* 270,04aug05,ot * Support for serial number and 20B filter mask if */ /* * supported by driver */ /* * Using strtoul() instead of atoi() for converting */ /* * data part of command line */ /* * Fixed last net is 255 instead 254 in help() */ /* * Use namespace clean NTCAN_HANDLE instead of HANDLE */ /* 2615,12jul05,mt * Support for MAIN_CALLTYPE */ /* 2614,07may05,ot * Missing defines for 64 bit support in Windows */ /* * NET+OS 6.x support */ /* * Additional error codes in get_error_str() */ /* 2613,19apr05,bl * Removed warnings after 64-Bit port of driver */ /* 2612,14apr05,mf * Removed timestamp union - use unsigned long long */ /* 2611,03may04,bl * Limiting count to size of rxmsg or txmsg */ /* 2610,15mar04,fj * Added NTCAN_SOCK_xxx return-codes */ /* 269,07jan04,mf * changed timestamping ioctl from period to freq */ /* 268,05jan04,stm * Fixed compiler warnings. */ /* 267,07oct03,mf * added timestamping test (23) */ /* * (timestamping code must be enabled by defining */ /* * NTCAN_HAVE_TIMESTAMPS */ /* * removed C++ style comments */ /* * added test 51 (written by mt) */ /* * merged with new esdcan tree's cantest.c */ /* * minor changes in RTAI code */ /* 265,23apr03,ot * Error message if opening handle failed with other */ /* * reason than 'no device' if called w/o parameter. */ /* * Error codes listed in err2str[] now depend on */ /* * NTCAN library and not on operating system. */ /* 264,22oct02,stm * Fixed compiler warnings. */ /* 263b,10oct02 * See CVS log */ /* 263a,09sep02 * See CVS log */ /* 263,13aug02,stm * Use compiler defines __RTOSUH__ + __RTOSUHPPC__ */ /* 262,08jul02,ot * Added support for NET+OS (define NET_OS) */ /* 261,16mar02,ot * Added support for RTX (define UNDER_RTSS) */ /* * Added support for time unit in duration output */ /* 260,05Nov01,mt * Added test 22 Object mode */ /* 257,10may01,ot * If possible use performance counter for Win32 */ /* * instead of GetTickCount() to have a more accurate */ /* * timing */ /* 256,27feb01,fj * Added start_rt_timer() and stop_rt_timer() for */ /* rtai-version */ /* 255,05feb01,fj * Added support for rtlinux-3.0 */ /* 254,06jul00,ot * Display feature flags of each interface */ /* * Added new error codes from NTCAN for Win32 */ /* 253,06jul00,ot * Caller priority check for Vxworks (not used yet) */ /* 252,05jul00,fj * rtai: added kernel module parameter infifo and */ /* * outfifo. printf() now via /dev/rtfx, with */ /* * x=outfifo (printf() no longer via printk() */ /* * to syslog). If not specified, infifo defaults*/ /* * to 0 and outfifo defaults to 1. */ /* 251,27jun00,sr * some // comments removed for vxworks */ /* 250,09jun00,fj * support for linux-rtai */ /* 249,17apr00,sr * rtos-uh-support included */ /* 248,13jan00,mt * rmos-support included */ /* 247,05jan00,ot * Fixed bug in previous version that idend is set to */ /* * idstart */ /* 246,16dec99,ot * Using strtol() instead of atoi() to parse baudrate */ /* * and CAN-IDs to support hex and oct values */ /* * Changes in value display for baudrate and idf */ /* 245,01dec99,mt * Test 19 */ /* 244,09nov99,mt * canGetBaudrate */ /* 243,20may99,ot * Removed test 13 from D3X version */ /* * Return immediately if test is undefined */ /* * Special test 6 for async I/O using signal handler */ /* * and poll for Solaris (D3X) version */ /* 242,17may99,mt * decimal net numbers in help() */ /* 241,03may99,ot * Windows CE support included (no test 6 and 7) */ /* * Changed GET_CURRENT_TIME macro from WIN32 API call */ /* * GetCurrentTime() to GetTickCount() as only the */ /* * latter is present in Windows CE */ /* 240,19mar99,mt * Test 7 added */ /* 230,19mar99,ot * Support for VxWorks included */ /* * Minor changes to prevent GCC compiler warnings */ /* * Replaced GetCurrentTime() call in Rev 2.2.1 with */ /* * macro */ /* * Display code revision in help() */ /* 221,09mar99,mt * NO_ASCII_OUTPUT => canRead/Take measures */ /* * Frames per second */ /* 220,01mar99,ot * New macros GET_CURRENT_TIME and SLEEP for multi */ /* * OS support */ /* * Replace DWORD with long */ /* * Replace ERROR_SUCCESS with NTCAN_SUCCESS */ /* * Fixed bug with non initialized board status */ /* * Minor changes to remove some BC and GCC compiler */ /* * warnings */ /* * Support for UNIX (Solaris) based on macro unix */ /* * Replaced macro SIEMENS with D3X */ /* * Description of test 9 in help() */ /* * Included ASCII output support for test 3 and 9 */ /* * Removed some junk code */ /* * Added RCS/CVS id */ /* * Made help() and get_error_str() static */ /* * Check for new NTCAN_INSUFICIENT_RESOURCES after */ /* * canIdAdd() and solve situation with sleep */ /* * Rename module from nttest.c to cantest.c */ /* 210,09dec98,mt * New Parameter for nttest */ /* 202,18dec97,mt * New Error-Code "NTCAN_INVALID_HARDWARE" */ /* 201,06nov97,mt * Bug-Fixes & different Default-values for testcount */ /* 200,28oct97,mt * D3x-Version */ /* 010,19jun97,mt * Birth of module */ /*----------------------------------------------------------------------*/ #define LEVEL 2 #define REVISION 12 #define CHANGE 6 /************************************************************************/ /************************************************************************/ /* Special includes, defines and functions for all Windows-platforms */ /* RTX and OnTime RTOS32 */ /************************************************************************/ /************************************************************************/ #ifdef _WIN32 /* Prevent warnings about deprecated ANSI C library functions in VC8 :-( */ #if defined (_MSC_VER) && (_MSC_VER >= 1400) # ifndef _CRT_SECURE_NO_DEPRECATE # define _CRT_SECURE_NO_DEPRECATE # endif # ifndef _CRT_NONSTDC_NO_DEPRECATE # define _CRT_NONSTDC_NO_DEPRECATE # endif #endif #if defined(__MINGW32__) || defined (__MINGW64__) # if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__ # pragma GCC diagnostic ignored "-Wstrict-aliasing" # endif # include <stdint.h> /* Include stdint.h if available */ #endif # include "windows.h" #define MAIN_CALLTYPE __cdecl # ifndef INT64_C # define INT64_C(c) (c ## I64) /* INT64 constant according to ISO C99 */ # define UINT64_C(c) (c ## UI64) /* UINT64 constant according to ISO C99 */ # endif /* * Macros for printing 64 bit format specifiers according to ISO C99 * missing in Windows */ #ifndef __PRI64_PREFIX # define __PRI64_PREFIX "I64" # define PRId64 __PRI64_PREFIX "d" # define PRIi64 __PRI64_PREFIX "i" # define PRIu64 __PRI64_PREFIX "u" # define PRIx64 __PRI64_PREFIX "x" # define PRIX64 __PRI64_PREFIX "X" #endif #ifndef RTOS32 # define CANTEST_MULTIPROCESSOR # define GET_CURRENT_TIME mtime() # define TIME_UNITS "us" static unsigned long mtime(void); static int ForceThreadAffinity(void); # define SLEEP(arg) Sleep(arg) #else # include <Rttarget.h> # include <Rtk32.h> # include <Finetime.h> # include <Clock.h> # define GET_CURRENT_TIME (CLKTicksToMilliSecs(RTKGetTime())) # define SLEEP(arg) { register RTKDuration ticks = CLKMilliSecsToTicks(arg); \ (ticks == 0 ? RTKDelay(1) : RTKDelay(ticks)); } # define main _canTest /* Redefine main for to be called from helper */ #endif /* !RTOS32 */ /* BL: not quite sure, if 400 is the version this behaviour was changed. Might have been earlier.*/ # ifdef _WIN32_WCE # if _WIN32_WCE < 400 # define atoi _wtoi /* As we work with unicode redefine this */ int CreateArgvArgc(TCHAR *pProgName, TCHAR *argv[30], TCHAR *pCmdLine); # endif /* of _WIN32_WCE < 400 */ # undef CANTEST_MULTIPROCESSOR # endif # ifdef UNDER_RTSS # include "rtapi.h" /* # define TIME_UNITS "us" */ # undef CANTEST_MULTIPROCESSOR # endif /* of UNDER_RTSS */ # if defined (_MSC_VER) && defined(D3X) __pragma(warning(disable:4996)) /* disable deprecated warning for canSendEvent and canReadEvent */ # endif #endif /* _WIN32 */ /************************************************************************/ /************************************************************************/ /* Special includes, defines and functions for all unix platforms */ /* except RTAI- and RT-Linux */ /************************************************************************/ /************************************************************************/ #if defined(unix) && !defined(RTAI) && !defined(RTLINUX) # include <errno.h> # include <sys/time.h> # include <unistd.h> # include <inttypes.h> /* Needed since 64-Bit port of driver! */ # include <string.h> # include <signal.h> # ifdef D3X /* Solaris driver only */ void sigio_handler(int arg); # endif /* of D3X */ static unsigned long mtime(void); void sigusr1_handler(int signum); # define CANTEST_USE_SIGUSR1_HANDLER # define SLEEP(arg) \ do { \ if ( (arg) >= 1000 ) { \ sleep((arg)/1000); \ usleep(((arg)%1000) * 1000); \ } else { \ usleep((arg)*1000); \ } \ } while(0) # define GET_CURRENT_TIME mtime() #endif /* unix */ /************************************************************************/ /************************************************************************/ /* Special includes, defines and functions for QNX */ /************************************************************************/ /************************************************************************/ #ifdef qnx # include <sys/time.h> # include <unistd.h> static unsigned long mtime(void); # define GET_CURRENT_TIME mtime() # define SLEEP(arg) delay(arg) #endif /* qnx */ /************************************************************************/ /************************************************************************/ /* Special includes, defines and functions for VxWorks */ /************************************************************************/ /************************************************************************/ #ifdef VXWORKS # include "vxWorks.h" # include "sysLib.h" # include "taskLib.h" # include "semLib.h" # include "tickLib.h" # include "string.h" # include "timers.h" # define GET_CURRENT_TIME ((tickGet() & 0x003fffff) * 1000 / sysClkRateGet()) # define SLEEP(arg) { register long ticks = arg * sysClkRateGet() / 1000; \ (ticks == 0 ? taskDelay(1) : taskDelay(ticks)); } # ifndef INT64_C # define INT64_C(c) (c ## LL) /* INT64 constant according to ISO C99 */ # define UINT64_C(c) (c ## ULL) /* UINT64 constant according to ISO C99 */ # endif /* * Macros for printing 64 bit format specifiers according to ISO C99 * missing in Windows */ #ifndef __PRI64_PREFIX # define __PRI64_PREFIX "ll" # define PRId64 __PRI64_PREFIX "d" # define PRIi64 __PRI64_PREFIX "i" # define PRIu64 __PRI64_PREFIX "u" # define PRIx64 __PRI64_PREFIX "x" # define PRIX64 __PRI64_PREFIX "X" #endif # define main _canTest /* Redefine main for to be called from helper */ # define WANT_PRIO_CHECK 0 /* 1 to enable priority check */ # if WANT_PRIO_CHECK == 1 static STATUS _checkPriority(int net); # endif #endif /* VXWORKS */ /************************************************************************/ /************************************************************************/ /* Special includes, defines and functions for RMOS */ /************************************************************************/ /************************************************************************/ #ifdef RMOS # include <errno.h> # include <rmapi.h> /* RMOS3-Include */ static unsigned long mtime(void); # define GET_CURRENT_TIME mtime() # define SLEEP(arg) RmPauseTask( arg ) # define __PRI64_PREFIX "ll" # define PRId64 __PRI64_PREFIX "d" # define PRIi64 __PRI64_PREFIX "i" # define PRIu64 __PRI64_PREFIX "u" # define PRIx64 __PRI64_PREFIX "x" # define PRIX64 __PRI64_PREFIX "X" # ifndef INT64_C # define INT64_C(c) (c ## LL) # define UINT64_C(c) (c ## ULL) # endif #endif /* RMOS */ /************************************************************************/ /************************************************************************/ /* Special includes, defines and functions for LynxOS */ /************************************************************************/ /************************************************************************/ #ifdef __Lynx__ # define __PRI64_PREFIX "ll" # define PRId64 __PRI64_PREFIX "d" # define PRIi64 __PRI64_PREFIX "i" # define PRIu64 __PRI64_PREFIX "u" # define PRIx64 __PRI64_PREFIX "x" # define PRIX64 __PRI64_PREFIX "X" # ifndef INT64_C # define INT64_C(c) (c ## LL) # define UINT64_C(c) (c ## ULL) # endif #endif /* __Lynx__ */ /************************************************************************/ /************************************************************************/ /* Special includes, defines and functions for RTOS-UH */ /************************************************************************/ /************************************************************************/ #if defined(__RTOSUH__) || defined(__RTOSUHPPC__) typedef unsigned long long uint64_t; typedef long long int64_t; typedef unsigned long uint32_t; typedef long int32_t; typedef unsigned short uint16_t; typedef unsigned char uint8_t; typedef char int8_t; # include <sys/types.h> # include <fcntl.h> # include <unistd.h> # include <ctype.h> # include <errno.h> # define GET_CURRENT_TIME clock_() /*# define SLEEP(arg) ttire(0x80000000 | arg) */ PROGRAM_TYPE(PT_SHM); SHELL_MODULE_SPEC(CANTEST, CANTEST, 30); #endif /* RTOSUH */ /************************************************************************/ /************************************************************************/ /* Special includes, defines and functions for NET-OS */ /************************************************************************/ /************************************************************************/ #ifdef NET_OS # if NET_OS < 6 # include <bspconf.h> #else # include <bsp.h> # endif # include <narmapi.h> # include <tx_api.h> static unsigned long mtime(void); # define GET_CURRENT_TIME mtime() # define SLEEP(msec) tx_thread_sleep((msec * BSP_TICKS_PER_SECOND) / 1000) # define main canTest /* Redefine main for to be called from helper */ #endif /* NET_OS */ /************************************************************************/ /************************************************************************/ /* Special includes, defines and functions for RT-Linux and RTAI-Linux */ /************************************************************************/ /************************************************************************/ #if defined(RTAI) || defined(RTLINUX) # include <linux/module.h> # ifdef RTAI # include <rtai.h> # include <rtai_fifos.h> # include <rtai_sched.h> RT_TASK thread; # define RT_TIMER_TICK_1MS 1000000 /* ns (!!!!! CAREFULL NEVER GREATER THAN 1E7 !!!!!) */ # else # include <rtl.h> # include <rtl_fifo.h> # include <rtl_sched.h> # include <rtl_time.h> # include <rtl_sched.h> # include <pthread.h> # define WPX(x) printk("### %s:%d ###\n", x, __LINE__); pthread_attr_t attr; pthread_t thread; struct sched_param sched_param; # endif /* RTAI */ # define STACK_SIZE 0x2000 # define CANTEST_PRIO RT_HIGHEST_PRIORITY + 100 # define DEFAULT_IN_FIFO 1 # define DEFAULT_OUT_FIFO 2 # define FIFO_BUF_SIZE 256 # define MAX_ARGC 32 static int infifo = DEFAULT_IN_FIFO; static int outfifo = DEFAULT_OUT_FIFO; int printf(const char *fmt, ...) { char sbuf[FIFO_BUF_SIZE]; va_list args; va_start(args, fmt); vsprintf(sbuf, fmt, args); va_end(args); rtf_put(outfifo, sbuf, strlen(sbuf)); return 0; } long strtol(const char *cp,char **endp,unsigned int base) { if (*cp == '-') { return -simple_strtoul(cp+1,endp,base); } return simple_strtoul(cp,endp,base); } # ifdef RTAI # define TIME_TYPE RTIME # define GET_CURRENT_TIME rt_get_time_ns() # define SLEEP(x) rt_sleep(nano2count(((unsigned long long)(x) * 1000LL * 1000LL))) # else # define TIME_TYPE hrtime_t # define GET_CURRENT_TIME gethrtime() # if 0 # define SLEEP(x) do { pthread_make_periodic_np(pthread_self(), gethrtime() + (x) * 1000 * 1000, 0); pthread_wait_np(); } while(0) # else # define SLEEP(x) usleep((x) > 1000 ? 999999 : (x) * 1000) # endif /* if 0 */ # endif /* RTAI */ # define TIME_UNITS "ns" MODULE_PARM(infifo, "1i"); MODULE_PARM(outfifo, "1i"); int atoi(char *str) { char *endp; int ul; ul = strtoul(str, &endp, 10); return ul; } /* ** Build argc and argv[] and call test program */ void fifoHandler(int fifo) { int status, i, argc = 0; char buf[FIFO_BUF_SIZE], *cp; char *argv[MAX_ARGC]; char *argv0 = "cantest"; int main(int argc, char *argv[]); while (1) { buf[0] = '\0'; buf[FIFO_BUF_SIZE - 1] = 0; i = 0; while (!strchr(buf,'\n')) { status = rtf_get(fifo, &buf[i] , FIFO_BUF_SIZE-i); if (status > 0) { i += status; buf[i] = '\0'; } else { SLEEP(500); } } i = 1; argv[0] = argv0; argc = 1; cp = strchr(buf, '\n'); if (cp && (cp != buf)) { *cp = '\0'; cp = strtok(buf, " "); while (cp && i < (MAX_ARGC - 2)) { argv[i] = rt_malloc(strlen(cp) + 1); strcpy(argv[i], cp); i++; cp = strtok(0, " "); } } argc = i; argv[MAX_ARGC - 1] = 0; /* call test program */ i = main(argc, argv); for (i = 1; i < argc; i++) { rt_free(argv[i]); } } /* while(1) */ } int init_module(void) { int status; rtf_destroy(infifo); if ((status = rtf_create(infifo, 256)) < 0) { printk("CANTEST: Can't create infifo [%d=%#x]\n", status, status); return status; } rtf_destroy(outfifo); if ((status = rtf_create(outfifo, 4096)) < 0) { printk("CANTEST: Can't create outfifo [%d=%#x]\n", status, status); return status; } # ifdef RTAI { RTIME __attribute__ ((unused)) ticks; # ifdef OSIF_ARCH_PPC /*#warning "USING ONESHOT MODE for ARCH PPC"*/ rt_set_oneshot_mode(); # endif ticks = start_rt_timer((int)nano2count(RT_TIMER_TICK_1MS)); printk("CANTEST: rtai-timer started with tick time 1ms [%ld]\n", (long)ticks); } /* * rtai offers fifo_handlers, but semaphores doesn't work with fifo-handlers in rtai-1.2 !? * So we spawn a task and poll for fifo-data */ if ((status = rt_task_init(&thread, fifoHandler, infifo, STACK_SIZE, CANTEST_PRIO, 0, 0)) < 0) { printk("CANTEST: rt_task_init() failed [%d=%#x]\n", status, status); return status; } rt_task_resume(&thread); # else pthread_attr_init(&attr); sched_param.sched_priority = 1; pthread_attr_setschedparam(&attr, &sched_param); if ((status = pthread_create(&thread, &attr, (void* (*)(void*))fifoHandler, (void*)infifo))) { printk("CANTEST: pthread_create() failed [%d=%#x]\n", status, status); return status; } # endif /* RTAI */ printk("CANTEST: Initialized using /dev/rtf%d as input and /dev/rtf%d as output-device\n", infifo, outfifo); return 0; } void cleanup_module(void) { rtf_destroy(infifo); rtf_destroy(outfifo); # ifdef RTAI rt_task_delete(&thread); # else pthread_delete_np(thread); # endif /* RTAI */ stop_rt_timer(); printk("CANTEST: cleanup ...\n"); return; } #else # include <stdio.h> # include <stdlib.h> # ifndef TIME_TYPE # define TIME_TYPE unsigned long # endif # ifndef TIME_UNITS # define TIME_UNITS "msec" # endif #endif /* RTAI || RTLINUX */ #include "ntcan.h" /* * RCS/CVS id with support to prevent compiler warnings about unused vars */ #if ((__GNUC__ > 2) || (__GNUC__ == 2 && __GNUC_MINOR__ >=7)) static char* rcsid __attribute__((unused)) = "$Id: cantest.c 15230 2016-02-16 08:58:34Z oliver $"; #else /* No or old GNU compiler */ # define USE(var) static void use_##var(void *x) {if(x) use_##var((void *)var);} static char* rcsid = "$Id: cantest.c 15230 2016-02-16 08:58:34Z oliver $"; USE(rcsid); #endif /* of GNU compiler */ /* * Defines */ #define NO_ASCII_OUTPUT 0x00000001 /* * Macros */ /* Check NTCAN-API used by test number */ #define IS_SEND_TEST(test) (0 == ((test) % 10)) #define IS_WRITE_TEST(test) (1 == ((test) % 10)) #define IS_TAKE_TEST(test) (2 == ((test) % 10)) #define IS_READ_TEST(test) (3 == ((test) % 10)) /* Use C library memory allocator if not defined OS specific */ #ifndef CANTEST_ALLOC # define CANTEST_ALLOC(s) malloc(s) #endif #ifndef CANTEST_FREE # define CANTEST_FREE(s) free(s) #endif /* * Typedefs */ #define MAX_RX_MSG_CNT 8192 #define MAX_TX_MSG_CNT 2048 typedef struct { CMSG rxmsg[MAX_RX_MSG_CNT]; CMSG txmsg[MAX_TX_MSG_CNT]; #ifdef NTCAN_IOCTL_GET_TIMESTAMP CMSG_T rxmsg_t[MAX_RX_MSG_CNT]; /* needs to have same number of messages as rxmsg */ CMSG_T txmsg_t[MAX_TX_MSG_CNT]; /* needs to have same number of messages as txmsg */ uint64_t udtTimestampFreq; uint64_t ullLastTime; #endif #ifdef NTCAN_FD CMSG_X rxmsg_x[MAX_RX_MSG_CNT]; /* needs to have same number of messages as rxmsg */ CMSG_X txmsg_x[MAX_TX_MSG_CNT]; /* needs to have same number of messages as txmsg */ #endif uint32_t mode; uint8_t ctrl_type; #if defined(unix) && defined(D3X) NTCAN_HANDLE h1; /* Handle for async I/O test */ #endif /* of unix && D3X */ } CANTEST_CTX; /* * Forward declarations */ static void help(int testnr); static int8_t *get_error_str(int8_t *str_buf, NTCAN_RESULT ntstatus); static void print_cmsg(CMSG *pCmsg, CANTEST_CTX *pCtx); static NTCAN_RESULT set_can_id(NTCAN_HANDLE handle, int32_t id); #ifdef NTCAN_IOCTL_GET_TIMESTAMP static int get_timestamp_freq(NTCAN_HANDLE handle, uint64_t *pFreq, int verbose); static void print_cmsg_t(CMSG_T *pCmsgT, CANTEST_CTX *pCtx); #endif #ifdef NTCAN_FD static void print_cmsg_x(CMSG_X *pCmsgX, CANTEST_CTX *pCtx); #endif static void print_event(EVMSG *e, uint64_t ts_diff, CANTEST_CTX *pCtx); /* * Dynamically loaded functions, if supported by OS */ #if defined(_WIN32) && defined(FUNCPTR_CAN_READ_T) # define CANTEST_DYNLOAD static int DynLoad(void); PFN_CAN_IOCTL pfnIoctl = NULL; PFN_CAN_TAKE_T pfnTakeT = NULL; PFN_CAN_READ_T pfnReadT = NULL; PFN_CAN_SEND_T pfnSendT = NULL; PFN_CAN_WRITE_T pfnWriteT = NULL; PFN_CAN_GET_OVERLAPPED_RESULT_T pfnGetOverlappedResultT = NULL; PFN_CAN_FORMAT_ERROR pfnFormatError = NULL; PFN_CAN_FORMAT_EVENT pfnFormatEvent = NULL; # if defined (NTCAN_FD) PFN_CAN_TAKE_X pfnTakeX = NULL; PFN_CAN_READ_X pfnReadX = NULL; PFN_CAN_SEND_X pfnSendX = NULL; PFN_CAN_WRITE_X pfnWriteX = NULL; PFN_CAN_GET_OVERLAPPED_RESULT_X pfnGetOverlappedResultX = NULL; # endif /* of NTCAN_FD */ # define canIoctl(hnd, cmd, pArg) \ (NULL == pfnIoctl) ? NTCAN_NOT_IMPLEMENTED : \ pfnIoctl((hnd), (cmd), (pArg)) # define canTakeT(hnd, pCmsg, pLen) \ (NULL == pfnTakeT) ? NTCAN_NOT_IMPLEMENTED : \ pfnTakeT((hnd), (pCmsg), (pLen)) # define canReadT(hnd, pCmsg, pLen, pOvr) \ (NULL == pfnReadT) ? NTCAN_NOT_IMPLEMENTED : \ pfnReadT((hnd), (pCmsg), (pLen), (pOvr)) # define canSendT(hnd, pCmsg, pLen) \ (NULL == pfnSendT) ? NTCAN_NOT_IMPLEMENTED : \ pfnSendT((hnd), (pCmsg), (pLen)) # define canWriteT(hnd, pCmsg, pLen, pOvr) \ (NULL == pfnWriteT) ? NTCAN_NOT_IMPLEMENTED : \ pfnWriteT((hnd), (pCmsg), (pLen), (pOvr)) # define canGetOverlappedResultT(hnd, pOvr, pLen, bWait) \ (NULL == pfnGetOverlappedResultT) ? NTCAN_NOT_IMPLEMENTED : \ pfnGetOverlappedResultT((hnd), (pOvr), (pLen), (bWait)) # define canFormatEvent(ev,pParams,pBuf,bufsize) \ (NULL == pfnFormatEvent) ? NTCAN_NOT_IMPLEMENTED : \ pfnFormatEvent((ev), (pParams), (pBuf), (bufsize)) # define canFormatError(err, type, pBuf, bufsize) \ (NULL == pfnFormatError) ? NTCAN_NOT_IMPLEMENTED : \ pfnFormatError((err), (type), (pBuf), (bufsize)) # if defined (NTCAN_FD) # define canTakeX(hnd, pCmsg, pLen) \ (NULL == pfnTakeX) ? NTCAN_NOT_IMPLEMENTED : \ pfnTakeX((hnd), (pCmsg), (pLen)) # define canReadX(hnd, pCmsg, pLen, pOvr) \ (NULL == pfnReadX) ? NTCAN_NOT_IMPLEMENTED : \ pfnReadX((hnd), (pCmsg), (pLen), (pOvr)) # define canSendX(hnd, pCmsg, pLen) \ (NULL == pfnSendX) ? NTCAN_NOT_IMPLEMENTED : \ pfnSendX((hnd), (pCmsg), (pLen)) # define canWriteX(hnd, pCmsg, pLen, pOvr) \ (NULL == pfnWriteX) ? NTCAN_NOT_IMPLEMENTED : \ pfnWriteX((hnd), (pCmsg), (pLen), (pOvr)) # define canGetOverlappedResultX(hnd, pOvr, pLen, bWait) \ (NULL == pfnGetOverlappedResultX) ? NTCAN_NOT_IMPLEMENTED : \ pfnGetOverlappedResultX((hnd), (pOvr), (pLen), (bWait)) # endif /* NTCAN_FD */ /* Disable warning about potentially uninitialized local variables */ # if defined (_MSC_VER) __pragma(warning(disable:4701)) # endif #endif static uint32_t num_baudrate; static void set_num_baudrate(uint32_t baud) { switch (baud) { case NTCAN_BAUD_1000: num_baudrate=1000000;break; case NTCAN_BAUD_800: num_baudrate= 800000;break; case NTCAN_BAUD_500: num_baudrate= 500000;break; case NTCAN_BAUD_250: num_baudrate= 250000;break; case NTCAN_BAUD_125: num_baudrate= 125000;break; case NTCAN_BAUD_100: num_baudrate= 100000;break; case NTCAN_BAUD_50: num_baudrate= 50000;break; case NTCAN_BAUD_20: num_baudrate= 20000;break; case NTCAN_BAUD_10: num_baudrate= 10000;break; default: num_baudrate=0;break; } } #ifndef MAIN_CALLTYPE #define MAIN_CALLTYPE #endif /************************************************************************/ /************************************************************************/ /* Function: main() */ /* The "#ifdef-massacre" simply adapts the prototype of main() to */ /* peculiarities of certain systems. */ /************************************************************************/ /************************************************************************/ /* AB: not quite sure, if 400 is the version this behaviour was changed. Might have been earlier.*/ #if defined(_WIN32_WCE) && (_WIN32_WCE < 400) int main(DWORD hInstance, /* Handle to current instance of application */ DWORD hPrevInstance, /* Handle to prev. instance of application */ TCHAR *pCmdLine, /* Command line for application w/o appname */ int nShowCmd) /* Windows show mode */ #else /* of _WIN32_WCE < 400 */ # ifdef RMOS int _FAR main(int argc, char *argv[]) # else /* of RMOS */ int MAIN_CALLTYPE main(int argc, char *argv[]) # endif /* of RMOS */ #endif /* of _WIN32_WCE < 400 */ { CANTEST_CTX *pCtx; NTCAN_HANDLE h0; CMSG cmdmsg; /* can-data from the command-line */ CMSG_T cmdmsg_t; /* can-data from the command-line */ #if defined(NTCAN_FD) CMSG_X cmdmsg_x; /* can-data from the command-line */ #endif EVMSG evmsg; int32_t test; int32_t net = 0; int32_t idstart = 0; int32_t idend = 0; int32_t maxcount = 1; int32_t txbufsize = 10; int32_t rxbufsize = 100; int32_t txtout = 1000; int32_t rxtout = 5000; int32_t idnow = 0; #ifdef D3X uint32_t baudrate = 7; #else uint32_t baudrate = 2; uint32_t time_1; #endif /* DX3 */ int32_t testcount = 10; int32_t ever = 0; int8_t str_buf[100]; int32_t data_from_cmd = 0; TIME_TYPE start_time, stop_time; TIME_TYPE start_test_time, stop_test_time; NTCAN_RESULT ret; int32_t h, i, j, k; int32_t frames = -1; CMSG *cm; #if defined(NTCAN_IOCTL_GET_TX_TS_WIN) || defined(NTCAN_IOCTL_GET_TIMESTAMP) CMSG_T *cmt; #endif #if defined(NTCAN_FD) CMSG_X *cmx; #endif int32_t len; char *pend; #ifdef NTCAN_IOCTL_GET_TIMESTAMP uint64_t lastStamp = 0; #endif #ifdef NTCAN_IOCTL_SET_BUSLOAD_INTERVAL uint32_t bl_event_period = 0; #endif #ifdef _WIN32 /* BL: not quite sure, if 400 is the version this behaviour was changed. Might have been earlier.*/ # if defined(_WIN32_WCE) && (_WIN32_WCE < 400) TCHAR *argv[30]; int argc; argc = CreateArgvArgc(TEXT("cantest.exe"), argv, pCmdLine); # elif UNDER_RTSS # else HANDLE hEvent = NULL; /* Event for overlapped operation */ OVERLAPPED overlapped; /* overlapped-structure */ # endif /* of _WIN32_WCE */ #endif /* of _WIN32 */ uint8_t rtr = 0; /* * Initialize function pointer if parts of the API are dynamically loaded */ #ifdef CANTEST_DYNLOAD DynLoad(); #endif /* of CANTEST_DYNLOAD */ /* * Parse command line parameters and assign test specific default values */ if (argc > 1) { /* Parameter 'test' */ test = atoi(argv[1]); if (test<0) { help(test); return(0); } } else { help(-1); return(-1); } /* Adapt some default values according to test type */ if(64 == test || 74 == test || 84 == test) { testcount = 1; baudrate = 0xFFFFFFFFU; } if (argc > 2) { /* Parameter 'net' */ net = atoi(argv[2]); if((net < 0) || (net > NTCAN_MAX_NETS)) { printf("!! Parameter 'net' invalid !!\n"); return(-1); } } if (argc > 3) { /* Parameter 'id-1st' */ idstart = strtoul(argv[3], &pend, 0); if (*pend != '\0') { printf("!! Parameter 'id-1st' invalid !!\n"); return(-1); } } if (argc > 4) { /* Parameter 'id-last' */ idend = strtoul(argv[4], &pend, 0); if (*pend != '\0') { printf("!! Parameter 'id-last' invalid !!\n"); return(-1); } } /* Allocate memory of context */ pCtx = CANTEST_ALLOC(sizeof(CANTEST_CTX)); if(NULL == pCtx) { printf("!! Error allocating context !!\n"); return(-1); } else { memset(pCtx, 0, sizeof(CANTEST_CTX)); } if (argc > 5) { /* Parameter 'count' */ maxcount = atoi(argv[5]); /* * Negative value of maxcount for receive operations means opening the * handle with NTCAN_MODE_MARK_INTERACTION, for transmit operations RTR * frames are send instead of data frames. */ if(maxcount < 0) { if(IS_READ_TEST(test)) { pCtx->mode |= NTCAN_MODE_MARK_INTERACTION; maxcount *= -1; } else if(IS_WRITE_TEST(test) || IS_SEND_TEST(test)) { rtr = NTCAN_RTR; maxcount *= -1; } else { printf("Parameter 'count' invalid !!\n"); CANTEST_FREE(pCtx); return(-1); } } else if(0 == maxcount) { if(IS_READ_TEST(test)) { pCtx->mode |= NTCAN_MODE_NO_INTERACTION; maxcount = 1; } } if (IS_SEND_TEST(test) || IS_WRITE_TEST(test) || (5 == test)) { if (maxcount > MAX_TX_MSG_CNT) { maxcount = MAX_TX_MSG_CNT; printf("Limited count to %ld!\n", (long)MAX_TX_MSG_CNT); } } else { if (maxcount > MAX_RX_MSG_CNT) { maxcount = MAX_RX_MSG_CNT; printf("Limited count to %ld!\n", (long)MAX_RX_MSG_CNT); } } } if (argc > 6) { /* Parameter 'txbufsize' */ txbufsize = atoi(argv[6]); } if (argc > 7) { /* Parameter 'rxbufsize' */ rxbufsize = atoi(argv[7]); } if (argc > 8) { /* Parameter 'txtout' */ txtout = atoi(argv[8]); } if (argc > 9) { /* Parameter 'rxtout' */ rxtout = atoi(argv[9]); } if (argc > 10) { /* Parameter 'baudrate' */ if(!strcmp(argv[10], "auto")) { baudrate = NTCAN_AUTOBAUD; } else if(!strcmp(argv[10], "disable")) { baudrate = NTCAN_NO_BAUDRATE; } else if(!strcmp(argv[10], "no")) { baudrate = 0xFFFFFFFFU; } else { baudrate = strtoul(argv[10], &pend, 0); if (*pend != '\0') { printf("!! Parameter 'baudrate' invalid !!\n"); CANTEST_FREE(pCtx); return(-1); } } } if (argc > 11) { /* Parameter 'testcount' */ testcount = atoi(argv[11]); } else { /* Default testcount to 'endless' for receive operations */ if (IS_TAKE_TEST(test) || IS_READ_TEST(test) || 4 == test) { testcount = -1; } } /* * Prepare default-data */ k = 1; for (i = 0; i < MAX_TX_MSG_CNT; i++) { cm = &pCtx->txmsg[i]; cm->id = idstart; cm->len = 8 | rtr; *((uint32_t*)(&cm->data[0])) = 0; *((uint32_t*)(&cm->data[4])) = k; #if defined(NTCAN_IOCTL_GET_TX_TS_WIN) cmt = &pCtx->txmsg_t[i]; cmt->id = idstart; cmt->len = 8 | rtr; *((uint32_t*)(&cmt->data[0])) = 0; *((uint32_t*)(&cmt->data[4])) = k; #endif #if defined(NTCAN_FD) cmx = &pCtx->txmsg_x[i]; cmx->id = idstart; cmx->len = (uint8_t)(NTCAN_FD | NTCAN_DATASIZE_TO_DLC(64)); *((uint32_t*)(&cmx->data[0])) = 0; *((uint32_t*)(&cmx->data[4])) = k; *((uint32_t*)(&cmx->data[8])) = 2; *((uint32_t*)(&cmx->data[12])) = 3; *((uint32_t*)(&cmx->data[16])) = 4; *((uint32_t*)(&cmx->data[20])) = 5; *((uint32_t*)(&cmx->data[24])) = 6; *((uint32_t*)(&cmx->data[28])) = 7; *((uint32_t*)(&cmx->data[32])) = 8; *((uint32_t*)(&cmx->data[36])) = 9; *((uint32_t*)(&cmx->data[40])) = 10; *((uint32_t*)(&cmx->data[44])) = 11; *((uint32_t*)(&cmx->data[48])) = 12; *((uint32_t*)(&cmx->data[52])) = 13; *((uint32_t*)(&cmx->data[56])) = 14; *((uint32_t*)(&cmx->data[60])) = 15; #endif k++; } for (i = 0; i <= (idend>2047?2047:idend)-idstart; i++) { cm = &pCtx->rxmsg[i]; cm->id = idstart+i; #ifdef NTCAN_IOCTL_GET_TIMESTAMP cmt = &pCtx->rxmsg_t[i]; cmt->id = idstart+i; #endif #if defined(NTCAN_FD) cmx = &pCtx->rxmsg_x[i]; cmx->id = idstart+i; #endif } /* * Try to fetch data-bytes from command-line */ evmsg.evid = (idstart & 0xff) + NTCAN_EV_BASE; cmdmsg.id = idstart; cmdmsg.len = 0 | rtr; #if defined(NTCAN_IOCTL_GET_TIMESTAMP) cmdmsg_t.id = cmdmsg.id; cmdmsg_t.len = cmdmsg.len; #endif #if defined(NTCAN_FD) cmdmsg_x.id = cmdmsg.id; cmdmsg_x.len = cmdmsg.len | NTCAN_FD; #endif evmsg.len = 0; for (i = 12; (i < argc) && (i < 12+64); i++) { uint32_t ulData = strtoul(argv[i], &pend, 0); if(*pend != '\0' || ulData > 255 ) { if( ulData == (uint32_t)-1) { cmdmsg.len = 0 | rtr; #if defined(NTCAN_IOCTL_GET_TIMESTAMP) cmdmsg_t.len = cmdmsg.len; #endif #if defined(NTCAN_FD) cmdmsg_x.len = cmdmsg.len | NTCAN_FD; #endif i = 13; break; } printf("!! Parameter data%ld invalid !!\n", (long)(i - 12)); CANTEST_FREE(pCtx); return(-1); } if(i < 20) cmdmsg.data[i-12] = (char)ulData; if(i < 27) cmdmsg.len ++; #if defined(NTCAN_IOCTL_GET_TIMESTAMP) if(i < 20) cmdmsg_t.data[i-12] = (char)ulData; if(i < 27) cmdmsg_t.len ++; #endif #if defined(NTCAN_FD) if(i < 76) cmdmsg_x.data[i-12] = (char)ulData; if(i < 20) { cmdmsg_x.len ++; } else { switch(i) { case 20: case 24: case 28: case 32: case 36: case 44: case 60: cmdmsg_x.len ++; break; } } #endif if(i < 20) evmsg.evdata.c[i-12] = (char)ulData; if(i < 27) evmsg.len ++; } if (i > 12) { data_from_cmd = 1; for (i = 0; i < MAX_TX_MSG_CNT; i++) { pCtx->txmsg[i] = cmdmsg; #if defined(NTCAN_IOCTL_GET_TX_TS_WIN) pCtx->txmsg_t[i] = cmdmsg_t; #endif #if defined(NTCAN_FD) pCtx->txmsg_x[i] = cmdmsg_x; #endif } } if (testcount == -1) { ever = 1; } /* * Print test configuration */ printf("test=%ld net=%ld ", (long)test, (long)net); if ((idstart > 0x7FF) || (idend > 0x7FF)) { printf("id-1st=0x%lx id-last=0x%lx ", (unsigned long)idstart, (unsigned long)idend); } else { printf("id-1st=%ld id-last=%ld ", (unsigned long)idstart, (unsigned long)idend); } printf("count=%ld\ntxbuf=%ld rxbuf=%ld txtout=%ld rxtout=%ld ", (unsigned long)maxcount, (unsigned long)txbufsize, (unsigned long)rxbufsize, (unsigned long)txtout, (unsigned long)rxtout); if (baudrate == 0xFFFFFFFFU) { printf("baudrate=(don't change) "); } else if (baudrate >= 15) { printf("baudrate=0x%lx ", (unsigned long)baudrate); } else { printf("baudrate=%ld ", (unsigned long)baudrate); } set_num_baudrate(baudrate); if (num_baudrate) { printf("(%u baud) ",(unsigned int)num_baudrate); } printf("\ntestcount=%ld ", (unsigned long)testcount); /* * Set object-mode, if needed */ if ((32 == test) || (42 == test)|| (82 == test)) { pCtx->mode |= NTCAN_MODE_OBJECT; } #if defined(NTCAN_FD) /* Set CAN-FD mode bit if header defines support for it */ if( (60 == test) || (61 == test) || (62 == test) || (72 == test) || (82 == test) || (63 == test) || (73 == test)) { pCtx->mode |= NTCAN_MODE_FD; } #endif /* * Mark overlapped for Windows overlapped I/O tests and create * the event parameter of the Win32 overlapped structure */ #if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(UNDER_RTSS) if ((6 == test) || (7 == test) || (16 == test)) { pCtx->mode |= NTCAN_MODE_OVERLAPPED; hEvent = CreateEvent(NULL, TRUE, /* flag for manual-reset */ FALSE, /* flag for initial state */ NULL); if (NULL == hEvent) { printf("Creating event for overlapped operation failed\n"); CANTEST_FREE(pCtx); return(-1); } overlapped.hEvent = hEvent; } #endif /* _WIN32 && !_WIN32_WCE && !UNDER_RTSS */ /* * Async I/O test for UNIX(Solaris) D3X interface driver * Install signal handler and make driver call SIGIO for each received frame */ #if defined(unix) && defined(D3X) if (test == 6) { if (signal(SIGIO, sigio_handler) == SIG_ERR) { printf("Initialising signal handler failed\n"); CANTEST_FREE(pCtx); return(-1); } pCtx->mode |= (NTCAN_MODE_OVERLAPPED | SIGIO); } #endif /* unix && D3X */ #if (defined VXWORKS) && WANT_PRIO_CHECK == 1 if (ERROR == _checkPriority(net)) { CANTEST_FREE(pCtx); return(ERROR); /* Check priority of caller */ } #endif #ifdef RMOS switch (test) { case 21: pCtx->mode |= NTCAN_MODE_SLOW; break; case 31: pCtx->mode |= NTCAN_MODE_FAST; break; case 41: pCtx->mode |= NTCAN_MODE_BURST; break; } #endif if(pCtx->mode & NTCAN_MODE_MARK_INTERACTION) { printf(" (Mode: Mark Interaction)"); } else if(pCtx->mode & NTCAN_MODE_NO_INTERACTION) { printf(" (Mode: No Interaction)"); } printf("\n"); #if defined(NTCAN_IOCTL_GET_TX_TS_WIN) if ( (21 == test) || (20 == test) ) { pCtx->mode |= NTCAN_MODE_TIMESTAMPED_TX; } #endif /* * Force thread affinity to one CPU or core on multiprocessor/multicore * hardware, if TSC of different CPUs/cores get out of sync. */ #ifdef CANTEST_MULTIPROCESSOR if(ForceThreadAffinity() != 0) printf("Forcing thread affinity to dedicated processor failed !!\n"); #endif /* of CANTEST_MULTIPROCESSOR */ #ifdef CANTEST_USE_SIGUSR1_HANDLER /* * Setup dummy signal handler for testing */ if (signal(SIGUSR1, &sigusr1_handler) == SIG_ERR) { printf("Initialising USR1 signal handler failed\n"); CANTEST_FREE(pCtx); return(-1); } #endif /* * Open CAN handle and check success */ for(;;) { if (21 == test) { /* Timeouts are (mis-)used for Timestamped TX purposes */ ret = canOpen(net, pCtx->mode, txbufsize, rxbufsize, 0, 0, &h0); } else { ret = canOpen(net, pCtx->mode, txbufsize, rxbufsize, txtout, rxtout, &h0); } #if defined(NTCAN_FD) if ((ret != NTCAN_SUCCESS) && (pCtx->mode & NTCAN_MODE_FD)) { printf("canOpen returned: %s, retrying without NTCAN_MODE_FD\n", get_error_str(str_buf,ret)); pCtx->mode &= ~NTCAN_MODE_FD; continue; } #endif break; } /* of for(;;) */ if (ret != NTCAN_SUCCESS) { printf("canOpen returned: %s\n", get_error_str(str_buf,ret)); CANTEST_FREE(pCtx); return(-1); } else { CAN_IF_STATUS cstat; /* Get the CAN controller type */ ret = canStatus(h0, &cstat); if (NTCAN_SUCCESS == ret) { #ifdef NTCAN_GET_CTRL_TYPE pCtx->ctrl_type = (uint8_t)NTCAN_GET_CTRL_TYPE(cstat.boardstatus); #endif } } /* * For tests which require timestamp support check if driver/hardware * supports timestamps and return timestamp frequency */ #ifdef NTCAN_IOCTL_GET_TIMESTAMP if ((23 == test) || (22 == test) || (21 == test) || (20 == test) || (42 == test) || (100 == test) || (16 == test) || (63 == test) || (62 == test) || (61 == test) || (60 == test) || (82 == test) || (110 == test) || (66 == test) ) { if(get_timestamp_freq(h0, &pCtx->udtTimestampFreq, 1) != 0) { CANTEST_FREE(pCtx); return(-1); } } #endif /* * Change idstart/idend to event range for the read event test */ if(4 == test) { idstart = NTCAN_EV_BASE + (idstart & 0xFF); idend = NTCAN_EV_BASE + (idend & 0xFF); } /* * Configure the CAN-ID filter for events before setting the baudrate * to e.g. capture baudrate change events. */ if((idend <= NTCAN_EV_LAST) && (idstart >= NTCAN_EV_BASE)) { for (i = idstart; i <= idend; i++) { ret = set_can_id(h0, i); if (ret != NTCAN_SUCCESS) { printf("canIdAdd for event %ld returns error %s\n", (long)i, get_error_str(str_buf, ret)); break; } } #ifdef NTCAN_IOCTL_SET_BUSLOAD_INTERVAL /* * If we just want to capture the busload event use txtout as * event period */ if((NTCAN_EV_BUSLOAD == idstart) && (idstart == idend)) { bl_event_period = txtout; ret = canIoctl(h0, NTCAN_IOCTL_SET_BUSLOAD_INTERVAL, &bl_event_period); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_SET_BUSLOAD_INTERVAL failed with: %s\n", get_error_str(str_buf,ret)); } else { /* Get configured bus load event period */ ret = canIoctl(h0, NTCAN_IOCTL_GET_BUSLOAD_INTERVAL, &bl_event_period); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_GET_BUSLOAD_INTERVAL failed with: %s\n", get_error_str(str_buf,ret)); } else { printf("Bus load event period set to %ld ms\n", (long)bl_event_period); } } } /* of if(idstart == idend == NTCAN_EV_BUSLOAD) */ #endif } /* of if((idend <= NTCAN_EV_LAST ) && (idstart >= NTCAN_EV_BASE)) */ /* * Configure the baudrate for all tests but sending events. */ if ( (test != 5) && (test != 53) && (baudrate!=0xFFFFFFFFU) ) { ret = canSetBaudrate(h0, baudrate); if (ret != NTCAN_SUCCESS) { printf("canSetBaudrate returned: %s\n", get_error_str(str_buf,ret)); CANTEST_FREE(pCtx); return(-1); } } #ifdef NTCAN_IOCTL_SET_20B_HND_FILTER /* * Configure the CAN-ID filter using 20B handle filter */ if(((idstart & 0x60000000) == 0x60000000) && ((idend & 0x60000000) == 0x60000000)) { unsigned long ulFilterMask = idend & 0x1FFFFFFF; ret = canIdAdd(h0, idstart & 0x2fffffff); if(ret != NTCAN_SUCCESS) { printf("canIdAdd for id %lx returns error %s\n", (long)idend, get_error_str(str_buf,ret)); CANTEST_FREE(pCtx); return(-1); } else { ret = canIoctl(h0, NTCAN_IOCTL_SET_20B_HND_FILTER, &ulFilterMask); if(ret != NTCAN_SUCCESS) { printf("canIoctl to set filter mask %lx returns error %s\n", (unsigned long)ulFilterMask, get_error_str(str_buf,ret)); CANTEST_FREE(pCtx); return(-1); } } printf("Using CAN 2.0B Acceptance Code: 0x%08lx / Acceptance Mask: 0x%08lx\n", (unsigned long)(idstart & 0x1fffffff), (unsigned long)ulFilterMask); idstart = 2048; /* No further canIdAdd() */ idend = 0; } else #endif { /* * Receive 2.0B IDs if either idend is in 2.0B or event range and * idstart is 2.0A ID or both idend and idstart are in 2.0B range */ if(idstart <= idend) { if (((idend >= NTCAN_20B_BASE) && (idstart < 2048)) || (((idstart & NTCAN_20B_BASE) == NTCAN_20B_BASE) && ((idend & NTCAN_20B_BASE) == NTCAN_20B_BASE))) { ret = canIdAdd(h0, NTCAN_20B_BASE); if (ret != NTCAN_SUCCESS) { printf("canIdAdd for all 29-Bit ids returns error %s\n", get_error_str(str_buf,ret)); } } } /* of if(idstart <= idend) */ } if (idend > 2047) { idend = 2047; } /* * Enable the 11-bit identifier */ for (i = idstart; i <= idend; i++) { ret = set_can_id(h0, i); if (ret != NTCAN_SUCCESS) { printf("canIdAdd for can-id %ld returns error %s\n", (long)i, get_error_str(str_buf,ret)); break; } } idnow = idstart; start_test_time = GET_CURRENT_TIME; /* * The following loop repeats the entire test "testcount"-times */ for (h = 0; (h < testcount) || ever; h++) { /* * Choose the desired test */ switch (test) { #ifndef D3X /* * canSend() * non-blocking write or write without wait */ case 0: case 50: len = maxcount; if (!data_from_cmd) { for (i = 0; i < len; i++) { *((uint32_t*)(&pCtx->txmsg[i].data[0])) = h; } } if (50 == test) { for (i = 0; i < len; i++) { pCtx->txmsg[i].id = idnow++; if (idnow > idend) { idnow = idstart; } } } start_time = GET_CURRENT_TIME; ret = canSend(h0, pCtx->txmsg, &len); stop_time = GET_CURRENT_TIME; printf("Duration=%9lu %s Can-Messages=%ld\n", (unsigned long)(stop_time-start_time), TIME_UNITS, (unsigned long)len); if (ret != NTCAN_SUCCESS) { printf("canSend returned: %s\n", get_error_str(str_buf,ret)); SLEEP(1000); } else { SLEEP(txtout); } break; /* * canSendT()/canWriteT()/canSendX()/canWriteT() * non-blocking timestamped write */ #if defined(NTCAN_IOCTL_GET_TX_TS_WIN) case 20: case 21: #if defined(NTCAN_FD) case 60: case 61: #endif len = maxcount; if (!data_from_cmd) { for (i = 0; i < len; i++) { *((uint32_t*)(&pCtx->txmsg_t[i].data[0])) = h; #if defined(NTCAN_FD) *((uint32_t*)(&pCtx->txmsg_x[i].data[0])) = h; #endif } } ret = canIoctl(h0, NTCAN_IOCTL_GET_TIMESTAMP, &pCtx->txmsg_t[0].timestamp); if (ret != NTCAN_SUCCESS) { printf("canIoctl returned: %s (failed to acquire timestamp)\n", get_error_str(str_buf, ret)); } #if defined(NTCAN_FD) pCtx->txmsg_x[0].timestamp = pCtx->txmsg_t[0].timestamp; pCtx->txmsg_x[0].timestamp += ((pCtx->udtTimestampFreq * (uint64_t)txtout) / 1000ULL); /* Schedule first frame to be send in "TX-timeout" milliseconds */ for (i = 1; i < len; i++) { pCtx->txmsg_x[i].timestamp = pCtx->txmsg_x[i-1].timestamp + ((pCtx->udtTimestampFreq * (uint64_t)rxtout) / 1000ULL); /* Every other frame will follow with "RX-timeout" milliseconds offset */ } #endif pCtx->txmsg_t[0].timestamp += ((pCtx->udtTimestampFreq * (uint64_t)txtout) / 1000ULL); /* Schedule first frame to be send in "TX-timeout" milliseconds */ for (i = 1; i < len; i++) { pCtx->txmsg_t[i].timestamp = pCtx->txmsg_t[i-1].timestamp + ((pCtx->udtTimestampFreq * (uint64_t)rxtout) / 1000ULL); /* Every other frame will follow with "RX-timeout" milliseconds offset */ } start_time = GET_CURRENT_TIME; switch(test) { case 20: ret = canSendT(h0, pCtx->txmsg_t, &len); break; case 21: ret = canWriteT(h0, pCtx->txmsg_t, &len, NULL); break; #if defined(NTCAN_FD) case 60: ret = canSendX(h0, pCtx->txmsg_x, &len); break; case 61: ret = canWriteX(h0, pCtx->txmsg_x, &len, NULL); break; #endif } stop_time = GET_CURRENT_TIME; printf("Duration=%9lu %s Can-Messages=%ld\n", (unsigned long)(stop_time-start_time), TIME_UNITS, (unsigned long)len); if (ret != NTCAN_SUCCESS) { printf("canSend returned: %s\n", get_error_str(str_buf,ret)); SLEEP(1000); } else { if(test == 20 || test == 21) { /* Sleep for some time (500ms + duration of scheduled frames) * in order to prevent close from aborting our running canSendT scheduling... */ SLEEP(500 + txtout + ((maxcount-1) * rxtout)); } } break; #endif #endif /* * canWrite() * blocking write or write with wait */ case 1: #ifdef RMOS case 21: #endif case 31: case 41: case 51: len = maxcount; if (!data_from_cmd) { for (i = 0; i < len; i++) { *((uint32_t*)(&pCtx->txmsg[i].data[0])) = h; } } if (51 == test) { for (i = 0; i < len; i++) { pCtx->txmsg[i].id = idnow++; if (idnow > idend) { idnow = idstart; } } } start_time = GET_CURRENT_TIME; ret = canWrite(h0, pCtx->txmsg, &len, NULL); stop_time = GET_CURRENT_TIME; printf("Duration=%9lu %s Can-Messages=%ld \n", (unsigned long)(stop_time-start_time), TIME_UNITS, (unsigned long)len); if (ret != NTCAN_SUCCESS) { printf("canWrite returned: %s\n", get_error_str(str_buf,ret) ); SLEEP(1000); } break; case 11: if (!data_from_cmd) { for (i = 0; i < maxcount; i++) { *((uint32_t*)(&pCtx->txmsg[i].data[0])) = h; } } start_time = GET_CURRENT_TIME; #if 0 for (i = 0; i < maxcount; i++) { len = 1; (void)canWrite(h0, &txmsg[i], &len, NULL); } #else for (i = 0; i < maxcount; i++) { do { len = 1; ret = canSend(h0, &pCtx->txmsg[i], &len); } while (ret == NTCAN_CONTR_BUSY); } #endif stop_time = GET_CURRENT_TIME; printf("Duration=%6ld %s Can-Messages=%ld \n", (unsigned long)(stop_time-start_time), TIME_UNITS, (unsigned long)len); if (ret != NTCAN_SUCCESS) { printf("canWrite returned: %s\n", get_error_str(str_buf,ret)); SLEEP(1000); } break; /* * canTake() * non-blocking read or read without wait */ #ifndef D3X case 32: len = idend-idstart+1; if(rxtout) { SLEEP(rxtout); } goto take_common; case 12: /* test with output disabled */ pCtx->mode |= NO_ASCII_OUTPUT; case 2: len = maxcount; take_common: start_time = GET_CURRENT_TIME; #ifdef RTAI /* To better see canTake working ... */ SLEEP(100); start_time += 100000; /* us */ start_test_time += 100000; /* us */ #endif ret = canTake(h0, pCtx->rxmsg, &len); stop_time = GET_CURRENT_TIME; if (frames >= 10000) { stop_test_time = GET_CURRENT_TIME; printf("Test-Duration=%lu %s frames=%ld\n", (unsigned long)(stop_test_time-start_test_time), TIME_UNITS, (unsigned long)frames); start_test_time = GET_CURRENT_TIME; frames = 0; } if (!(pCtx->mode & NO_ASCII_OUTPUT)) { printf("Duration=%9lu %s Can-Messages=%ld\n", (unsigned long)(stop_time-start_time), TIME_UNITS, (unsigned long)len); } if (ret == NTCAN_SUCCESS) { if ((pCtx->mode & NO_ASCII_OUTPUT)) { if (frames == -1) { start_test_time = GET_CURRENT_TIME; frames = 0; continue; } } for (i = 0; i < len; i++) { print_cmsg(&pCtx->rxmsg[i], pCtx); frames ++; } } else { printf("canTake returned: %s\n", get_error_str(str_buf,ret)); SLEEP(1000); } break; /* * canRead() * blocking read or read with wait */ case 33: /* test with output disabled and data validation */ case 13: /* test with output disabled */ pCtx->mode |= NO_ASCII_OUTPUT; #endif /* of !D3X */ case 3: len = maxcount; start_time = GET_CURRENT_TIME; ret = canRead(h0, pCtx->rxmsg, &len, NULL); #ifdef RTAI /* To better see canRead working ... */ SLEEP(100); start_time += 100000; /* us */ start_test_time += 100000; /* us */ #endif stop_time = GET_CURRENT_TIME; if (frames >= 10000) { stop_test_time = GET_CURRENT_TIME; printf("Test-Duration=%lu %s frames=%ld\n", (unsigned long)(stop_test_time-start_test_time), TIME_UNITS, (unsigned long)frames); start_test_time = GET_CURRENT_TIME; frames = 0; } if (!(pCtx->mode & NO_ASCII_OUTPUT)) { printf("Duration=%6lu %s Can-Messages=%ld \n", (unsigned long)(stop_time-start_time), TIME_UNITS, (unsigned long)len); } if (ret == NTCAN_SUCCESS) { if ((pCtx->mode & NO_ASCII_OUTPUT)) { if (frames == -1) { start_test_time = GET_CURRENT_TIME; frames = 0; } } for (i = 0; i < len; i++) { if (33 == test) { static uint32_t counter; pCtx->mode |= NO_ASCII_OUTPUT; if ( (pCtx->rxmsg[i].msg_lost != 0) || (*((uint32_t*)&pCtx->rxmsg[i].data[4]) == 1) ) { counter = *((uint32_t*)&pCtx->rxmsg[i].data[4]); } if ( (pCtx->rxmsg[i].len != 8) || (pCtx->rxmsg[i].id != idstart) || (counter != *((uint32_t*)&pCtx->rxmsg[i].data[4]) ) ) { printf("Wrong Frame received. Counter=0x%lx 0x%lx 0x%lx %u!\n", (unsigned long)counter, (unsigned long)*((uint32_t*)&pCtx->rxmsg[i].data[4]), (unsigned long)pCtx->rxmsg[i].id, (unsigned int)pCtx->rxmsg[i].msg_lost); pCtx->mode &= ~NO_ASCII_OUTPUT; print_cmsg(&pCtx->rxmsg[i], pCtx); exit(1); } counter++; } print_cmsg(&pCtx->rxmsg[i], pCtx); frames ++; } } else { printf("canRead returned: %s\n", get_error_str(str_buf,ret)); SLEEP(100); #ifdef RTAI start_test_time += 100000; /* us, this should be done more genric for other OS */ #endif } break; #ifdef NTCAN_IOCTL_GET_TIMESTAMP /* * canTakeT()/canTakeX() * non-blocking read */ #ifdef NTCAN_FD case 82: #endif case 42: len = idend-idstart+1; if(rxtout) { SLEEP(rxtout); } goto taket_common; #ifdef NTCAN_FD case 72: pCtx->mode |= NO_ASCII_OUTPUT; #endif case 22: #ifdef NTCAN_FD case 62: #endif len = maxcount; taket_common: start_time = GET_CURRENT_TIME; #ifdef RTAI /* To better see canTakeT working ... */ SLEEP(100); start_time += 100000; /* us */ start_test_time += 100000; /* us */ #endif #ifdef NTCAN_FD if(test == 62 || test == 72 || test == 82) { ret = canTakeX(h0, pCtx->rxmsg_x, &len); } else #endif { ret = canTakeT(h0, pCtx->rxmsg_t, &len); } stop_time = GET_CURRENT_TIME; if (frames >= 10000) { stop_test_time = GET_CURRENT_TIME; printf("Test-Duration=%lu %s frames=%ld\n", (unsigned long)(stop_test_time-start_test_time), TIME_UNITS, (unsigned long)frames); start_test_time = GET_CURRENT_TIME; frames = 0; } if (!(pCtx->mode & NO_ASCII_OUTPUT)) { printf("Duration=%9lu %s Can-Messages=%ld\n", (unsigned long)(stop_time-start_time), TIME_UNITS, (unsigned long)len); } if (ret == NTCAN_SUCCESS) { if ((pCtx->mode & NO_ASCII_OUTPUT)) { if (frames == -1) { start_test_time = GET_CURRENT_TIME; frames = 0; continue; } } for (i = 0; i < len; i++) { #ifdef NTCAN_FD if(test == 62 || test == 72 || test == 82) { print_cmsg_x(&pCtx->rxmsg_x[i], pCtx); } else #endif { print_cmsg_t(&pCtx->rxmsg_t[i], pCtx); } frames ++; } } else { printf("canTake* returned: %s\n", get_error_str(str_buf,ret)); SLEEP(1000); } break; /* * canReadT()/canReadX() * blocking read with timestamp support */ #ifdef NTCAN_FD case 73: /* test with output disabled and timestamp validation */ #endif case 43: /* test with output disabled and timestamp validation */ pCtx->mode |= NO_ASCII_OUTPUT; case 23: #ifdef NTCAN_FD case 63: #endif len = maxcount; start_time = GET_CURRENT_TIME; #ifdef NTCAN_FD if(test == 63 || test == 73) { ret = canReadX(h0, pCtx->rxmsg_x, &len, NULL); } else #endif { ret = canReadT(h0, pCtx->rxmsg_t, &len, NULL); } #ifdef RTAI /* To better see canRead working ... */ SLEEP(100); #endif stop_time = GET_CURRENT_TIME; if (frames >= 10000) { stop_test_time = GET_CURRENT_TIME; printf("Test-Duration=%lu %s frames=%ld\n", (unsigned long)(stop_test_time-start_test_time), TIME_UNITS, (unsigned long)frames); start_test_time = GET_CURRENT_TIME; frames = 0; } if (!(pCtx->mode & NO_ASCII_OUTPUT)) { printf("Duration=%6lu %s Can-Messages=%ld \n", (unsigned long)(stop_time-start_time), TIME_UNITS, (unsigned long)len); } if (ret == NTCAN_SUCCESS) { if (frames == -1) { start_test_time = GET_CURRENT_TIME; #ifdef NTCAN_FD if(test == 63 || test == 73) { lastStamp = pCtx->rxmsg_x[0].timestamp; } else #endif { lastStamp = pCtx->rxmsg_t[0].timestamp; } frames = 0; } for (i = 0; i < len; i++ ) { if (!(pCtx->mode & NO_ASCII_OUTPUT)) { #ifdef NTCAN_FD if(test == 63 || test == 73) { print_cmsg_x(&pCtx->rxmsg_x[i], pCtx); } else #endif { print_cmsg_t(&pCtx->rxmsg_t[i], pCtx); } } if ((pCtx->mode & NO_ASCII_OUTPUT)) { #ifdef NTCAN_FD if(test == 63 || test == 73) { if( lastStamp > pCtx->rxmsg_x[i].timestamp) { printf("Negative timestamp interval= 0x%"PRIx64",0x%"PRIx64"\n", lastStamp, pCtx->rxmsg_x[i].timestamp); } lastStamp = pCtx->rxmsg_x[i].timestamp; } else #endif { if( lastStamp > pCtx->rxmsg_t[i].timestamp) { printf("Negative timestamp interval= 0x%"PRIx64",0x%"PRIx64"\n", lastStamp, pCtx->rxmsg_t[i].timestamp); } lastStamp = pCtx->rxmsg_t[i].timestamp; } } frames++; } } else { printf("canRead* returned: %s\n", get_error_str(str_buf, ret)); SLEEP(100); } break; #endif /* * canReadEvent() * blocking read of status information and customer specific events */ case 4: start_time = GET_CURRENT_TIME; #ifndef D3X len = 1; ret = canRead(h0, (CMSG *)&evmsg, &len, NULL); #else ret = canReadEvent(h0, &evmsg, NULL); #endif stop_time = GET_CURRENT_TIME; printf("Duration=%lu %s\n", (unsigned long)(stop_time-start_time), TIME_UNITS); if (ret == NTCAN_SUCCESS) { printf("EVENT-ID=%8lx len=%01X data= ", (long)evmsg.evid, evmsg.len); for (j = 0; j < evmsg.len; j++) { printf("%02X ", evmsg.evdata.c[j]); } printf("\n"); print_event(&evmsg, 0, pCtx); } else { printf("Reading event returned: %s\n", get_error_str(str_buf,ret)); SLEEP(100); } break; #if 0 /* test-only !!!!!!!!!!!!!!!! */ case 44: len = maxcount; start_time = GET_CURRENT_TIME; SLEEP(1000); ret = canIoctl(h0, NTCAN_IOCTL_FLUSH_RX_FIFO, NULL); stop_time = GET_CURRENT_TIME; printf("Duration=%u %s\n", (unsigned long)(stop_time-start_time), TIME_UNITS); printf("pre canTake: len=%d maxcount=%d\n", (long)len, (long)maxcount); ret = canTake(h0, rxmsg, &len); printf("canTake returns: ret=%x len=%d\n", (long)ret, (long)len); break; case 45: len = maxcount; start_time = GET_CURRENT_TIME; SLEEP(1000); stop_time = GET_CURRENT_TIME; printf("Duration=%u %s\n", (uint32_t)(stop_time-start_time), TIME_UNITS); ret = canTake(h0, rxmsg, &len); printf("canTake returns: ret=%x len=%d\n", (int32_t)ret, (int32_t)len); break; case 46: { uint32_t val; len = maxcount; start_time = GET_CURRENT_TIME; SLEEP(1000); ret = canIoctl(h0, NTCAN_IOCTL_GET_RX_MSG_COUNT, &val); printf("GET_RX_MSG_COUNT=%d\n", (int32_t)val); ret = canIoctl(h0, NTCAN_IOCTL_FLUSH_RX_FIFO, NULL); stop_time = GET_CURRENT_TIME; printf("Duration=%u %s\n", (unsigned long)(stop_time-start_time), TIME_UNITS); ret = canTake(h0, rxmsg, &len); printf("canTake returns: ret=%x len=%d\n", (long)ret, (long)len); break; } #endif #ifdef NTCAN_IOCTL_GET_TIMESTAMP case 53: { uint64_t ts, ts_old, ts_mindiff; int cnt; cnt = 100000; ts_mindiff = UINT64_C(9999999999); ts_old = 0; printf("canIoctl(GET_TIMESTAMP), %d calls, ",cnt); start_time = GET_CURRENT_TIME; do { ret = canIoctl(h0, NTCAN_IOCTL_GET_TIMESTAMP, &ts); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_GET_TIMESTAMP failed with: %s\n", get_error_str(str_buf,ret)); break; } if (ts<ts_old) { printf("Timestamps not increasing!! Old=0x%" PRIx64 " New=0x%" PRIx64 ".\n",ts_old,ts); break; } ts-=ts_old; if (ts_mindiff>ts) ts_mindiff=ts; ts_old=ts; } while (--cnt); stop_time = GET_CURRENT_TIME; printf("Min_diff=%" PRIu64 " Duration=%lu %s\n", ts_mindiff, (unsigned long)(stop_time-start_time), TIME_UNITS); break; } #endif #ifdef unix case 54: { int iii,ppp; const int lens[10]={555,111,1234,765,777,3333,2345,888,1000,10}; if (!data_from_cmd) { for (i = 0; i < MAX_TX_MSG_CNT; i++) { *((uint32_t*)(&pCtx->txmsg[i].data[0])) = h; } } len=maxcount; printf("Parent: Testcount=%d.\n",h); start_time = GET_CURRENT_TIME; for (iii = 0; iii< 10 ; iii++) { if ((ppp=fork())==0) { /* we are the child */ for (i = 0; i < len; i++) { pCtx->txmsg[i].id = iii; } start_time = GET_CURRENT_TIME; SLEEP(lens[iii]); ret = canSend(h0, pCtx->txmsg, &len); stop_time = GET_CURRENT_TIME; printf("Child %d: Duration=%9lu %s Can-Messages=%ld \n", iii,(unsigned long)(stop_time-start_time), TIME_UNITS, (unsigned long)len); if (ret != NTCAN_SUCCESS) { printf("Child %d: canSend returned: %s\n", iii, get_error_str(str_buf,ret) ); } SLEEP(500); #ifndef nto SLEEP(4500); /* fork not working that way here, canClose would render the handle useless for all forked childs */ #endif printf("Child %d: Exiting...\n",iii); h=testcount; /* last testcount for this child, child shouldn't run any (more) tests ... */ break; } else { printf("Parent: Started child %d with pid %d.\n",iii,ppp); } } if (iii==10) { stop_time = GET_CURRENT_TIME; printf("Parent: Duration=%9lu %s\n",(unsigned long)(stop_time-start_time), TIME_UNITS); printf("Parent: Sleeping 5 secs...\n");fflush(stdout);SLEEP(5000); printf("Parent: Sleeping done.\n");fflush(stdout); } break; } #endif case 55: /* close - send test */ ret = canClose(h0); printf("canClose returned: %s\n",get_error_str(str_buf,ret)); /* should be SUCCESS */ len = maxcount; ret = canSend(h0, pCtx->txmsg, &len); printf("canSend returned: %s - len=%u\n", get_error_str(str_buf,ret), (unsigned int)len); /* should be INVALID HANDLE */ break; #if 0 case 56: { int cnt; uint32_t bb,bb0; cnt = maxcount * 1000;if (cnt>100000) cnt=100000; printf("canGetBaudrate(), %d calls, ",cnt); ret = canGetBaudrate(h0, &bb0); if (ret != NTCAN_SUCCESS) { printf("canGetBaudrate failed with: %s\n", get_error_str(str_buf,ret)); } start_time = GET_CURRENT_TIME; do { ret = canGetBaudrate(h0, &bb); if (ret != NTCAN_SUCCESS) { printf("canGetBaudrate failed with: %s\n", get_error_str(str_buf,ret)); break; } if (bb!=bb0) { printf("Baudrate has suddenly changed! Old=0x%x New=0x%x\n",(unsigned int)bb0,(unsigned int)bb); break; } } while (--cnt); stop_time = GET_CURRENT_TIME; printf("Duration=%lu %s\n", (unsigned long)(stop_time-start_time), TIME_UNITS); break; } #endif #if defined NTCAN_IOCTL_GET_BUS_STATISTIC && !defined D3X case 64: { NTCAN_BUS_STATISTIC stat; NTCAN_CTRL_STATE ctrl_state; ret = canIoctl(h0, NTCAN_IOCTL_GET_BUS_STATISTIC, &stat); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_GET_BUS_STATISTIC failed with: %s\n", get_error_str(str_buf, ret)); break; } ret = canIoctl(h0, NTCAN_IOCTL_GET_CTRL_STATUS, &ctrl_state); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_GET_CTRL_STATUS failed with: %s\n", get_error_str(str_buf, ret)); break; } printf("CAN bus statistic:\n------------------\n"); printf("Rcv frames : Std(Data/RTR): %ld/%ld Ext(Data/RTR) %ld/%ld\n", (long)stat.rcv_count.std_data, (long)stat.rcv_count.std_rtr, (long)stat.rcv_count.ext_data, (long)stat.rcv_count.ext_rtr); printf("Xmit frames : Std(Data/RTR): %ld/%ld Ext(Data/RTR) %ld/%ld\n", (long)stat.xmit_count.std_data, (long)stat.xmit_count.std_rtr, (long)stat.xmit_count.ext_data, (long)stat.xmit_count.ext_rtr); printf("Bytes : (Rcv/Xmit): %ld/%ld\n", (long)stat.rcv_byte_count, (long)stat.xmit_byte_count); printf("Overruns : (Controller/FIFO): %ld/%ld\n", (long)stat.ctrl_ovr, (long)stat.fifo_ovr); printf("Err frames : %ld\n", (long)stat.err_frames); printf("Aborted frames : %ld\n", (long)stat.aborted_frames); printf("Err counter : (Rx/Tx): %d/%d Status: %02x\n", ctrl_state.rcv_err_counter, ctrl_state.xmit_err_counter, ctrl_state.status); printf("Rcv bits : %" PRIu64 "\n", stat.bit_count); SLEEP(txtout); } break; case 74: { ret = canIoctl(h0, NTCAN_IOCTL_GET_BUS_STATISTIC, NULL); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_GET_BUS_STATISTIC (NULL) failed with: %s\n", get_error_str(str_buf, ret)); break; } printf("CAN bus statistic reset.\n"); SLEEP(txtout); } break; #endif /* of NTCAN_IOCTL_GET_BUS_STATISTIC */ #ifdef NTCAN_IOCTL_GET_BITRATE_DETAILS case 84: { NTCAN_BITRATE bitrate; long sp; ret = canIoctl(h0, NTCAN_IOCTL_GET_BITRATE_DETAILS, &bitrate); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_GET_BITRATE_DETAILS failed with: %s\n", get_error_str(str_buf, ret)); break; } printf("CAN bitrate:\n------------\n"); printf("Value set by canSetBaudrate() : 0x%08lX\n", (long)bitrate.baud); if (NTCAN_SUCCESS == bitrate.valid) { printf("Actual Bitrate : %ld Bits/s\n", (long)bitrate.rate); printf("Timequantas per Bit : %ld\n", (long)(bitrate.tq_pre_sp + bitrate.tq_post_sp)); printf("Timequantas before samplepoint : %ld\n", (long)bitrate.tq_pre_sp); printf("Timequantas after samplepoint : %ld\n", (long)bitrate.tq_post_sp); printf("Syncronization Jump Width : %ld\n", (long)bitrate.sjw); printf("Additional flags : 0x%08lX\n", (long)bitrate.flags); sp = (long)((bitrate.tq_pre_sp * 10000) / (bitrate.tq_pre_sp + bitrate.tq_post_sp)); printf("Position samplepoint : %ld.%ld%%\n", sp/100, sp%100); printf("Deviation from configured rate : %ld.%02ld%%\n", (long)(bitrate.error/100), (long)(bitrate.error%100)); printf("Controller clockrate : %ld.%ldMHz\n", (long)(bitrate.clock/1000000), (long)(bitrate.clock%1000000)); } SLEEP(txtout); } break; #endif /* NTCAN_IOCTL_GET_BITRATE_DETAILS */ /* * canSendEvent() * non-blocking send of customer specific events */ case 5: #ifndef D3X len = 1; ret = canSend(h0, (CMSG *)&evmsg, &len); #else ret = canSendEvent( h0, &evmsg ); #endif if (ret == NTCAN_SUCCESS) { printf("Event %08lx, data written: ", (long)evmsg.evid); for (j = 0; j < evmsg.len; j++) { printf("%02X ", evmsg.evdata.c[j]); } printf ("\n" ); } else { printf("Sending event returned: %s\n", get_error_str(str_buf,ret)); } SLEEP(1000); break; #if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(UNDER_RTSS) case 6: len = MAX_RX_MSG_CNT; start_time = GET_CURRENT_TIME; ret = canRead(h0, pCtx->rxmsg, &len, &overlapped); stop_time = GET_CURRENT_TIME; printf("async-Read triggered; Duration=%lu %s\n", stop_time - start_time, TIME_UNITS); printf("canRead returned %s \n", get_error_str(str_buf,ret)); if ((ret != NTCAN_SUCCESS) && (ret != NTCAN_IO_PENDING)) { break; } start_time = GET_CURRENT_TIME; ret = WaitForSingleObject(hEvent, /* event-handle */ INFINITE); /* wait indefinitely */ stop_time = GET_CURRENT_TIME; printf("WaitForSingleObject returned %s; Duration=%lu %s\n", get_error_str(str_buf,ret), stop_time-start_time, TIME_UNITS); ret = canGetOverlappedResult(h0, /* filehandle */ &overlapped, &len, /* ret cmsg-count */ FALSE); /* do not wait */ if (ret == NTCAN_SUCCESS) { printf("Len(cmsg)=%d\n", len); for (i = 0; i < len; i++) { print_cmsg(&pCtx->rxmsg[i], pCtx); } } else { printf("canOverlappedResult returned: %s\n", get_error_str(str_buf,ret)); } break; # if defined(NTCAN_IOCTL_GET_TIMESTAMP) && !defined(D3X) case 66: case 16: len = MAX_RX_MSG_CNT; start_time = GET_CURRENT_TIME; # if defined(NTCAN_FD) if(test == 66) { ret = canReadX(h0, pCtx->rxmsg_x, &len, &overlapped); } else # endif { ret = canReadT(h0, pCtx->rxmsg_t, &len, &overlapped); } stop_time = GET_CURRENT_TIME; printf("async-Read triggered; Duration=%lu %s\n", stop_time - start_time, TIME_UNITS); printf("canRead returned %s \n", get_error_str(str_buf,ret)); if ((ret != NTCAN_SUCCESS) && (ret != NTCAN_IO_PENDING)) { break; } start_time = GET_CURRENT_TIME; ret = WaitForSingleObject(hEvent, /* event-handle */ INFINITE); /* wait indefinitely */ stop_time = GET_CURRENT_TIME; printf("WaitForSingleObject returned %s; Duration=%lu %s\n", get_error_str(str_buf,ret), stop_time-start_time, TIME_UNITS); ret = canGetOverlappedResultT(h0, /* handle */ &overlapped, /* overlapped structure */ &len, /* ret cmsg-count */ FALSE); /* do not wait */ if (ret == NTCAN_SUCCESS) { printf("Len(cmsg)=%d\n", len); for (i = 0; i < len; i++) { # if defined(NTCAN_FD) if(test == 66) { print_cmsg_x(&pCtx->rxmsg_x[i], pCtx); } else # endif { print_cmsg_t(&pCtx->rxmsg_t[i], pCtx); } } } else { printf("canOverlappedResult returned: %s\n", get_error_str(str_buf,ret)); } break; # endif case 7: len = maxcount; if (!data_from_cmd) { for (i = 0; i < len; i++) { *((uint32_t*)(&pCtx->txmsg[i].data[0])) = h; } } start_time = GET_CURRENT_TIME; ret = canWrite(h0, pCtx->txmsg, &len, &overlapped); stop_time =GET_CURRENT_TIME; printf("async-Write triggered; Duration=%lu %s\n", stop_time - start_time, TIME_UNITS); printf("canWrite returned %s \n", get_error_str(str_buf,ret)); if ((ret != NTCAN_SUCCESS) && (ret != NTCAN_IO_PENDING)) { break; } start_time = GET_CURRENT_TIME; #if 1 ret = WaitForSingleObject(hEvent, /* event-handle */ INFINITE); /* wait indefinitely */ printf("WaitForSingleObject returned %s; \n", get_error_str(str_buf,ret)); ret = canGetOverlappedResult(h0, /* filehandle */ &overlapped, &len, /* ret cmsg-count */ FALSE); /* do not wait */ #else ret = canGetOverlappedResult(h0, /* filehandle */ &overlapped, &len, /* ret cmsg-count */ TRUE); /* wait */ #endif stop_time = GET_CURRENT_TIME; if (ret == NTCAN_SUCCESS) { printf("Duration=%6lu %s Can-Messages=%d \n", stop_time-start_time, TIME_UNITS, len); } else { printf("canOverlappedResult returned: %s\n", get_error_str(str_buf,ret)); } break; #endif /* of _WIN32 */ #if defined(unix) && defined(D3X) case 6: h1 = h0; /* Store handle in global variable, start of test */ printf("Async Read triggred\n"); while(1); start_time = GET_CURRENT_TIME; break; #endif /* of unix && D3X */ #ifndef D3X # ifdef NTCAN_IOCTL_TX_OBJ_SCHEDULE case 8: /* * Create auto RTR object */ len = 1; if (!data_from_cmd) *((uint32_t*)(&pCtx->txmsg[0].data[0])) = h; ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_CREATE, &pCtx->txmsg[0]); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_TX_OBJ_CREATE failed with :%s\n", get_error_str(str_buf,ret)); break; } ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_AUTOANSWER_ON, &pCtx->txmsg[0]); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_TX_OBJ_AUTOANSWER_ON failed with :%s\n", get_error_str(str_buf,ret)); break; } ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_UPDATE, &pCtx->txmsg[0]); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_TX_OBJ_UPDATE failed with :%s\n", get_error_str(str_buf,ret)); break; } SLEEP(rxtout); ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_AUTOANSWER_OFF, &pCtx->txmsg[0]); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_TX_OBJ_AUTOANSWER_OFF failed with :%s\n", get_error_str(str_buf,ret)); break; } SLEEP(rxtout); ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_DESTROY, &pCtx->txmsg[0]); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_TX_OBJ_DESTROY failed with :%s\n", get_error_str(str_buf,ret)); break; } break; # endif /* of NTCAN_IOCTL_TX_OBJ_SCHEDULE */ case 19: pCtx->mode |= NO_ASCII_OUTPUT; case 9: /* * Send RTR of len 0 and keep system time */ len = 1; pCtx->txmsg->len |= NTCAN_RTR; /* rtr */ start_time = GET_CURRENT_TIME; ret = canSend(h0, pCtx->txmsg, &len); if (ret != NTCAN_SUCCESS) { printf("canSend returned: %s\n", get_error_str(str_buf,ret)); break; } /* * Wait for reply to this remote request and keep system time */ time_1 = GET_CURRENT_TIME; len = maxcount; ret = canRead(h0, pCtx->rxmsg, &len, NULL); stop_time = GET_CURRENT_TIME; /* * Print durations and reply */ if (!(pCtx->mode & NO_ASCII_OUTPUT)) { printf("Duration=%9lu %s Duration2=%9lu %s Can-Messages=%ld \n", (unsigned long)(time_1-start_time), TIME_UNITS, (unsigned long)(stop_time-time_1), TIME_UNITS, (long)len); } if (ret == NTCAN_SUCCESS) { if (!(pCtx->mode & NO_ASCII_OUTPUT)) { for (i = 0; i < len; i++) { print_cmsg(&pCtx->rxmsg[i], pCtx); } } } else { printf("canRead returned: %s\n", get_error_str(str_buf,ret)); } break; #endif /* of !D3X */ #ifdef NTCAN_IOCTL_TX_OBJ_SCHEDULE #ifdef NTCAN_FD case 110: #endif case 100: for(j=0; j < maxcount; j ++) { #ifdef NTCAN_FD CMSG_X *cmx = &pCtx->txmsg_x[j]; #endif CMSG *cm = &pCtx->txmsg[j]; CSCHED sched; #ifdef NTCAN_FD cmx->id = j+idstart; #endif cm->id = j+idstart; #ifdef NTCAN_FD if(test == 110) { ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_CREATE_X, cmx); } else #endif { ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_CREATE, cm); } if( 0 != ret) { printf("NTCAN_IOCTL_TX_OBJ_CREATE returned 0x%x!\n", (unsigned int)ret); } if ((j & 1)==0) { sched.id = cm->id; sched.flags = NTCAN_SCHED_FLAG_INC16 | NTCAN_SCHED_FLAG_OFS6; sched.time_start= pCtx->udtTimestampFreq * (1+j); sched.time_interval = pCtx->udtTimestampFreq / 1000 * (j+4); sched.count_start = 0x1; sched.count_stop = 0x1234; ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_SCHEDULE, &sched); if(0 != ret) { printf("NTCAN_IOCTL_TX_OBJ_SCHEDULE returned 0x%x!\n", (unsigned int)ret); } } else { ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_AUTOANSWER_ON, cm); if(0 != ret) { printf("NTCAN_IOCTL_TX_OBJ_AUTOANSWER_ON returned 0x%x!\n", (unsigned int)ret); } } } ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_SCHEDULE_START, NULL); printf("NTCAN_IOCTL_TX_OBJ_SCHED_START returned 0x%x!\n", (unsigned int)ret); for(k=0; k < testcount || ever; k ++) { CSCHED sched; SLEEP(1000); for(j=0; j < maxcount; j ++) { CMSG *cm = &pCtx->txmsg[j]; #ifdef NTCAN_FD CMSG_X *cmx = &pCtx->txmsg_x[j]; #endif if ( ( k == 64 || k == 128) && (j & 1)==0 ) { if( (j & 3) == 0) { sched.id = cm->id; if( k == 64 ) { sched.flags = NTCAN_SCHED_FLAG_DIS; } else { sched.flags = NTCAN_SCHED_FLAG_EN; } ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_SCHEDULE, &sched); if( 0 != ret) { printf("NTCAN_IOCTL_TX_OBJ_SCHEDULE returned 0x%x!\n", (unsigned int)ret); } else { printf("NTCAN_IOCTL_TX_OBJ_SCHEDULE ID=0x%03lx Flags=0x%08lx!\n", (long)sched.id, (long)sched.flags ); } } } #ifndef NTCAN_FD *((int32_t *)&cm->data[0]) +=(j+1); #else *((int32_t *)&cmx->data[0]) +=(j+1); if(test == 110) { ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_UPDATE_X, cmx); } else #endif { ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_UPDATE, cm); } if( 0 != ret) { printf("NTCAN_IOCTL_TX_OBJ_UPDATE returned 0x%x!\n", (unsigned int)ret); } } } ret = canIoctl(h0, NTCAN_IOCTL_TX_OBJ_SCHEDULE_STOP, NULL); printf("NTCAN_IOCTL_TX_OBJ_SCHED_STOP returned 0x%x\n", (unsigned int)ret); SLEEP(1000); testcount = 0; ever = 0; break; #endif /* of NTCAN_IOCTL_TX_OBJ_SCHEDULE */ default: printf("Undefined Test!\n"); ret=canClose(h0); if (ret != NTCAN_SUCCESS) { printf("canClose returned: %s\n", get_error_str(str_buf,ret)); } CANTEST_FREE(pCtx); return(-1); } /* of switch */ /* If we return with NTCAN_NO_ID_ENABLED stop testing */ if(NTCAN_NO_ID_ENABLED == ret) break; } /* of for */ stop_test_time = GET_CURRENT_TIME; /* * To prevent that pending Tx messages are discarded by the driver if * a non-blocking test is executed and the driver does not support a * delayed close we wait the configured Tx timeout before closing the handle */ if((0 == test) && (NTCAN_SUCCESS == ret)) { SLEEP(txtout); } #ifdef NTCAN_IOCTL_SET_BUSLOAD_INTERVAL /* Stop the busload event */ if(bl_event_period != 0) { bl_event_period = 0; ret = canIoctl(h0, NTCAN_IOCTL_SET_BUSLOAD_INTERVAL, &bl_event_period); if (ret != NTCAN_SUCCESS) { printf("NTCAN_IOCTL_SET_BUSLOAD_INTERVAL failed with: %s\n", get_error_str(str_buf, ret)); } } #endif /* * Close the CAN handle */ ret = canClose(h0); if (ret != NTCAN_SUCCESS) { printf("canClose returned: %s\n", get_error_str(str_buf,ret)); } printf("Test-Duration=%lu %s \n", (unsigned long)(stop_test_time-start_test_time), TIME_UNITS); #if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(UNDER_RTSS) /* Close the event handle of Win32 overlapped tests */ if(hEvent != NULL) CloseHandle(hEvent); #endif /* Free allocated memory */ CANTEST_FREE(pCtx); return((NTCAN_SUCCESS == ret) ? 0 : -1); } /************************************************************************/ /************************************************************************/ /* Function: help() */ /* Print usage and number of available CAN devices */ /************************************************************************/ /************************************************************************/ #ifndef D3X static void help(int testnr) { NTCAN_RESULT ret; int i; int fwUpdateRequired = 0; NTCAN_HANDLE h0; CAN_IF_STATUS cstat; int8_t str_buf[100]; uint32_t baudrate; uint32_t features; uint32_t ulSerial = 0; char cBuffer[16]; char boardid[48]; uint16_t fw2 = 0; #ifdef NTCAN_IOCTL_GET_TIMESTAMP uint64_t udtTimestampFreq; uint64_t ullLastTime; #endif /* ifdef NTCAN_IOCTL_GET_TIMESTAMP */ #ifdef NTCAN_IOCTL_GET_BITRATE_DETAILS NTCAN_BITRATE bitrate; #endif /* ifdef NTCAN_IOCTL_GET_BITRATE_DETAILS */ #ifdef NTCAN_IOCTL_GET_INFO NTCAN_INFO info; #endif /* ifdef NTCAN_IOCTL_GET_INFO */ printf("CAN Test Rev %d.%d.%d -- (c) 1997-2015 esd electronic system design gmbh\n\n", LEVEL, REVISION, CHANGE); printf("Available CAN-Devices: \n"); for (i = 0; i <= NTCAN_MAX_NETS; i++) { ret = canOpen(i, 0, 1, 1, 0, 0, &h0); if (ret == NTCAN_SUCCESS) { ret = canStatus(h0, &cstat); if (ret != NTCAN_SUCCESS) { printf("Cannot get Status of Net-Device %02X (ret = 0x%x)\n", i, (unsigned int)ret); } else { features = (uint32_t)cstat.features; strncpy(boardid, (const char *)cstat.boardid, sizeof(boardid)); #ifdef NTCAN_IOCTL_GET_INFO memset(&info, 0, sizeof(info)); ret = canIoctl(h0, NTCAN_IOCTL_GET_INFO, &info); if(NTCAN_SUCCESS == ret) { features = info.features; fw2 = info.firmware2; sprintf(boardid, "%s (%d ports)", cstat.boardid, info.ports); } #endif baudrate = NTCAN_NO_BAUDRATE; ret = canGetBaudrate(h0, &baudrate); if(NTCAN_INVALID_FIRMWARE == ret) { fwUpdateRequired = 1; ret = NTCAN_SUCCESS; } if (ret != NTCAN_SUCCESS) { printf("Cannot get Baudrate of Net-Device %02X (ret: 0x%x)\n", i, (unsigned int)ret); } else { #ifdef NTCAN_IOCTL_GET_BITRATE_DETAILS bitrate.valid = 0; ret = canIoctl(h0, NTCAN_IOCTL_GET_BITRATE_DETAILS, &bitrate); if (ret != NTCAN_SUCCESS) { bitrate.valid = NTCAN_INVALID_PARAMETER; } #endif /* ifdef NTCAN_IOCTL_GET_BITRATE_DETAILS */ /* * Get the serial number. */ #ifdef NTCAN_IOCTL_GET_SERIAL ret = canIoctl(h0, NTCAN_IOCTL_GET_SERIAL, &ulSerial); if(ret != NTCAN_SUCCESS) { ulSerial = 0; } #endif /* ifdef NTCAN_IOCTL_GET_SERIAL */ if(0 == ulSerial) { sprintf(cBuffer,"N/A"); } else { sprintf(cBuffer, "%c%c%06ld", (char)('A' + (ulSerial >> 28 & 0xF)), (char)('A' + (ulSerial >> 24 & 0xF)), (long)(ulSerial & 0xFFFFFF)); } #ifdef NTCAN_IOCTL_GET_INFO if(info.serial_string[0] != '\0') { strncpy(cBuffer, info.serial_string, sizeof(cBuffer)); } #endif /* of NTCAN_IOCTL_GET_INFO */ printf("Net %3d: ID=%s Serial no.: %s\n" " Versions (hex): Lib=%1X.%1X.%02X" " Drv=%1X.%1X.%02X" " HW=%1X.%1X.%02X" " FW=%1X.%1X.%02X (%1X.%1X.%02X)\n", i, boardid, cBuffer, cstat.dll >>12, (cstat.dll >>8) & 0xf, cstat.dll & 0xff, cstat.driver >>12, (cstat.driver >>8) & 0xf, cstat.driver & 0xff, cstat.hardware>>12, (cstat.hardware>>8) & 0xf, cstat.hardware & 0xff, cstat.firmware>>12, (cstat.firmware>>8) & 0xf, cstat.firmware & 0xff, fw2 >> 12, fw2 >> 8, fw2 & 0xff); #if defined (NTCAN_IOCTL_GET_INFO) if (-3 == testnr) { if(info.drv_build_info[0] != '\0') { printf(" Drv build: %s\n", info.drv_build_info); } if(info.lib_build_info[0] != '\0') { printf(" Lib build: %s\n", info.lib_build_info); } } #endif /* NTCAN_IOCTL_GET_INFO */ printf(" Baudrate=%08lx", (unsigned long)baudrate); #ifdef NTCAN_IOCTL_GET_BITRATE_DETAILS if(NTCAN_SUCCESS == bitrate.valid) { printf(" (%d KBit/s", (int)(bitrate.rate / 1000)); if(bitrate.baud & NTCAN_LISTEN_ONLY_MODE) { printf(", LOM"); } printf(")"); } else if(NTCAN_NO_BAUDRATE == bitrate.baud) { printf(" (Not set)"); } #endif /* ifdef NTCAN_IOCTL_GET_BITRATE_DETAILS */ printf(" Status=%04x Features=%08x\n", #ifdef NTCAN_GET_BOARD_STATUS (unsigned int)NTCAN_GET_BOARD_STATUS(cstat.boardstatus), #else /* ifdef NTCAN_GET_BOARD_STATUS */ (unsigned int)cstat.boardstatus, #endif /* ifdef NTCAN_GET_BOARD_STATUS */ (unsigned int)features); } /* of if (ret != NTCAN_SUCCESS) */ /* Decode feature flags */ if (-3 == testnr) { printf( " %c CAN 2.0B support %c Rx Object Mode %c Timestamp support\n" " %c Listen Only Mode %c Smart Disconnect %c Local Echo\n" " %c Smart ID filter %c Tx Scheduling %c Enhanced Bus Diagnostic\n" " %c Error Injection %c IRIG-B Support %c PXI Support\n" " %c CAN-FD support %c Self Test Mode", features & NTCAN_FEATURE_CAN_20B ? '+' : '-', features & NTCAN_FEATURE_RX_OBJECT_MODE ? '+' : '-', features & NTCAN_FEATURE_TIMESTAMP ? '+' : '-', features & NTCAN_FEATURE_LISTEN_ONLY_MODE ? '+' : '-', features & NTCAN_FEATURE_SMART_DISCONNECT ? '+' : '-', features & NTCAN_FEATURE_LOCAL_ECHO ? '+' : '-', features & NTCAN_FEATURE_SMART_ID_FILTER ? '+' : '-', features & NTCAN_FEATURE_SCHEDULING ? '+' : '-', features & NTCAN_FEATURE_DIAGNOSTIC ? '+' : '-', features & NTCAN_FEATURE_ERROR_INJECTION ? '+' : '-', features & NTCAN_FEATURE_IRIGB ? '+' : '-', features & NTCAN_FEATURE_PXI ? '+' : '-', features & NTCAN_FEATURE_CAN_FD ? '+' : '-', features & NTCAN_FEATURE_SELF_TEST ? '+' : '-'); if(cstat.driver > 0x3000) { printf(" %c Timestamped Tx\n", features & NTCAN_FEATURE_TIMESTAMPED_TX ? '+' : '-'); } else { printf(" %c Cyclic Tx\n", features & NTCAN_FEATURE_TIMESTAMPED_TX ? '+' : '-'); } } #ifdef NTCAN_GET_CTRL_TYPE printf(" Ctrl="); switch(NTCAN_GET_CTRL_TYPE(cstat.boardstatus)) { case NTCAN_CANCTL_SJA1000: printf("NXP SJA1000"); break; case NTCAN_CANCTL_I82527: printf("Intel C527"); break; case NTCAN_CANCTL_FUJI: printf("Fujitsu MBxxxxx MCU"); break; case NTCAN_CANCTL_LPC: printf("NXP LPC2xxx MCU"); break; case NTCAN_CANCTL_MSCAN: printf("Freescale MCU"); break; case NTCAN_CANCTL_ATSAM: printf("Atmel ARM MCU"); break; case NTCAN_CANCTL_ESDACC: printf("esd Advanced CAN Core"); break; case NTCAN_CANCTL_STM32: printf("ST STM32Fxx MCU"); break; case NTCAN_CANCTL_CC770: printf("Bosch CC770"); break; case NTCAN_CANCTL_SPEAR: printf("ST SPEAr320 MCU"); break; case NTCAN_CANCTL_FLEXCAN: printf("Freescale iMX MCU"); break; case NTCAN_CANCTL_SITARA: printf("TI AM335x (Sitara) MCU"); break; default: printf("Unknown (0x%02x)", (unsigned int)NTCAN_GET_CTRL_TYPE(cstat.boardstatus)); } #ifdef NTCAN_IOCTL_GET_BITRATE_DETAILS if(bitrate.valid != NTCAN_INVALID_PARAMETER) { printf(" @ %d MHz", (int)(bitrate.clock / 1000000)); } #endif /* ifdef NTCAN_IOCTL_GET_BITRATE_DETAILS */ if(features & NTCAN_FEATURE_FULL_CAN) { printf(" -- FullCAN"); } #ifdef NTCAN_IOCTL_GET_CTRL_STATUS { NTCAN_CTRL_STATE ctrl_state; ret = canIoctl(h0, NTCAN_IOCTL_GET_CTRL_STATUS, &ctrl_state); if (NTCAN_SUCCESS == ret) { printf(" ("); switch(ctrl_state.status) { case 0x00: printf("Error Active"); break; case 0x40: printf("Error Warn"); break; case 0x80: printf("Error Passive"); break; case 0xC0: printf("Bus-Off"); break; default: printf("Unknown"); break; } printf(" / REC:%d / TEC:%d)", ctrl_state.rcv_err_counter, ctrl_state.xmit_err_counter); } } #endif /* ifdef NTCAN_IOCTL_GET_CTRL_STATUS */ printf("\n"); #endif /* ifdef NTCAN_GET_CTRL_TYPE */ #if defined (NTCAN_IOCTL_GET_INFO) printf(" Transceiver="); switch(info.transceiver) { case NTCAN_TRX_PCA82C251: printf("NXP PCA82C251"); break; case NTCAN_TRX_SN65HVD251: printf("TI SN65HVD251"); break; case NTCAN_TRX_SN65HVD265: printf("TI SN65HVD265"); break; default: printf("Unknown (0x%02x)", info.transceiver); } printf("\n"); #endif #ifdef NTCAN_IOCTL_GET_TIMESTAMP /* * Print timestamp frequency and current timestamp if supported */ if(0 == get_timestamp_freq(h0, &udtTimestampFreq, 0)) { ret = canIoctl(h0, NTCAN_IOCTL_GET_TIMESTAMP, &ullLastTime); printf(" TimestampFreq=%ld.%06ld MHz", (unsigned long)(udtTimestampFreq / 1000000), (unsigned long)(udtTimestampFreq % 1000000)); if (NTCAN_SUCCESS == ret) { printf(" Timestamp=%08lX%08lX", (unsigned long)((ullLastTime >> 32) & 0xFFFFFFFF), (unsigned long)(ullLastTime & 0xFFFFFFFF)); } printf("\n"); } /* Indicate a required FW update */ if(fwUpdateRequired != 0) { printf("\n ----> !!!! THIS BOARD REQUIRES A FW UPDATE !!!! <----\n\n"); } #endif /* ifdef NTCAN_IOCTL_GET_TIMESTAMP */ } canClose(h0); } else if(ret != NTCAN_NET_NOT_FOUND) { /* Error-code sanity check */ printf("Net %3d: Opening device returned with error %s\n", i, get_error_str(str_buf,ret)); } } if (testnr <= -4) { printf("\n"); printf(" |======================================================================|\n"); printf(" | Bitrate (KBit/s) | 1000 | 800 | 500 | 250 | 125 | 100 | 50 | 20 | 10 |\n"); printf(" |------------------+------+-----+-----+-----+-----+-----+----+----+----|\n"); printf(" | Index | 0 | 14 | 2 | 4 | 6 | 7 | 9 | 11 | 13 |\n"); printf(" |======================================================================|\n"); } if (testnr <= -2) return; #if defined(VXWORKS) printf("\nSyntax: canTest test-Nr " #else /* defined(VXWORKS) */ printf("\nSyntax: cantest test-Nr " #endif /* defined(VXWORKS) */ "[net id-1st id-last count\n" " txbuf rxbuf txtout rxtout baud testcount data0 data1 ...]\n"); printf("Test 0: canSend()\n"); #if defined(NTCAN_IOCTL_GET_TX_TS_WIN) printf("Test 20: canSendT()\n"); #endif /* defined(NTCAN_IOCTL_GET_TX_TS_WIN) */ printf("Test 50: canSend() with incrementing ids\n"); #if defined(NTCAN_FD) printf("Test 60: canSendX()\n"); #endif /* defined(NTCAN_FD) */ printf("Test 1: canWrite()\n"); #if defined(NTCAN_IOCTL_GET_TX_TS_WIN) printf("Test 21: canWriteT()\n"); #endif /* defined(NTCAN_IOCTL_GET_TX_TS_WIN) */ #ifdef RMOS printf("Test 21: canWrite() fifo SLOW\n"); printf("Test 31: canWrite() fifo FAST\n"); printf("Test 41: canWrite() fifo BURST\n"); #endif /* ifdef RMOS */ printf("Test 51: canWrite() with incrementing ids\n"); #if defined(NTCAN_FD) printf("Test 61: canWriteX()\n"); #endif /* defined(NTCAN_FD) */ printf("Test 2: canTake()\n"); printf("Test 12: canTake() with time-measurement for 10000 can-frames\n"); #ifdef NTCAN_IOCTL_GET_TIMESTAMP printf("Test 22: canTakeT()\n"); #endif /* ifdef NTCAN_IOCTL_GET_TIMESTAMP */ printf("Test 32: canTake() in Object-Mode\n"); #ifdef NTCAN_IOCTL_GET_TIMESTAMP printf("Test 42: canTakeT() in Object-Mode\n"); #endif /* ifdef NTCAN_IOCTL_GET_TIMESTAMP */ #if defined(NTCAN_FD) printf("Test 62: canTakeX()\n"); printf("Test 72: canTakeX() with time-measurement for 10000 can-frames\n"); printf("Test 82: canTakeX() in Object-Mode\n"); #endif /* defined(NTCAN_FD) */ printf("Test 3: canRead()\n"); printf("Test 13: canRead() with time-measurement for 10000 can-frames\n"); #ifdef NTCAN_IOCTL_GET_TIMESTAMP printf("Test 23: canReadT()\n"); #endif /* ifdef NTCAN_IOCTL_GET_TIMESTAMP */ #if defined(NTCAN_FD) printf("Test 63: canReadX()\n"); printf("Test 73: canReadX() with time-measurement for 10000 can-frames\n"); #endif /* defined(NTCAN_FD) */ printf("Test 4: canReadEvent()\n"); #if defined(NTCAN_IOCTL_GET_BUS_STATISTIC) && !defined(D3X) printf("Test 64: Retrieve bus statistics (every tx timeout)\n"); printf("Test 74: Reset bus statistics\n"); #endif /* if defined(NTCAN_IOCTL_GET_BUS_STATISTIC) && !defined(D3X) */ #if defined(NTCAN_IOCTL_GET_BITRATE_DETAILS) && !defined(D3X) printf("Test 84: Retrieve bitrate details (every tx timeout)\n"); #endif /* if defined(NTCAN_IOCTL_GET_BITRATE_DETAILS) && !defined(D3X) */ printf("Test 5: canSendEvent()\n"); #if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(UNDER_RTSS) printf("Test 6: Overlapped-canRead()\n"); # if defined(NTCAN_IOCTL_GET_TIMESTAMP) && !defined(D3X) printf("Test 16: Overlapped-canReadT()\n"); # if defined(NTCAN_FD) printf("Test 66: Overlapped-canReadX()\n"); # endif # endif /* if defined(NTCAN_IOCTL_GET_TIMESTAMP) && !defined(D3X) */ printf("Test 7: Overlapped-canWrite()\n"); #endif /* if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(UNDER_RTSS) */ #if defined(unix) && defined(D3X) printf("Test 6: Async canRead()\n"); #endif /* if defined(unix) && defined(D3X) */ #ifndef D3X # ifdef NTCAN_IOCTL_TX_OBJ_SCHEDULE printf("Test 8: Create auto RTR object\n"); # endif /* ifdef NTCAN_IOCTL_TX_OBJ_SCHEDULE */ printf("Test 9: Wait for RTR reply\n"); printf("Test 19: Wait for RTR reply without text-output\n"); # ifdef NTCAN_IOCTL_TX_OBJ_SCHEDULE printf("Test 100: Object Scheduling test\n"); # if defined(NTCAN_FD) printf("Test 110: Object Scheduling test with cmsg_x\n"); # endif # endif #endif /* ifndef D3X */ printf("Test -2: Overview without syntax help\n"); printf("Test -3: Overview without syntax help but with feature flags details\n"); } #else static void help(int testnr) { NTCAN_RESULT ret; int i; NTCAN_HANDLE h0; CAN_IF_STATUS cstat; int8_t str_buf[100]; printf("CAN Test Rev %d.%d.%d -- (c) 1997-2013 esd electronic system design gmbh\n\n", LEVEL, REVISION, CHANGE); printf("Available CAN-Devices: \n"); for (i = 0; i <= NTCAN_MAX_NETS; i++) { ret = canOpen(i, 0, 1, 1, 0, 0, &h0); if (ret == NTCAN_SUCCESS) { ret = canStatus(h0, &cstat); if (ret != NTCAN_SUCCESS) { printf("Cannot get Status of Net-Device %02X (ret = %d)\n", i, ret); } else { printf("Net %3d: ID=%s\n" " Versions (hex): Dll=%1X.%1X.%02X " " Drv=%1X.%1X.%02X" " FW=%1X.%1X.%02X" " HW=%1X.%1X.%02X\n" " Status=%08x\n", i, cstat.boardid, cstat.dll >>12, (cstat.dll >>8) & 0xf, cstat.dll & 0xff, cstat.driver >>12, (cstat.driver >>8) & 0xf, cstat.driver & 0xff, cstat.firmware>>12, (cstat.firmware>>8) & 0xf, cstat.firmware & 0xff, cstat.hardware>>12, (cstat.hardware>>8) & 0xf, cstat.hardware & 0xff, (unsigned long)cstat.boardstatus); } canClose(h0); } else if(ret != NTCAN_NET_NOT_FOUND) { /* Error-code sanity check */ printf("Net %3d: Opening device returned with error %s\n", i, get_error_str(str_buf,ret)); } } if (testnr <= -2) return; printf("\nSyntax: d3xtest test-Nr " "[net id-1st id-last count\n" " txbuf rxbuf txtout rxtout baud testcount data0 data1 ...]\n"); printf("Test 1: canWrite()\n"); printf("Test 3: canRead()\n"); printf("Test 4: canReadEvent()\n"); printf("Test 5: canSendEvent()\n"); #if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(UNDER_RTSS) printf("Test 6: Overlapped-canRead()\n"); printf("Test 7: Overlapped-canWrite()\n"); #endif /* of _WIN32 && !_WIN32_WCE && !UNDER_RTSS */ #if defined(unix) printf("Test 6: Async canRead()\n"); #endif /* of unix */ } #endif /* of ! defined D3X */ /************************************************************************/ /************************************************************************/ /* Function: set_can_id() */ /* Boilerplate code to enable a single ID of the CAN handle filter */ /************************************************************************/ /************************************************************************/ static NTCAN_RESULT set_can_id(NTCAN_HANDLE handle, int32_t id) { int i; NTCAN_RESULT ret = NTCAN_SUCCESS; /* * For some active CAN hardware old driver implementations might return * NTCAN_INSUFFICIENT_RESOURCES if the communication FIFO of the device * is full and can not accept further requests because the host performs * consecutive calls of canIdAdd()/canIdDelete much faster than it can be * processed by the CAN hardware. * * All current driver can handle this situation internally more efficient * so this boileplate code around canIdAdd(), which waits several ms in this * situation, isn't usually necessary in a user's application. */ for (i = 0; i < 2; i++) { ret = canIdAdd(handle, id); if (NTCAN_INSUFFICIENT_RESOURCES == ret) { SLEEP(100); continue; } break; } return ret; } /************************************************************************/ /************************************************************************/ /* Function: get_timestamp_freq() */ /* Boilerplate code to check if driver/device supports timestamps and */ /* to request the frequency of the timestamp counter. */ /* Returns 0 on success -1 otherwise */ /************************************************************************/ /************************************************************************/ #ifdef NTCAN_IOCTL_GET_TIMESTAMP static int get_timestamp_freq(NTCAN_HANDLE handle, uint64_t *pFreq, int verbose) { CAN_IF_STATUS cstat; NTCAN_RESULT ret; int8_t str_buf[100]; /* Check for timestamp support */ ret = canStatus(handle, &cstat); if ((ret != NTCAN_SUCCESS) || (0 == (cstat.features & NTCAN_FEATURE_TIMESTAMP))) { if(verbose != 0) printf("Driver/Hardware does not support timestamps\n"); return(-1); } /* Read timestamp frequency */ ret = canIoctl(handle, NTCAN_IOCTL_GET_TIMESTAMP_FREQ, pFreq); if (ret != NTCAN_SUCCESS) { if(verbose != 0) printf("canIoctl returned: %s\n", get_error_str(str_buf, ret)); return(-1); } if(verbose != 0) printf("TimestampFreq=%" PRId64 " Hz\n", *pFreq); return(0); } #endif /* of NTCAN_IOCTL_GET_TIMESTAMP */ /************************************************************************/ /************************************************************************/ /* Function: get_error_str() */ /* Return ASCII representation of NTCAN return code */ /************************************************************************/ /************************************************************************/ static int8_t *get_error_str(int8_t *str_buf, NTCAN_RESULT ntstatus) { struct ERR2STR { NTCAN_RESULT ntstatus; const char *str; }; static const struct ERR2STR err2str[] = { { NTCAN_SUCCESS , "NTCAN_SUCCESS" }, { NTCAN_RX_TIMEOUT , "NTCAN_RX_TIMEOUT" }, { NTCAN_TX_TIMEOUT , "NTCAN_TX_TIMEOUT" }, { NTCAN_TX_ERROR , "NTCAN_TX_ERROR" }, { NTCAN_CONTR_OFF_BUS , "NTCAN_CONTR_OFF_BUS" }, { NTCAN_CONTR_BUSY , "NTCAN_CONTR_BUSY" }, { NTCAN_CONTR_WARN , "NTCAN_CONTR_WARN" }, { NTCAN_NO_ID_ENABLED , "NTCAN_NO_ID_ENABLED" }, { NTCAN_ID_ALREADY_ENABLED , "NTCAN_ID_ALREADY_ENABLED" }, { NTCAN_ID_NOT_ENABLED , "NTCAN_ID_NOT_ENABLED" }, { NTCAN_INVALID_FIRMWARE , "NTCAN_INVALID_FIRMWARE" }, { NTCAN_MESSAGE_LOST , "NTCAN_MESSAGE_LOST" }, { NTCAN_INVALID_PARAMETER , "NTCAN_INVALID_PARAMETER" }, { NTCAN_INVALID_HANDLE , "NTCAN_INVALID_HANDLE" }, { NTCAN_NET_NOT_FOUND , "NTCAN_NET_NOT_FOUND" }, #ifdef NTCAN_IO_INCOMPLETE { NTCAN_IO_INCOMPLETE , "NTCAN_IO_INCOMPLETE" }, #endif #ifdef NTCAN_IO_PENDING { NTCAN_IO_PENDING , "NTCAN_IO_PENDING" }, #endif #ifdef NTCAN_INVALID_HARDWARE { NTCAN_INVALID_HARDWARE , "NTCAN_INVALID_HARDWARE" }, #endif #ifdef NTCAN_PENDING_WRITE { NTCAN_PENDING_WRITE , "NTCAN_PENDING_WRITE" }, #endif #ifdef NTCAN_PENDING_READ { NTCAN_PENDING_READ , "NTCAN_PENDING_READ" }, #endif #ifdef NTCAN_INVALID_DRIVER { NTCAN_INVALID_DRIVER , "NTCAN_INVALID_DRIVER" }, #endif #ifdef NTCAN_OPERATION_ABORTED { NTCAN_OPERATION_ABORTED , "NTCAN_OPERATION_ABORTED" }, #endif #ifdef NTCAN_WRONG_DEVICE_STATE { NTCAN_WRONG_DEVICE_STATE , "NTCAN_WRONG_DEVICE_STATE" }, #endif { NTCAN_INSUFFICIENT_RESOURCES, "NTCAN_INSUFFICIENT_RESOURCES"}, #ifdef NTCAN_HANDLE_FORCED_CLOSE { NTCAN_HANDLE_FORCED_CLOSE, "NTCAN_HANDLE_FORCED_CLOSE" }, #endif #ifdef NTCAN_NOT_IMPLEMENTED { NTCAN_NOT_IMPLEMENTED , "NTCAN_NOT_IMPLEMENTED" }, #endif #ifdef NTCAN_NOT_SUPPORTED { NTCAN_NOT_SUPPORTED , "NTCAN_NOT_SUPPORTED" }, #endif #ifdef NTCAN_SOCK_CONN_TIMEOUT { NTCAN_SOCK_CONN_TIMEOUT , "NTCAN_SOCK_CONN_TIMEOUT" }, #endif #ifdef NTCAN_SOCK_CMD_TIMEOUT { NTCAN_SOCK_CMD_TIMEOUT , "NTCAN_SOCK_CMD_TIMEOUT" }, #endif #ifdef NTCAN_SOCK_HOST_NOT_FOUND { NTCAN_SOCK_HOST_NOT_FOUND, "NTCAN_SOCK_HOST_NOT_FOUND" }, #endif #ifdef NTCAN_CONTR_ERR_PASSIVE { NTCAN_CONTR_ERR_PASSIVE , "NTCAN_CONTR_ERR_PASSIVE" }, #endif #ifdef NTCAN_ERROR_NO_BAUDRATE { NTCAN_ERROR_NO_BAUDRATE , "NTCAN_ERROR_NO_BAUDRATE" }, #endif #ifdef NTCAN_ERROR_LOM { NTCAN_ERROR_LOM , "NTCAN_ERROR_LOM" }, #endif { (NTCAN_RESULT)0xffffffff , "NTCAN_UNKNOWN" } /* stop-mark */ }; const struct ERR2STR *es = err2str; do { if (es->ntstatus == ntstatus) { break; } es++; } while((uint32_t)es->ntstatus != 0xffffffff); #ifdef NTCAN_ERROR_FORMAT_LONG { NTCAN_RESULT res; char szErrorText[60]; res = canFormatError(ntstatus, NTCAN_ERROR_FORMAT_LONG, szErrorText, sizeof(szErrorText) - 1); if(NTCAN_SUCCESS == res) { sprintf((char *)str_buf, "%s - %s", es->str, szErrorText); } else { sprintf((char *)str_buf, "%s(0x%08x)", es->str, (unsigned int)ntstatus); } } #else sprintf((char *)str_buf, "%s(0x%08x)", es->str, ntstatus); #endif /* of NTCAN_ERROR_FORMAT_LONG */ return str_buf; } /************************************************************************/ /************************************************************************/ /* Function: print_event() */ /* Print interpreted version of a CAN event */ /************************************************************************/ /************************************************************************/ static void print_event(EVMSG *e, uint64_t ts, CANTEST_CTX *pCtx) { if(NTCAN_EV_CAN_ERROR == e->evid) { printf(" CAN controller state: "); switch(e->evdata.error.can_status) { case 0x00: printf("OK"); break; case 0x40: printf("WARN"); break; case 0x80: printf("ERROR PASSIVE"); break; case 0xC0: printf("BUS-OFF"); break; default: printf("UNKNOWN State ?!?"); break; } printf(" - Lost messages (Ctrl: %d, Driver: %d)\n", e->evdata.error.ctrl_overrun, e->evdata.error.fifo_overrun); } #if defined NTCAN_EV_BAUD_CHANGE else if (e->evid == NTCAN_EV_BAUD_CHANGE) { if(NTCAN_NO_BAUDRATE == (uint32_t)e->evdata.baud_change.baud) { printf(" CAN controller removed from bus\n"); } #ifdef NTCAN_AUTOBAUD else if(NTCAN_AUTOBAUD == (uint32_t)e->evdata.baud_change.baud) { printf(" CAN controller changes in auto baudrate detection\n"); } #endif else { printf(" New baudrate : 0x%08lX", (unsigned long)e->evdata.baud_change.baud); if ( 4 < e->len ) { printf(" (%ld baud)", (unsigned long)e->evdata.baud_change.num_baud); num_baudrate = e->evdata.baud_change.num_baud; } #ifdef NTCAN_LISTEN_ONLY_MODE if(((uint32_t)e->evdata.baud_change.baud & NTCAN_LISTEN_ONLY_MODE) != 0) { printf(" Listen only enabled"); } else { printf(" Listen only disabled"); } #endif printf("\n"); } } # if defined NTCAN_EV_BUSLOAD && defined NTCAN_IOCTL_GET_TIMESTAMP else if (NTCAN_EV_BUSLOAD == e->evid) { static EVMSG e_last; static uint64_t last_bl_ts; /* Timestamp of last busload event */ if (0 == ts) { printf(" Busload-Error! ts?\n"); } else if (0 == last_bl_ts) { printf(" First Busload event\n"); } else if (0 == num_baudrate) { printf(" Busload-Error! baud?\n"); } else if (((int64_t)(ts-last_bl_ts))<=0) { /* prevent division by zero */ printf(" Busload-Error! ts_last>=ts"); } else { unsigned int can_load; uint64_t dbits; dbits = e->evdata.q; dbits -= e_last.evdata.q; dbits *= pCtx->udtTimestampFreq; dbits *= 100; /* for percentage */ can_load = (unsigned int)(dbits/(ts-last_bl_ts)); can_load /= num_baudrate; printf(" Busload %u%%\n", (can_load > 100) ? 100 : can_load); } last_bl_ts=ts; e_last=*e; } # endif /* of NTCAN_EV_BUSLOAD */ #endif /* of NTCAN_EV_BAUD_CHANGE */ #if defined NTCAN_EV_CAN_ERROR_EXT && defined NTCAN_FORMATEVENT_SHORT else if(NTCAN_EV_CAN_ERROR_EXT == e->evid) { NTCAN_RESULT result = NTCAN_NOT_IMPLEMENTED; NTCAN_FORMATEVENT_PARAMS ev; char buffer[80]; memset(&ev, 0, sizeof(ev)); ev.ctrl_type = pCtx->ctrl_type; result = canFormatEvent(e,&ev,buffer,sizeof(buffer)); if(NTCAN_SUCCESS == result){ printf(" %s\n", buffer); } } #endif /* of NTCAN_EV_CAN_ERROR_EXT */ return; } /************************************************************************/ /************************************************************************/ /* Function: print_cmsg() */ /* Print a formatted CAN message to stdout if NO_ASCII_OUTPUT flag is */ /* not set */ /************************************************************************/ /************************************************************************/ static void print_cmsg(CMSG *pCmsg, CANTEST_CTX *pCtx) { int j, c; if(pCtx->mode & NTCAN_MODE_OBJECT) { if (pCmsg->len & NTCAN_NO_DATA) { printf("RX-ID=%9ld (0x%08lx) NO DATA\n", (unsigned long)pCmsg->id, (unsigned long)pCmsg->id); } else if (pCmsg->len & NTCAN_RTR) { printf("RX-RTR-ID=%9ld (0x%08lx) len=%02X\n", (unsigned long)pCmsg->id, (unsigned long)pCmsg->id, pCmsg->len & 0x0f ); } else { pCmsg->len &= 0x0f; printf("RX-ID=%9ld (0x%08lx) len=%02X data= ", (unsigned long)pCmsg->id, (unsigned long)pCmsg->id, pCmsg->len ); if(pCmsg->len > 8) pCmsg->len = 8; for (j = 0; j < pCmsg->len; j++) { printf("%02X ", pCmsg->data[j]); } for (j = pCmsg->len; j < 8; j++) { printf(" "); } printf(" ["); { for (j = 0; j < pCmsg->len; j++) { c = pCmsg->data[j]; printf("%c", c > 31 && c < 128 ? c : '.' ); } for (j = pCmsg->len; j < 8; j++) { printf(" "); } } printf("]\n"); } } else { /* Check for lost messages */ if (pCmsg->msg_lost != 0) { printf("%02x Messages lost !\n", pCmsg->msg_lost); } /* Return if console output is disabled */ if ((pCtx->mode & NO_ASCII_OUTPUT)) return; /* Mark interaction messages */ if (pCmsg->len & NTCAN_INTERACTION) { printf("*"); } if (pCmsg->len & NTCAN_RTR) { printf("RX-RTR-ID=%9ld (0x%08lx) len=%02X\n", (unsigned long)pCmsg->id, (unsigned long)pCmsg->id, pCmsg->len & 0x0f ); } else { pCmsg->len &= 0x0f; printf("RX-ID=%9ld (0x%08lx) len=%02X data= ", (unsigned long)pCmsg->id, (unsigned long)pCmsg->id, pCmsg->len ); if(pCmsg->len > 8) pCmsg->len = 8; for (j = 0; j < pCmsg->len; j++) { printf("%02X ", pCmsg->data[j]); } for (j = pCmsg->len; j < 8; j++) { printf(" "); } printf(" ["); { for (j = 0; j < pCmsg->len; j++) { c = pCmsg->data[j]; printf("%c", c > 31 && c < 128 ? c : '.' ); } for (j = pCmsg->len; j < 8; j++) { printf(" "); } } printf("]\n"); } /* Decode events */ if((pCmsg->id & NTCAN_EV_BASE) != 0) { print_event((EVMSG *)pCmsg, 0, pCtx); } } return; } /************************************************************************/ /************************************************************************/ /* Function: print_cmsg_t() */ /* Print a formatted timestamped CAN message to stdout if */ /* NO_ASCII_OUTPUT flag is not set */ /************************************************************************/ /************************************************************************/ #ifdef NTCAN_IOCTL_GET_TIMESTAMP static void print_cmsg_t(CMSG_T *pCmsgT, CANTEST_CTX *pCtx) { int j; uint32_t ulTimeDiff = 0; if(pCtx->mode & NTCAN_MODE_OBJECT) { pCtx->ullLastTime = pCmsgT->timestamp; if (pCmsgT->len & NTCAN_NO_DATA) { printf("RX-ID= %4ld (0x%03lx) - %016" PRIx64 " - NO DATA\n", (unsigned long)pCmsgT->id, (unsigned long)pCmsgT->id, pCtx->ullLastTime); } else if (pCmsgT->len & NTCAN_RTR) { printf("RTR-ID=%4ld (0x%03lx) - %016" PRIx64 " - len=%02X\n", (unsigned long)pCmsgT->id, (unsigned long)pCmsgT->id, pCtx->ullLastTime, pCmsgT->len & 0x0f); } else { pCmsgT->len &= 0x0f; printf("RX-ID= %4ld (0x%03lx) - %016" PRIx64 " - len=%02X data= ", (unsigned long)pCmsgT->id, (unsigned long)pCmsgT->id, pCtx->ullLastTime, pCmsgT->len); if(pCmsgT->len > 8) pCmsgT->len = 8; for (j = 0; j < pCmsgT->len; j++) { printf("%02X ", pCmsgT->data[j]); } printf("\n"); } } else { /* Check for lost messages */ if (pCmsgT->msg_lost != 0) { printf("%02x Messages lost !\n", pCmsgT->msg_lost); } /* Return if console output is disabled */ if ((pCtx->mode & NO_ASCII_OUTPUT)) return; /* Calculate time difference */ if (pCtx->ullLastTime != 0) { ulTimeDiff = (uint32_t)((pCmsgT->timestamp - pCtx->ullLastTime) * INT64_C(1000000) / pCtx->udtTimestampFreq); /*us*/ } pCtx->ullLastTime = pCmsgT->timestamp; /* Mark interaction messages */ if (pCmsgT->len & NTCAN_INTERACTION) { printf("*"); } if (pCmsgT->len & NTCAN_RTR) { printf("RTR-ID=%9ld (0x%08lx) - %05ld.%03ld - len=%02X\n", (unsigned long)pCmsgT->id, (unsigned long)pCmsgT->id, (unsigned long)(ulTimeDiff / 1000), (unsigned long)(ulTimeDiff % 1000), pCmsgT->len & 0x0f); } else { pCmsgT->len &= 0x0f; #if 0 if (ullLastTime != 0) { ulTimeDiff = (uint32_t)((pCmsgT->timestamp - ullLastTime) * INT64_C(1000000) / udtTimestampFreq); /*us*/ } ullLastTime = pCmsgT->timestamp; #endif printf("RX-ID=%9ld (0x%08lx) - %05ld.%03ld - len=%02X data=", (unsigned long)pCmsgT->id, (unsigned long)pCmsgT->id, (unsigned long)(ulTimeDiff / 1000), (unsigned long)(ulTimeDiff % 1000), pCmsgT->len); if(pCmsgT->len > 8) pCmsgT->len = 8; for (j = 0; j < pCmsgT->len; j++) { printf("%02X ", pCmsgT->data[j]); } printf("\n"); /* Decode events */ if((pCmsgT->id & NTCAN_EV_BASE) != 0) { print_event((EVMSG *)pCmsgT, pCmsgT->timestamp, pCtx); } } } } #endif /* of NTCAN_IOCTL_GET_TIMESTAMP */ /************************************************************************/ /************************************************************************/ /* Function: print_cmsg_x() */ /* Print a formatted timestamped CAN message to stdout if */ /* NO_ASCII_OUTPUT flag is not set */ /************************************************************************/ /************************************************************************/ #ifdef NTCAN_FD static void print_cmsg_x(CMSG_X *pCmsgX, CANTEST_CTX *pCtx) { int j; uint32_t ulTimeDiff = 0; uint32_t len; int dPos; char fd = ' '; if(pCmsgX->len & NTCAN_FD) { fd = 'f'; } if(pCtx->mode & NTCAN_MODE_OBJECT) { pCtx->ullLastTime = pCmsgX->timestamp; if (pCmsgX->len & NTCAN_NO_DATA) { printf("RX-ID= %4ld (0x%03lx) - %016" PRIx64 " - NO DATA\n", (unsigned long)pCmsgX->id, (unsigned long)pCmsgX->id, pCtx->ullLastTime); } else if (pCmsgX->len & NTCAN_RTR) { printf("RTR-ID=%4ld (0x%03lx) - %016" PRIx64 " - len=%02X\n", (unsigned long)pCmsgX->id, (unsigned long)pCmsgX->id, pCtx->ullLastTime, pCmsgX->len & 0x0f); } else { len = NTCAN_LEN_TO_DATASIZE(pCmsgX->len); dPos = printf("RX-ID= %4ld (0x%03lx) - %016" PRIx64 " - len=%02X %cdat=", (unsigned long)pCmsgX->id, (unsigned long)pCmsgX->id, pCtx->ullLastTime, len, fd); for (j = 0; j < (int)len; j++) { if(j && !(j & 7)) { int k = 0; printf("\n"); while( k ++ < dPos-3 ){ printf(" "); } printf("%02X=", j); } printf("%02X ", pCmsgX->data[j]); } printf("\n"); } } else { /* Check for lost messages */ if (pCmsgX->msg_lost != 0) { printf("%02x Messages lost !\n", pCmsgX->msg_lost); } /* Return if console output is disabled */ if ((pCtx->mode & NO_ASCII_OUTPUT)) return; /* Calculate time difference */ if (pCtx->ullLastTime != 0) { ulTimeDiff = (uint32_t)((pCmsgX->timestamp - pCtx->ullLastTime) * INT64_C(1000000) / pCtx->udtTimestampFreq); /*us*/ } pCtx->ullLastTime = pCmsgX->timestamp; /* Mark interaction messages */ if (pCmsgX->len & NTCAN_INTERACTION) { printf("*"); } if (pCmsgX->len & NTCAN_RTR) { printf("RTR-ID=%9ld (0x%08lx) - %05ld.%03ld - len=%02X\n", (unsigned long)pCmsgX->id, (unsigned long)pCmsgX->id, (unsigned long)(ulTimeDiff / 1000), (unsigned long)(ulTimeDiff % 1000), pCmsgX->len & 0x0f); } else { len = NTCAN_LEN_TO_DATASIZE(pCmsgX->len); #if 0 if (ullLastTime != 0) { ulTimeDiff = (uint32_t)((pCmsgX->timestamp - ullLastTime) * INT64_C(1000000) / udtTimestampFreq); /*us*/ } ullLastTime = pCmsgX->timestamp; #endif dPos = printf("RX-ID=%9ld (0x%08lx) - %05ld.%03ld - len=%02X %cdat=", (unsigned long)pCmsgX->id, (unsigned long)pCmsgX->id, (unsigned long)(ulTimeDiff / 1000), (unsigned long)(ulTimeDiff % 1000), len, fd); for (j = 0; j < (int)len; j++) { if(j && !(j & 7)) { int k = 0; printf("\n"); while( k ++ < dPos - 3){ printf(" "); } printf("%02X=", j); } printf("%02X ", pCmsgX->data[j]); } printf("\n"); /* Decode events */ if((pCmsgX->id & NTCAN_EV_BASE) != 0) { print_event((EVMSG *)pCmsgX, pCmsgX->timestamp, pCtx); } } } } #endif /* of NTCAN_FD */ #if defined(unix) && !defined(RTAI) && !defined(RTLINUX) static unsigned long mtime(void) { struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return( tv.tv_sec *1000 + tv.tv_usec/1000); } #ifdef D3X void sigio_handler(int arg) { register CMSG *cm; int i, j; NTCAN_RESULT err; int32_t len; int8_t str_buf[100]; printf("Received signal SIGIO %d\n", arg); len = 1; err = canRead(h1, rxmsg, &len, NULL); if (err == NTCAN_SUCCESS) { if (!(pCtx->mode & NO_ASCII_OUTPUT)) { printf("Signal = %d Can-Messages=%d \n", arg, len); } for (i = 0; i < len; i++) { cm = &rxmsg[i]; if (cm->len & NTCAN_RTR) { if (cm->msg_lost != 0) { printf("%02x Messages lost !\n", cm->msg_lost); } if (!(pCtx->mode & NO_ASCII_OUTPUT)) { printf("RX-RTR-ID=%4d len=%01X\n", cm->id, cm->len & 0x0f); } } else { cm->len &= 0x0f; if (cm->msg_lost != 0) { printf("%02x Messages lost !\n", cm->msg_lost); } if (!(pCtx->mode & NO_ASCII_OUTPUT)) { printf("RX-ID=%4d len=%01X data= ", cm->id, cm->len); for (j = 0; j < cm->len; j++) { printf("%02X ", cm->data[j]); } printf(" ["); { int c; for (j = 0; j < cm->len; j++) { c = cm->data[j]; printf("%c", c > 31 && c < 128 ? c : '.' ); } } putchar(']'); printf("\n"); } } #if 0 frames ++; #endif } } else { printf("canRead returned:%s\n", get_error_str(str_buf,err)); SLEEP(100); } if (signal(SIGIO, sigio_handler) == SIG_ERR) { printf("Re-Initialising signal handler failed\n"); } else { printf("Re-Initialising signal handler succesfull\n"); } } # endif /* of D3X */ #endif /* of unix */ #ifdef CANTEST_USE_SIGUSR1_HANDLER void sigusr1_handler(int signum) { static unsigned int sigcnt; if (signum != SIGUSR1) return; sigcnt++; if ((sigcnt % 1000)==0) { printf("sigusr1_handler: sigcnt=%u\n",sigcnt); } } #endif #ifdef qnx static unsigned long mtime(void) { struct timespec tv; clock_gettime( CLOCK_REALTIME, &tv ); return (tv.tv_sec *1000 + tv.tv_nsec/1000000); } #endif /* of qnx */ #if defined(VXWORKS) || defined(RTOS32) # define CT_MAX_ARGS 30 /* Maximum arguments for command line */ /* * Helper code for VxWorks limited capability to deal with many cmd line args */ int canTest(char *args) { char *token; int argc = 1; char *argv[CT_MAX_ARGS] = {"canTest"}; /* * Make comand line from given string */ if(args != NULL) { for (token = strtok(args, " "); token && argc < (CT_MAX_ARGS - 1); argc++) { argv[argc] = token; token = strtok(NULL, " "); } } /* * Call real test program. Main is redefined for VxWorks */ return(main(argc, argv)); } #endif /* VXWORKS || RTOS32 */ #ifdef VXWORKS #if WANT_PRIO_CHECK == 1 /* * Helper code for VxWorks to prevent start with priority higher than * backend */ static STATUS _checkPriority(int net) { char *taskName = "CANx"; int prioSelf, prioBackend; int tid; taskName[3] = (char)('0' + net); /* * Get TID of backend */ tid = taskNameToId(taskName); if (ERROR == tid) { printf("\nError: No backend %s running\n", taskName); return(ERROR); } /* * Return error if getting own or backend priority failed */ if (ERROR == taskPriorityGet(tid, &prioBackend)) { printf("\nError getting priority of backend %s\n", taskName); return(ERROR); } /* * Return error if getting backend priority failed */ if (ERROR == taskPriorityGet(0, &prioSelf)) { printf("\nError getting own priority\n"); return(ERROR); } /* * Return error if own prio is higher than backend prio */ if (prioSelf <= prioBackend) { printf("\nOwn priority (%d) is higher than priority of backend" " '%s' (%d) which can cause unexpected results." " Spawn canTest with lower priority !!\n\n", prioSelf, taskName, prioBackend); return(ERROR); } return(OK); } #endif /* #if WANT_PRIO_CHECK == 1 */ #endif /* of VXWORKS */ #ifdef NET_OS static unsigned long mtime(void) { unsigned long ulHigh, ulLow; NATotalTicks(&ulHigh, &ulLow); return((ulLow * 1000) / BSP_TICKS_PER_SECOND); } #endif /* of NET_OS */ #ifdef _WIN32_WCE /* * Helper code for VxWorks to create argc/argv arrays for programs by * parsing the command line given as unicode string without the * program name into individual arguments. * It does not handle quoted strings. */ int CreateArgvArgc(TCHAR *pProgName, TCHAR *argv[30], TCHAR *pCmdLine) { TCHAR *pEnd; int argc = 0; /* Insert the program name as argc 1 */ argv[argc++] = pProgName; while (*pCmdLine != TEXT('\0')) { while (iswspace (*pCmdLine)) { pCmdLine++; /* Skip to first whitsacpe */ } if (*pCmdLine == TEXT('\0')) { break; /* Break at EOL */ } /* * Check for '' or "" */ if ((*pCmdLine == TEXT('"')) || (*pCmdLine == TEXT('\''))) { TCHAR cTerm = *pCmdLine++; for (pEnd = pCmdLine; (*pEnd != cTerm) && (*pEnd != TEXT('\0'));) { pEnd++; } } else { /* Find the end.*/ for (pEnd = pCmdLine; !iswspace(*pEnd) && (*pEnd != TEXT('\0'));) { pEnd++; } } if (*pEnd != TEXT('\0')) { *pEnd = TEXT('\0'); pEnd++; } argv[argc] = pCmdLine; argc++; pCmdLine = pEnd; } return argc; } #endif /* of _WIN32_WCE */ #ifdef RMOS static unsigned long mtime(void) { int rmStatus; RmAbsTimeStruct time; rmStatus = RmGetAbsTime(&time); if (rmStatus != RM_OK) { printf("Cannot get RMOS-Time! Err=%d!\n", rmStatus); return 0; } else { return time.lotime; } } #endif #ifdef _WIN32 # if defined(UNDER_RTSS) static unsigned long mtime(void) { LARGE_INTEGER ticks; RtGetClockTime(CLOCK_FASTEST, &ticks); /* Get 100 ns tick */ return ((unsigned long)(ticks.QuadPart / 10)); /* Return us tick */ } # elif defined(RTOS32) # else static unsigned long mtime(void) { LARGE_INTEGER frequency; if (QueryPerformanceFrequency(&frequency)) { LARGE_INTEGER ticks; QueryPerformanceCounter(&ticks); return (unsigned long) (((ticks.QuadPart) * 1000000) / frequency.QuadPart); } else { return GetTickCount(); } } /* * Helper code to dynamically load entries of NTCAN libraries >= 4.x.x * to be prevent load errors with previous versions which do not contain * these exports. */ static int DynLoad(void) { HMODULE hDll = NULL; # ifndef _WIN32_WCE /* Try loading NTCAN DLL (32 or 64 bit) dynamically and check success */ hDll = LoadLibrary("ntcan.dll"); /* 32 bit version */ if (NULL == hDll) { /* * In 64-bit driver revision 2.4.x the NTCAN library was named * ntcan64.dll. Cope with this legacy name. */ # if defined (_MSC_VER) __pragma(warning(disable:4127)) # endif if(8 == sizeof(INT_PTR)) { hDll = LoadLibrary("ntcan64.dll"); /* 64-bit legacy name */ } # if defined (_MSC_VER) __pragma(warning(default:4127)) # endif if (NULL == hDll) return -1; } # else /* Try loading NTCAN DLL dynamically and check success */ hDll = LoadLibrary(TEXT("ntcan.dll")); if (NULL == hDll) return -1; # endif /* of !defined _WIN32_WCE */ /* * NTCAN >= 2.3.0: * Get function ptr of canIoctl() */ pfnIoctl = FUNCPTR_CAN_IOCTL(hDll); /* * NTCAN > 4.0.x * Get function ptr of canTakeT() and canReadT() */ pfnTakeT = FUNCPTR_CAN_TAKE_T(hDll); pfnReadT = FUNCPTR_CAN_READ_T(hDll); /* * NTCAN > 4.1.x: * Get function ptr of canFormatError() */ pfnFormatError = FUNCPTR_CAN_FORMAT_ERROR(hDll); /* * NTCAN > 4.1.x: * Get function ptr of canGetOverlappedResultT() */ pfnGetOverlappedResultT = FUNCPTR_CAN_GET_OVERLAPPED_RESULT_T(hDll); /* * NTCAN > 4.3.0: * Get function ptr of canFormatEvent() */ pfnFormatEvent = FUNCPTR_CAN_FORMAT_EVENT(hDll); /* * NTCAN > 4.7.x: * Get function ptr of canSendT() and canWriteT() */ pfnSendT = FUNCPTR_CAN_SEND_T(hDll); pfnWriteT = FUNCPTR_CAN_WRITE_T(hDll); # if defined (NTCAN_FD) /* * NTCAN > 5.0.x: * Get function ptr of canTakeX(), canReadX(), canWriteX(), canSendX(), * canGetOverlappedResultX() */ pfnTakeX = FUNCPTR_CAN_TAKE_X(hDll); pfnReadX = FUNCPTR_CAN_READ_X(hDll); pfnSendX = FUNCPTR_CAN_SEND_X(hDll); pfnWriteX = FUNCPTR_CAN_WRITE_X(hDll); pfnGetOverlappedResultX = FUNCPTR_CAN_GET_OVERLAPPED_RESULT_X(hDll); #endif /* of NTCAN_FD) */ return(0); } # ifndef _WIN32_WCE static int ForceThreadAffinity(void) { SYSTEM_INFO udtSysInfo; int i; /* * GetProcessAffinityMask() parameter changed with the introduction of * 64-bit Windows from DWORD to DWORD_PTR. As earlier revisions of the * SDK didn't define DWORD_PTR we leave the definition for 32-bit * Windows as is to stay backward compatible. */ # ifdef _WIN64 DWORD_PTR dwProcessAffinityMask, dwSystemAffinityMask, dwMask; # else DWORD dwProcessAffinityMask, dwSystemAffinityMask, dwMask; # endif /* Get system information */ GetSystemInfo(&udtSysInfo); /* * In case of more than one processor force execution to the 1st processor * to be sure that using QueryPerformanceCounter() does not return TSC * counter values from different cores/processors. */ if(udtSysInfo.dwNumberOfProcessors <= 1) return 0; if(GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask)) { /* * Search the processor mask for the 1st allowed CPU and use this one. */ for(dwMask = 1, i = 0; i < (int)(sizeof(dwMask)<<3); i++, dwMask <<= 1) { if((dwProcessAffinityMask & dwMask) != 0) { SetThreadAffinityMask(GetCurrentThread(), dwMask); return(0); } } } return(1); } # endif /* of !defined(_WIN32_WCE) */ # endif /* of UNDER_RTSS */ #endif /* of _WIN32 */
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/include/ntcan.h
/* ntcan.h ** ** Copyright (c) 2001-2015 by electronic system design gmbh ** ** This software is copyrighted by and is the sole property of ** esd gmbh. All rights, title, ownership, or other interests ** in the software remain the property of esd gmbh. This ** software may only be used in accordance with the corresponding ** license agreement. Any unauthorized use, duplication, transmission, ** distribution, or disclosure of this software is expressly forbidden. ** ** This Copyright notice may not be removed or modified without prior ** written consent of esd gmbh. ** ** esd gmbh, reserves the right to modify this software without notice. ** ** electronic system design gmbh Tel. +49-511-37298-0 ** Vahrenwalder Str 207 Fax. +49-511-37298-68 ** 30165 Hannover http://www.esd.eu ** Germany support@esd.eu ** ** */ #ifndef _ntcan_h_ #define _ntcan_h_ /* ******************************************** */ /* ----------- Revision information ----------- */ /* Automatically inserted, don't edit template! */ /* CVS File $Revision: 15109 $ */ /* Released with libntcan.so.4.0.1 */ /* ------------ end template ------------ */ /* ******************************************** */ #if ((__GNUC__ > 2) || (__GNUC__ > 2) && (__GNUC_MINOR__ >= 1)) # define NTCAN_GCCATTR_DEPRECATED __attribute__((deprecated)) #else # define NTCAN_GCCATTR_DEPRECATED #endif #include <stdint.h> #include <errno.h> #ifndef EXPORT #define EXPORT #endif #ifndef CALLTYPE #define CALLTYPE #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /**************************************************************************************************/ /* Defines and macros */ /**************************************************************************************************/ /* * Flags for canIdAdd() */ #define NTCAN_20B_BASE 0x20000000 #define NTCAN_EV_BASE 0x40000000 #define NTCAN_EV_USER 0x40000080 #define NTCAN_EV_LAST 0x400000FF #define NTCAN_EV_CAN_ERROR NTCAN_EV_BASE #define NTCAN_EV_BAUD_CHANGE (NTCAN_EV_BASE + 0x1) #define NTCAN_EV_CAN_ERROR_EXT (NTCAN_EV_BASE + 0x2) #define NTCAN_EV_BUSLOAD (NTCAN_EV_BASE + 0x3) /* * Flags to interpret/set the length field of CAN frames */ #define NTCAN_RTR 0x10 /* CAN message is RTR */ /* -> NTCAN_FD bit not set */ #define NTCAN_NO_DATA 0x20 /* No updated data */ /* -> Object mode handle */ #define NTCAN_INTERACTION 0x20 /* Interaction data */ /* -> FIFO mode handle */ /* #define NTCAN_OLD_DATA 0x40 */ /* Only in 2.x driver? */ /* * Mode-flags for canOpen() */ #define NTCAN_MODE_NO_RTR 0x00000010 /* Ignore RTR frames on handle */ #define NTCAN_MODE_NO_DATA 0x00000020 /* Ignore data frames on handle */ #define NTCAN_MODE_NO_INTERACTION 0x00000100 /* Ignore locally send interaction messages */ #define NTCAN_MODE_MARK_INTERACTION 0x00000200 /* Mark interaction messages in len field */ #define NTCAN_MODE_LOCAL_ECHO 0x00000400 /* Echo sent frames to same handle */ #define NTCAN_MODE_TIMESTAMPED_TX 0x00020000 /* Timestamped TX */ #define NTCAN_MODE_OBJECT 0x10000000 /* Open for Rx object mode */ #define NTCAN_MODE_OVERLAPPED 0x20000000 /* Not supported under Linux! */ /* * Queue-Size in canOpen() */ #define NTCAN_MAX_TX_QUEUESIZE 2047 #define NTCAN_MAX_RX_QUEUESIZE 2047 #define NTCAN_NO_QUEUE -1 /* * Max for parameter net of canOpen() */ #define NTCAN_MAX_NETS 255 /* * Baudrate for canSetBaudrate()/canGetBaudrate() */ #define NTCAN_NO_BAUDRATE 0x7FFFFFFF /* No baudrate configured / Go off bus */ #define NTCAN_AUTOBAUD 0x00FFFFFE /* Activates autobaud mode, can be combined */ /* with NTCAN_LISTEN_ONLY_MODE flag */ /* * Defines to easily use CiA-recommended baudrates predefined by esd */ #define NTCAN_BAUD_1000 0x0 #define NTCAN_BAUD_800 0xE #define NTCAN_BAUD_500 0x2 #define NTCAN_BAUD_250 0x4 #define NTCAN_BAUD_125 0x6 #define NTCAN_BAUD_100 0x7 #define NTCAN_BAUD_50 0x9 #define NTCAN_BAUD_20 0xB #define NTCAN_BAUD_10 0xD /* * Additional flags, which can be combined (ored) with above baudrates */ #define NTCAN_LISTEN_ONLY_MODE 0x40000000 /* * Additional flags, which allow to configure baudrates in different ways */ #define NTCAN_USER_BAUD 0x80000000 /* DEPRECATED, please use the define below, */ #define NTCAN_USER_BAUDRATE 0x80000000 /* Program BTRs directly */ #define NTCAN_USER_BAUDRATE_NUM 0x20000000 /* Set a numerical baudrate */ /* (e.g. 1000000 for 1MBit/s) */ /* * Flags for scheduling mode (use with canIoctl()) */ #define NTCAN_SCHED_FLAG_EN 0x00000000 /* ID is enabled */ #define NTCAN_SCHED_FLAG_DIS 0x00000002 /* ID is disabled */ #define NTCAN_SCHED_FLAG_REL 0x00000000 /* Start time is relative */ #define NTCAN_SCHED_FLAG_ABS 0x00000001 /* Start time is absolute */ #define NTCAN_SCHED_FLAG_INC8 0x00000100 /* 8 Bit incrementer */ #define NTCAN_SCHED_FLAG_INC16 0x00000200 /* 16 Bit incrementer */ #define NTCAN_SCHED_FLAG_INC32 0x00000300 /* 32 Bit incrementer */ #define NTCAN_SCHED_FLAG_DEC8 0x00000400 /* 8 Bit decrementer */ #define NTCAN_SCHED_FLAG_DEC16 0x00000500 /* 16 Bit decrementer */ #define NTCAN_SCHED_FLAG_DEC32 0x00000600 /* 32 Bit decrementer */ #define NTCAN_SCHED_FLAG_OFS0 0x00000000 /* Counter at offset 0 */ #define NTCAN_SCHED_FLAG_OFS1 0x00001000 /* Counter at offset 1 */ #define NTCAN_SCHED_FLAG_OFS2 0x00002000 /* Counter at offset 2 */ #define NTCAN_SCHED_FLAG_OFS3 0x00003000 /* Counter at offset 3 */ #define NTCAN_SCHED_FLAG_OFS4 0x00004000 /* Counter at offset 4 */ #define NTCAN_SCHED_FLAG_OFS5 0x00005000 /* Counter at offset 5 */ #define NTCAN_SCHED_FLAG_OFS6 0x00006000 /* Counter at offset 6 */ #define NTCAN_SCHED_FLAG_OFS7 0x00007000 /* Counter at offset 7 */ /* * CAN controller types * (returned by canIoctl(NTCAN_IOCTL_GET_CTRL_STATUS) or * canIoctl(NTCAN_IOCTL_GET_BITRATE_DETAILS)) */ #define NTCAN_CANCTL_SJA1000 0x00 /* NXP SJA1000 / 82C200 */ #define NTCAN_CANCTL_I82527 0x01 /* Intel I82527 */ #define NTCAN_CANCTL_FUJI 0x02 /* Fujitsu MBxxxxx MCU */ #define NTCAN_CANCTL_LPC 0x03 /* NXP LPC2xxx MCU / LPC17xx */ #define NTCAN_CANCTL_MSCAN 0x04 /* Freescale MCU */ #define NTCAN_CANCTL_ATSAM 0x05 /* Atmel ARM CPU */ #define NTCAN_CANCTL_ESDACC 0x06 /* esd Advanced CAN Core */ #define NTCAN_CANCTL_STM32 0x07 /* ST STM32Fxxx MCU (bxCAN) */ #define NTCAN_CANCTL_CC770 0x08 /* Bosch CC770 (82527 comaptible) */ #define NTCAN_CANCTL_SPEAR 0x09 /* SPEAr320 (C_CAN compatible) */ #define NTCAN_CANCTL_FLEXCAN 0x0A /* Flexcan (e.g. in i.MX28 SoCs) */ #define NTCAN_CANCTL_SITARA 0x0B /* Texas Instruments Sitara */ #define NTCAN_CANCTL_MCP2515 0x0C /* Microchip MCP2515 */ #define NTCAN_CANCTL_MCAN 0x0D /* Bosch IP Core (M_CAN) */ /* * CAN transceiver types returned with canIoctl(NTCAN_IOCTL_GET_INFO) */ #define NTCAN_TRX_PCA82C251 0x00 /* NXP PCA82C251 */ #define NTCAN_TRX_SN65HVD251 0x01 /* TI SN65HVD251 */ #define NTCAN_TRX_SN65HVD265 0x02 /* TI SN65HVD265 */ /* * CAN baudrate flags * (returned by canIoctl(NTCAN_IOCTL_GET_BITRATE_DETAILS), * see NTCAN_BITRATE structure (flags)) */ #define NTCAN_BITRATE_FLAG_SAM 0x00000001 /* * Error code base, marking NTCAN specific errors */ #define NTCAN_ERRNO_BASE 0x00000100 /* * Error codes */ #define NTCAN_SUCCESS 0 #define NTCAN_RX_TIMEOUT (NTCAN_ERRNO_BASE + 1) #define NTCAN_TX_TIMEOUT (NTCAN_ERRNO_BASE + 2) /* #define NTCAN_RESERVED (NTCAN_ERRNO_BASE + 3) */ #define NTCAN_TX_ERROR (NTCAN_ERRNO_BASE + 4) #define NTCAN_CONTR_OFF_BUS (NTCAN_ERRNO_BASE + 5) #define NTCAN_CONTR_BUSY (NTCAN_ERRNO_BASE + 6) #define NTCAN_CONTR_WARN (NTCAN_ERRNO_BASE + 7) #define NTCAN_NO_ID_ENABLED (NTCAN_ERRNO_BASE + 9) #define NTCAN_ID_ALREADY_ENABLED (NTCAN_ERRNO_BASE + 10) #define NTCAN_ID_NOT_ENABLED (NTCAN_ERRNO_BASE + 11) /* #define NTCAN_RESERVED (NTCAN_ERRNO_BASE + 12) */ #define NTCAN_INVALID_FIRMWARE (NTCAN_ERRNO_BASE + 13) #define NTCAN_MESSAGE_LOST (NTCAN_ERRNO_BASE + 14) #define NTCAN_INVALID_HARDWARE (NTCAN_ERRNO_BASE + 15) #define NTCAN_PENDING_WRITE (NTCAN_ERRNO_BASE + 16) #define NTCAN_PENDING_READ (NTCAN_ERRNO_BASE + 17) #define NTCAN_INVALID_DRIVER (NTCAN_ERRNO_BASE + 18) #define NTCAN_SOCK_CONN_TIMEOUT (NTCAN_ERRNO_BASE + 0x80) #define NTCAN_SOCK_CMD_TIMEOUT (NTCAN_ERRNO_BASE + 0x81) #define NTCAN_SOCK_HOST_NOT_FOUND (NTCAN_ERRNO_BASE + 0x82) /* gethostbyname() failed */ #define NTCAN_INVALID_PARAMETER EINVAL #define NTCAN_INVALID_HANDLE EBADFD /* #define NTCAN_IO_INCOMPLETE not reasonable under Linux */ /* #define NTCAN_IO_PENDING not reasonable under Linux */ #define NTCAN_NET_NOT_FOUND ENODEV #define NTCAN_INSUFFICIENT_RESOURCES ENOMEM #define NTCAN_OPERATION_ABORTED EINTR #define NTCAN_WRONG_DEVICE_STATE (NTCAN_ERRNO_BASE + 19) #define NTCAN_HANDLE_FORCED_CLOSE (NTCAN_ERRNO_BASE + 20) #define NTCAN_NOT_IMPLEMENTED ENOSYS #define NTCAN_NOT_SUPPORTED (NTCAN_ERRNO_BASE + 21) #define NTCAN_CONTR_ERR_PASSIVE (NTCAN_ERRNO_BASE + 22) #define NTCAN_ERROR_NO_BAUDRATE (NTCAN_ERRNO_BASE + 23) #define NTCAN_ERROR_LOM (NTCAN_ERRNO_BASE + 24) /* * Macros to decode the 32-bit boardstatus of CAN_IF_STATUS */ #define NTCAN_GET_CTRL_TYPE(boardstatus) ((boardstatus >> 24) & 0xFF) #define NTCAN_GET_BOARD_STATUS(boardstatus) (boardstatus & 0xFFFF) /* * Macros for parameter len of CMSG / CMSG_T structure */ #define NTCAN_DLC(len) ((len) & 0x0F) #define NTCAN_DLC_AND_TYPE(len) ((len) & (0x0F | NTCAN_RTR)) #define NTCAN_IS_RTR(len) ((len) & NTCAN_RTR) #define NTCAN_IS_INTERACTION(len) ((len) & NTCAN_INTERACTION) /* * Feature-flags returned by canStatus() */ #define NTCAN_FEATURE_FULL_CAN (1<<0) /* Full CAN controller */ #define NTCAN_FEATURE_CAN_20B (1<<1) /* CAN 2.OB support */ #define NTCAN_FEATURE_DEVICE_NET (1<<2) /* Device net adapter */ #define NTCAN_FEATURE_CYCLIC_TX (1<<3) /* Cyclic Tx support */ #define NTCAN_FEATURE_TIMESTAMPED_TX (1<<3) /* SAME AS CYCLIC_TX, timestamped TX support */ #define NTCAN_FEATURE_RX_OBJECT_MODE (1<<4) /* Receive object mode support */ #define NTCAN_FEATURE_TIMESTAMP (1<<5) /* Timestamp support */ #define NTCAN_FEATURE_LISTEN_ONLY_MODE (1<<6) /* Listen-only-mode support */ #define NTCAN_FEATURE_SMART_DISCONNECT (1<<7) /* Leave-bus-after-last-close */ #define NTCAN_FEATURE_LOCAL_ECHO (1<<8) /* Interaction w. local echo */ #define NTCAN_FEATURE_SMART_ID_FILTER (1<<9) /* Adaptive ID filter */ #define NTCAN_FEATURE_SCHEDULING (1<<10) /* Scheduling feature */ #define NTCAN_FEATURE_DIAGNOSTIC (1<<11) /* CAN bus diagnostig support */ #define NTCAN_FEATURE_ERROR_INJECTION (1<<12) /* esdACC error injection support */ #define NTCAN_FEATURE_IRIGB (1<<13) /* IRIG-B support */ #define NTCAN_FEATURE_PXI (1<<14) /* Backplane clock and startrigger support */ #define NTCAN_FEATURE_CAN_FD (1<<15) /* CAN-FD support */ #define NTCAN_FEATURE_SELF_TEST (1<<16) /* Self-test mode support */ #define NTCAN_FEATURE_BASIC_20B NTCAN_FEATURE_CAN_20B /* DEPRECATED */ /* Use NTCAN_FEATURE_CAN_20B to */ /* assure OS interoperability */ /* * Bus states delivered by status-event (NTCAN_EV_CAN_ERROR) and * canIoctl(NTCAN_IOCTL_GET_CTRL_STATUS) */ #define NTCAN_BUSSTATE_OK 0x00 #define NTCAN_BUSSTATE_WARN 0x40 #define NTCAN_BUSSTATE_ERRPASSIVE 0x80 #define NTCAN_BUSSTATE_BUSOFF 0xC0 /* * IOCTL codes for canIoctl() */ #define NTCAN_IOCTL_FLUSH_RX_FIFO 0x0001 /* Flush Rx FIFO */ #define NTCAN_IOCTL_GET_RX_MSG_COUNT 0x0002 /* Ret # CMSG in Rx FIFO */ #define NTCAN_IOCTL_GET_RX_TIMEOUT 0x0003 /* Ret configured Rx tout */ #define NTCAN_IOCTL_GET_TX_TIMEOUT 0x0004 /* Ret configured Tx tout */ #define NTCAN_IOCTL_SET_20B_HND_FILTER 0x0005 /* Configure 20B filter */ #define NTCAN_IOCTL_GET_SERIAL 0x0006 /* Get HW serial number */ #define NTCAN_IOCTL_GET_TIMESTAMP_FREQ 0x0007 /* Get timestamp frequency in Hz */ #define NTCAN_IOCTL_GET_TIMESTAMP 0x0008 /* Get timestamp counter */ #define NTCAN_IOCTL_ABORT_RX 0x0009 /* Abort a pending read */ #define NTCAN_IOCTL_ABORT_TX 0x000A /* Abort pending write */ #define NTCAN_IOCTL_SET_RX_TIMEOUT 0x000B /* Change rx-timeout parameter */ #define NTCAN_IOCTL_SET_TX_TIMEOUT 0x000C /* Change tx-timeout parameter */ #define NTCAN_IOCTL_TX_OBJ_CREATE 0x000D /* Create obj, arg->CMSG */ #define NTCAN_IOCTL_TX_OBJ_AUTOANSWER_ON 0x000E /* Switch autoanswer on,arg->CMSG */ #define NTCAN_IOCTL_TX_OBJ_AUTOANSWER_OFF 0x000F /* Switch autoanswer off,arg->CMSG */ #define NTCAN_IOCTL_TX_OBJ_UPDATE 0x0010 /* update obj, arg->CMSG */ #define NTCAN_IOCTL_TX_OBJ_DESTROY 0x0011 /* Destroy obj, arg->id */ /* #define NTCAN_IOCTL_RESERVED 0x0012 */ #define NTCAN_IOCTL_TX_OBJ_SCHEDULE_START 0x0013 /* Start scheduling for handle */ #define NTCAN_IOCTL_TX_OBJ_SCHEDULE_STOP 0x0014 /* Stop scheduling for handle */ #define NTCAN_IOCTL_TX_OBJ_SCHEDULE 0x0015 /* Set sched. for obj,arg->CSCHED */ #define NTCAN_IOCTL_SET_BUSLOAD_INTERVAL 0x0016 /* Set busload event interval (ms) */ #define NTCAN_IOCTL_GET_BUSLOAD_INTERVAL 0x0017 /* Get busload event interval (ms) */ #define NTCAN_IOCTL_GET_BUS_STATISTIC 0x0018 /* Get CAN bus statistic */ #define NTCAN_IOCTL_GET_CTRL_STATUS 0x0019 /* Get Controller status */ #define NTCAN_IOCTL_GET_BITRATE_DETAILS 0x001A /* Get detailed baudrate info */ #define NTCAN_IOCTL_GET_NATIVE_HANDLE 0x001B /* Get native (OS) handle */ #define NTCAN_IOCTL_SET_HND_FILTER 0x001C /* Set handle filter */ #define NTCAN_IOCTL_GET_INFO 0x001D /* Get extended board information */ #define NTCAN_IOCTL_TX_OBJ_CREATE_X 0x001E /* Create obj, arg->CMSG_X */ #define NTCAN_IOCTL_TX_OBJ_UPDATE_X 0x001F /* update obj, arg->CMSG_X */ /* * Error injection IOCTLs */ #define NTCAN_IOCTL_EEI_CREATE 0x0020 /* Allocate esdacc error injection (EEI) unit */ #define NTCAN_IOCTL_EEI_DESTROY 0x0021 /* Free EEI unit */ #define NTCAN_IOCTL_EEI_STATUS 0x0022 /* Get status of EEI unit */ #define NTCAN_IOCTL_EEI_CONFIGURE 0x0023 /* Configure EEI unit */ #define NTCAN_IOCTL_EEI_START 0x0024 /* Arm EEI unit */ #define NTCAN_IOCTL_EEI_STOP 0x0025 /* Halt EEI unit */ #define NTCAN_IOCTL_EEI_TRIGGER_NOW 0x0026 /* Manually trigger EEI unit */ /* * Timestamped-TX IOCTLs */ #define NTCAN_IOCTL_SET_TX_TS_WIN 0x0030 /* Configure window for timestamped TX, */ /* 0: off (use normal FIFO), */ /* >0: size in ms, max depends on hardware */ /* ((2^32 - 1) ticks) */ #define NTCAN_IOCTL_GET_TX_TS_WIN 0x0031 /* Get window for timestamped TX in ms */ #define NTCAN_IOCTL_SET_TX_TS_TIMEOUT 0x0032 /* Set frame timeout for timestamped TX, */ /* 0: no timeout, >0: timeout in ms */ #define NTCAN_IOCTL_GET_TX_TS_TIMEOUT 0x0033 /* Get frame timeout for timestamped TX */ /* */ #define NTCAN_IOCTL_RESET_CTRL_EC 0x801B /* Reset Tx/Rx error counters of controller */ /* * Types for canFormatError() */ #define NTCAN_ERROR_FORMAT_LONG 0x0000 /* Error text as string */ #define NTCAN_ERROR_FORMAT_SHORT 0x0001 /* Error code as string */ /* * Flags for canFormatEvent() (flags in NTCAN_FORMATEVENT_PARAMS) */ #define NTCAN_FORMATEVENT_SHORT 0x0001 /* Create a shorter description */ /**************************************************************************************************/ /* Defines for error injection */ /**************************************************************************************************/ /* * status in NTCAN_EEI_STATUS */ #define EEI_STATUS_OFF 0x0 #define EEI_STATUS_WAIT_TRIGGER 0x1 #define EEI_STATUS_SENDING 0x2 #define EEI_STATUS_FINISHED 0x3 /* * mode_trigger in NTCAN_EEI_UNIT */ #define EEI_TRIGGER_MATCH 0 #define EEI_TRIGGER_ARBITRATION 1 #define EEI_TRIGGER_TIMESTAMP 2 #define EEI_TRIGGER_FIELD_POSITION 3 #define EEI_TRIGGER_EXTERNAL_INPUT 4 /* * mode_trigger_option in NTCAN_EEI_UNIT */ #define EEI_TRIGGER_ARBITRATION_OPTION_ABORT_ON_ERROR 1 /* ARBITRATION MODE ONLY */ #define EEI_TRIGGER_MATCH_OPTION_DESTUFFED 1 /* MATCH MODE ONLY */ #define EEI_TRIGGER_TIMESTAMP_OPTION_BUSFREE 1 /* TIMESTAMP MODE ONLY */ /* * mode_repeat in NTCAN_EEI_UNIT */ #define EEI_MODE_REPEAT_ENABLE 0x1 #define EEI_MODE_REPEAT_USE_NUMBER_OF_REPEAT 0x2 /* * mode_triggerarm_delay and mode_triggeraction_delay in NTCAN_EEI_UNIT */ #define EEI_TRIGGERDELAY_NONE 0 /* no delay */ #define EEI_TRIGGERDELAY_BITTIMES 1 /* delay specified in bittimes */ /**************************************************************************************************/ /* Data types and structures */ /**************************************************************************************************/ /* * Dear ntcan-user, * we regret, that we were forced to change the name of our handle type. * This had to be done to keep "inter-system" compatibility of your * application sources, after a change in VxWorks 6.0. Please replace all * occurrences of HANDLE with NTCAN_HANDLE in your application's source * code. */ typedef int32_t OVERLAPPED; #ifndef NTCAN_CLEAN_NAMESPACE typedef int32_t HANDLE NTCAN_GCCATTR_DEPRECATED; #endif typedef int32_t NTCAN_RESULT; typedef int32_t NTCAN_HANDLE; typedef struct { int32_t id; /* can-id */ uint8_t len; /* length of message: 0-8 */ uint8_t msg_lost; /* count of lost rx-messages */ uint8_t reserved[2]; /* reserved */ uint8_t data[8]; /* 8 data-bytes */ } CMSG; typedef struct { int32_t id; /* can-id */ uint8_t len; /* length of message: 0-8 */ uint8_t msg_lost; /* count of lost rx-messages */ uint8_t reserved[2]; /* reserved */ uint8_t data[8]; /* 8 data-bytes */ uint64_t timestamp; /* time stamp of this message */ } CMSG_T; typedef struct { uint8_t reserved1; /* Reserved for future use */ uint8_t can_status; /* CAN controller status */ uint8_t reserved2; /* Reserved for future use */ uint8_t ctrl_overrun; /* Controller overruns */ uint8_t reserved3; /* Reserved for future use */ uint8_t fifo_overrun; /* Driver FIFO overruns */ } EV_CAN_ERROR; typedef struct { uint32_t baud; /* New NTCAN baudrate value */ uint32_t num_baud; /* New numerical baudrate value (optional) */ } EV_CAN_BAUD_CHANGE; typedef union { struct { uint8_t status; /* (SJA1000) CAN controller status */ uint8_t ecc; /* Error Capture Register */ uint8_t rec; /* Rx Error Counter */ uint8_t tec; /* Tx Error Counter */ } sja1000; struct { uint8_t status; /* (ESDACC) CAN controller status */ uint8_t ecc; /* Error Capture Register */ uint8_t rec; /* Rx Error Counter */ uint8_t tec; /* Tx Error Counter */ uint8_t txstatus; /* (ESDACC) CAN controller TX status */ } esdacc; } EV_CAN_ERROR_EXT; typedef struct { int32_t evid; /* event-id: range: EV_BASE...EV_LAST */ uint8_t len; /* length of message: 0-8 */ uint8_t reserved[3]; /* reserved */ union { uint8_t c[8]; uint16_t s[4]; uint32_t l[2]; uint64_t q; EV_CAN_ERROR error; EV_CAN_BAUD_CHANGE baud_change; EV_CAN_ERROR_EXT error_ext; } evdata; } EVMSG; typedef struct { int32_t evid; /* event-id: range: EV_BASE...EV_LAST */ uint8_t len; /* length of message: 0-8 */ uint8_t reserved[3]; /* reserved */ union { uint8_t c[8]; uint16_t s[4]; uint32_t l[2]; uint64_t q; EV_CAN_ERROR error; EV_CAN_BAUD_CHANGE baud_change; EV_CAN_ERROR_EXT error_ext; } evdata; uint64_t timestamp; /* time stamp of this message */ } EVMSG_T; typedef struct { uint16_t hardware; uint16_t firmware; uint16_t driver; uint16_t dll; uint32_t boardstatus; uint8_t boardid[14]; uint16_t features; } CAN_IF_STATUS; typedef struct { const uint16_t hardware; /* Hardware version */ const uint16_t firmware; /* Firmware / FPGA version (0 = N/A) */ const uint16_t driver; /* Driver version */ const uint16_t dll; /* NTCAN library version */ const uint32_t features; /* Device/driver capability flags */ const uint32_t serial; /* Serial # (0 = N/A) */ const uint64_t timestamp_freq; /* Timestamp frequency (in Hz, 1 = N/A) */ const uint32_t ctrl_clock; /* Frequency of CAN controller (in Hz) */ const uint8_t ctrl_type; /* Controller type (NTCAN_CANCTL_XXX) */ const uint8_t base_net; /* Base net number */ const uint8_t ports; /* Number of physical ports */ const uint8_t transceiver; /* Transceiver type (NTCAN_TRX_XXX) */ const uint16_t boardstatus; /* Hardware status */ const uint16_t firmware2; /* Second firmware version (0 = N/A) */ const char boardid[32]; /* Board ID string */ const char serial_string[16]; /* Serial # as string */ const char drv_build_info[64]; /* Build info of driver */ const char lib_build_info[64]; /* Build info of library */ const uint8_t reserved2[44]; /* Reserved for future use */ } NTCAN_INFO; typedef struct { int32_t id; int32_t flags; uint64_t time_start; uint64_t time_interval; uint32_t count_start; /* Start value for counting */ uint32_t count_stop; /* Stop value for counting. After reaching */ /* this value, the counter is loaded with */ /* the count_start value. */ } CSCHED; typedef struct { uint32_t std_data; /* # of std CAN messages */ uint32_t std_rtr; /* # of std RTR requests */ uint32_t ext_data; /* # of ext CAN messages */ uint32_t ext_rtr; /* # of ext RTR requests */ } NTCAN_FRAME_COUNT; typedef struct { uint64_t timestamp; /* Timestamp */ NTCAN_FRAME_COUNT rcv_count; /* # of received frames */ NTCAN_FRAME_COUNT xmit_count; /* # of transmitted frames */ uint32_t ctrl_ovr; /* # of controller overruns */ uint32_t fifo_ovr; /* # of FIFO verflows */ uint32_t err_frames; /* # of error frames */ uint32_t rcv_byte_count; /* # of received bytes */ uint32_t xmit_byte_count; /* # of transmitted bytes */ uint32_t aborted_frames; /* # of aborted frames */ uint32_t reserved[2]; /* Reserved */ uint64_t bit_count; /* # of received bits */ } NTCAN_BUS_STATISTIC; typedef struct { uint8_t rcv_err_counter; /* Receive error counter */ uint8_t xmit_err_counter; /* Transmit error counter */ uint8_t status; /* CAN controller status */ uint8_t type; /* CAN controller type */ } NTCAN_CTRL_STATE; typedef struct { uint32_t baud; /* value configured by user via canSetBaudrate() */ uint32_t valid; /* validity of all _following_ infos */ /* (-1 = invalid, NTCAN_SUCCESS, NTCAN_NOT_IMPLEMENTED) */ uint32_t rate; /* CAN bitrate in Bit/s */ uint32_t clock; /* frequency of CAN controller */ uint8_t ctrl_type; /* CANIO_CANCTL_XXX defines */ uint8_t tq_pre_sp; /* number of time quantas before samplep. (SYNC + TSEG1)*/ uint8_t tq_post_sp; /* number of time quantas after samplepoint (TSEG2) */ uint8_t sjw; /* syncronization jump width in time quantas (SJW) */ uint32_t error; /* actual deviation of configured baudrate in (% * 100) */ uint32_t flags; /* baudrate flags (possibly ctrl. specific, e.g. SAM) */ uint32_t reserved[3]; /* for future use */ } NTCAN_BITRATE; typedef struct { uint64_t timestamp; /* Timestamp (for busload) */ uint64_t timestamp_freq; /* Timestamp frequency (for busload) */ uint32_t num_baudrate; /* Numerical baudrate (for busload) */ uint32_t flags; /* Flags */ uint64_t busload_oldts; /* <---+-- used internally, set to */ uint64_t busload_oldbits; /* <---+ zero on first call */ uint8_t ctrl_type; /* Controller type (for ext_error) */ uint8_t reserved[7]; /* Reserved (7 bytes) */ uint32_t reserved2[4]; /* Reserved (16 bytes) */ } NTCAN_FORMATEVENT_PARAMS; typedef struct { uint32_t acr; uint32_t amr; uint32_t idArea; } NTCAN_FILTER_MASK; /**************************************************************************************************/ /* Structures to be used with error injection */ /**************************************************************************************************/ typedef union { uint8_t c[20]; uint16_t s[10]; uint32_t l[5]; } CAN_FRAME_STREAM; typedef struct _NTCAN_EEI_UNIT { uint32_t handle; /* Handle for ErrorInjection Unit */ uint8_t mode_trigger; /* Trigger mode */ uint8_t mode_trigger_option; /* Options to trigger */ uint8_t mode_triggerarm_delay; /* Enable delayed arming of trigger unit */ uint8_t mode_triggeraction_delay; /* Enable delayed TX out */ uint8_t mode_repeat; /* Enable repeat */ uint8_t mode_trigger_now; /* Trigger with next TX point */ uint8_t mode_ext_trigger_option; /* Switch between trigger and sending */ uint8_t mode_send_async; /* Send without timing synchronization */ uint8_t reserved1[4]; uint64_t timestamp_send; /* Timestamp for Trigger Timestamp */ CAN_FRAME_STREAM trigger_pattern; /* Trigger for mode Pattern Match */ CAN_FRAME_STREAM trigger_mask; /* Mask to trigger Pattern */ uint8_t trigger_ecc; /* ECC for Trigger Field Position */ uint8_t reserved2[3]; uint32_t external_trigger_mask; /* Enable Mask for external Trigger */ uint32_t reserved3[16]; CAN_FRAME_STREAM tx_pattern; /* TX pattern */ uint32_t tx_pattern_len; /* Length of TX pattern */ uint32_t triggerarm_delay; /* Delay for mode triggerarm delay */ uint32_t triggeraction_delay; /* Delay for mode trigger delay */ uint32_t number_of_repeat; /* Number of repeats in mode repeat (0 = forever) */ uint32_t reserved4; CAN_FRAME_STREAM tx_pattern_recessive; /* Recessive TX pattern (USB400 Addon) */ uint32_t reserved5[9]; } NTCAN_EEI_UNIT; typedef struct _NTCAN_EEI_STATUS { uint32_t handle; /* Handle for ErrorInjection Unit */ uint8_t status; /* Status form Unit */ uint8_t unit_index; /* Error Injection Unit ID */ uint8_t units_total; /* Max Error Units in esdacc core */ uint8_t units_free; /* Free Error Units in esdacc core */ uint64_t trigger_timestamp; /* Timestamp of trigger time */ uint16_t trigger_cnt; /* Count of trigger in Repeat mode */ uint16_t reserved0; uint32_t reserved1[27]; } NTCAN_EEI_STATUS; typedef struct _CMSG_FRAME { CAN_FRAME_STREAM can_frame; /* Complete Can Frame */ CAN_FRAME_STREAM stuff_bits; /* Mask of Stuff bits */ uint16_t crc; /* CRC of CAN Frame */ uint8_t length; /* Length of Can Frame in Bit */ uint8_t pos_id11; /* Position of Identifier 11 Bit */ uint8_t pos_id18; /* Position of Identifier 18 Bit */ uint8_t pos_rtr; /* Position of RTR Bit */ uint8_t pos_crtl; /* Position of Control Field */ uint8_t pos_dlc; /* Position of DLC Bits */ uint8_t pos_data[8]; /* Position of Data Field */ uint8_t pos_crc; /* Position of CRC Field */ uint8_t pos_crc_del; /* Position of CRC delimiter */ uint8_t pos_ack; /* Position of ACK Field */ uint8_t pos_eof; /* Position of End of Frame */ uint8_t pos_ifs; /* Position of Inter Frame Space */ uint8_t reserved[3]; } CMSG_FRAME; /**************************************************************************************************/ /* Prototypes */ /**************************************************************************************************/ EXPORT NTCAN_RESULT CALLTYPE canOpen( /* Ret: NTCAN_SUCCESS if no error occured */ int32_t net, /* In: net number */ uint32_t flags, /* In: handle mode flags */ int32_t txqueuesize, /* In: nr of entries in message queue */ int32_t rxqueuesize, /* In: nr of entries in message queue */ int32_t txtimeout, /* In: tx-timeout in miliseconds */ int32_t rxtimeout, /* In: rx-timeout in miliseconds */ NTCAN_HANDLE *handle ); /* Out: nt-handle */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canClose( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle ); /* In: handle */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canSetBaudrate( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ uint32_t baud ); /* In: baudrate-constant */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canGetBaudrate( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ uint32_t *baud ); /* Out: baudrate */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canIdAdd( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ int32_t id ); /* In: CAN identifier */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canIdDelete( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ int32_t id ); /* In: CAN identifier */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canIdRegionAdd( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ int32_t idStart, /* In: 1st CAN message identifier */ int32_t *idCnt ); /* In: Number of CAN IDs to enable */ /* Out: Number of enabled CAN IDs */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canIdRegionDelete( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ int32_t idStart, /* In: 1st CAN message identifier */ int32_t *idCnt ); /* In: Number of CAN IDs to disable */ /* Out: Number of disabled CAN IDs */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canTake( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ CMSG *cmsg, /* In: ptr to CMSG-buffer */ int32_t *len ); /* In: size of CMSG-buffer */ /* Out: count of received messages */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canTakeT( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ CMSG_T *cmsg_t, /* In: ptr to receive buffer */ int32_t *len ); /* Out: size of CMSG_T-Buffer */ /* In: number of received messages */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canRead( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ CMSG *cmsg, /* In: ptr to CMSG-buffer */ int32_t *len, /* In: size of CMSG-buffer */ /* Out: count of received messages */ OVERLAPPED *ovrlppd); /* In: NULL (n/a under Linux) */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canReadT( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ CMSG_T *cmsg_t, /* In: ptr to receive buffer */ int32_t *len, /* In: size of CMSG_T-Buffer */ /* Out: count of received messages */ OVERLAPPED *ovrlppd); /* In: NULL (n/a under Linux) */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canSend( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ CMSG *cmsg, /* In: ptr to CMSG-buffer */ int32_t *len ); /* In: size of CMSG-buffer */ /* Out: number of processed messages */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canSendT( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ CMSG_T *cmsg, /* In: ptr to CMSG_T-buffer */ int32_t *len ); /* In: size of CMSG_T-buffer */ /* Out: number of processed messages */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canWrite( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ CMSG *cmsg, /* In: ptr to CMSG-buffer */ int32_t *len, /* In: size of CMSG-buffer */ /* Out: number of transmitted messages */ OVERLAPPED *ovrlppd); /* In: NULL (n/a under Linux) */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canWriteT( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ CMSG_T *cmsg, /* In: ptr to CMSG_T-buffer */ int32_t *len, /* In: size of CMSG_T-buffer */ /* Out: number of transmitted messages */ OVERLAPPED *ovrlppd); /* In: NULL (n/a under Linux) */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canReadEvent( /* DEPRECATED Ret: NTCAN_SUCCESS, if no error */ NTCAN_HANDLE handle, /* In: handle */ EVMSG *evmsg, /* In: ptr to event-msg-buffer */ OVERLAPPED *ovrlppd); /* In: NULL (n/a under Linux) */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canSendEvent( /* DEPRECATED Ret: NTCAN_SUCCESS, if no error */ NTCAN_HANDLE handle, /* In: handle */ EVMSG *evmsg ); /* In: ptr to event-msg-buffer */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canStatus( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ CAN_IF_STATUS *cstat ); /* In: ptr to can-status-buffer */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canIoctl( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_HANDLE handle, /* In: handle */ uint32_t ulCmd, /* In: Command */ void *pArg ); /* In: Ptr to command specific argument */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canFormatError( /* Ret: NTCAN_SUCCESS if no error occured */ NTCAN_RESULT error, /* In: Error code */ uint32_t type, /* In: Error message type */ char *pBuf, /* In: Pointer to destination buffer */ uint32_t bufsize); /* In: Size of the buffer above */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canFormatEvent( /* Ret: NTCAN_SUCCESS if no error occured */ EVMSG *event, /* In: pointer to event message */ NTCAN_FORMATEVENT_PARAMS *para, /* In: Parameters */ char *pBuf, /* In: Pointer to destination buffer */ uint32_t bufsize); /* In: Size of the buffer above */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canFormatFrame( /* Ret: NTCAN_SUCCESS if no error occured */ CMSG *msg, /* In: CAN message */ CMSG_FRAME *frame, /* Out: CAN Frame + Information */ uint32_t eccExt); /* In: ECC Errors + Features */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canGetOverlappedResult(/* Ret: NTCAN_NOT_IMPLEMENTED */ NTCAN_HANDLE handle, /* In: handle */ OVERLAPPED *ovrlppd, /* In: overlapped-structure */ int32_t *len, /* Out: cnt of available CMSG-buffer */ int32_t bWait ); /* In: FALSE => do not wait, else wait */ /*................................................................................................*/ EXPORT NTCAN_RESULT CALLTYPE canGetOverlappedResultT(/* Ret: NTCAN_NOT_IMPLEMENTED */ NTCAN_HANDLE handle, /* In: handle */ OVERLAPPED *ovrlppd, /* Out: Win32 overlapped structure */ int32_t *len, /* Out: # of available CMSG_T-Buffer */ int32_t bWait ); /* In: FALSE =>do not wait, else wait */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _ntcan_h_ */
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/osiftypes.h
/* -*- linux-c -*- * FILE NAME osiftypes.h * * BRIEF MODULE DESCRIPTION * ... * * * history: * * 21.05.03 - first version mt * */ /************************************************************************ * * Copyright (c) 1996 - 2009 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd-electronics.com * Germany sales@esd-electronics.com * *************************************************************************/ /*! \file osiftypes.h \brief OSIFTypes header This file contains the OSIF datatypes. Any driver should use OSIF datatypes instead of the native ones. */ #ifndef __OSIFTYPES_H__ #define __OSIFTYPES_H__ #include <sys_osiftypes.h> #endif
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/sysdep.h
/* -*- esdcan-c -*- * FILE NAME sysdep.h * copyright 2002-2015 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * Linux kernel version dependency adaption * * * * history: * * 09.01.15 - Use vprintk() for kernels > 2.6.18 stm * 19.08.13 - fix for kernel greater 3.7 mk * 23.09.04 - removed include of version.h ab * 26.11.03 - corrected OSIF_VSNPRINTF for kernel < 2.4.0 ab * 13.11.03 - added urb-typedef for some linux-versions ab * 02.09.02 - first version mf * */ /************************************************************************ * * Copyright (c) 1996 - 2015 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd-electronics.com * Germany sales@esd-electronics.com * *************************************************************************/ /*! \file sysdep.h \brief Adaption of Linux kernel version changes This file fixes changes in the Linux kernel version. */ #ifndef __SYSDEP_H__ #define __SYSDEP_H__ # if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,0) # define OSIF_VSNPRINTF(buf, cnt, fmt, arg) vsprintf(buf, fmt, arg) # elif LINUX_VERSION_CODE < KERNEL_VERSION(2,4,8) /* * AB: I've tried to find out, when vsnprintf came into the kernel. * At least for Alan Cox kernels it seems to be 2.4.6. * Increased to 2.4.8, since further science suggested, that * integration happened on 2001-07-13 and changelogs on kernel.org * suggest, that it might have happened with 2.4.7 (2001-07-20). * To be on the save side, I chose 2.4.8 (2001-08-10). */ # define OSIF_VSNPRINTF(buf, cnt, fmt, arg) osif_vsnprintf(buf, cnt, fmt, arg) /* Use implementation of osif_vsnprintf() in osif.c */ # define OSIF_PROVIDES_VSNPRINTF # else # define OSIF_VSNPRINTF(buf, cnt, fmt, arg) vsnprintf(buf, cnt, fmt, arg) # endif /* * STM: Kernels since 2.6.0 should have vprintk(). Checked for sure with * kernel 2.6.18 and later. */ # if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,18) # define OSIF_USE_VPRINTK 1 # endif # if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,0) # define PCI_BASE_ADDR_ACC(dev, n) (dev->base_address[n] & (~0x0000000F)) # define OSIF_PCI_GET_FLAGS(dev, n) (dev->base_address[n] & 0x0000000F) # define OSIF__INIT # define OSIF__EXIT # elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # define PCI_BASE_ADDR_ACC(dev, n) (pci_resource_start(dev, n)) # define OSIF_PCI_GET_FLAGS(dev, n) (pci_resource_flags(dev, n)) # if LINUX_VERSION_CODE <= KERNEL_VERSION(3,7,0) # define OSIF__INIT __devinit # define OSIF__EXIT __devexit # else # define OSIF__INIT # define OSIF__EXIT # endif # else # define PCI_BASE_ADDR_ACC(dev, n) (dev->resource[n].start) # define OSIF_PCI_GET_FLAGS(dev, n) (dev->resource[n].flags) # define OSIF__INIT __init # define OSIF__EXIT __exit # endif # if LINUX_VERSION_CODE < KERNEL_VERSION(2,2,18) /* AB TODO: check minor version */ # define OSIF_MODULE_INIT(fct) INT32 init_module(VOID) { return fct(); } # define OSIF_MODULE_EXIT(fct) VOID cleanup_module(VOID) { fct(); } # define OSIF_DECL_WAIT_QUEUE(p) struct wait_queue *p = NULL # define OSIF_PCI_GET_RANGE(dev, n) \ (dev->PCI_BASE_ADDR_ACC(n) & PCI_BASE_ADDRESS_SPACE ? \ /* I/O-space */ \ (~(dev->PCI_BASE_ADDR_ACC(n) & PCI_BASE_ADDRESS_IO_MASK) + 1) : \ /* Memory-space */ \ (~(dev->PCI_BASE_ADDR_ACC(n) & PCI_BASE_ADDRESS_MEM_MASK) + 1) \ ) # else # define OSIF_MODULE_INIT(fct) module_init(fct) # define OSIF_MODULE_EXIT(fct) module_exit(fct) # define OSIF_DECL_WAIT_QUEUE(p) DECLARE_WAIT_QUEUE_HEAD(p) # define OSIF_PCI_GET_RANGE(dev, n) pci_resource_len(dev, n) # endif #endif
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/esdcan.c
/* -*- esdcan-c -*- * FILE NAME esdcan.c * copyright 2002-2015 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * This file contains the Linux / RTAI-Linux entries for * the esd CAN driver * * * Author: Matthias Fuchs * matthias.fuchs@esd.eu * * history: * * $Log$ * Revision 1.166 2015/07/09 13:07:57 stefanm * Added printout for OSIF_ZONE_USR_INIT to show when kernel * module's initialisation starts. * * Revision 1.165 2015/03/12 19:08:30 stefanm * Mantis 2553: Adapted message that is shown if the * PCI405 board doesn't boot correctly because there is * an old U-Boot installed on the PCI405. * Additionally needed a fix in boardrc.c. * * Revision 1.164 2015/01/13 15:31:02 stefanm * Added support for NTCAN_IOCTL_GET_INFO / IOCTL_ESDCAN_GET_INFO. * Will now count active nodes in <num_nodes> of card structure. * New <version_firmware2> is needed for USB400 Cypress updateable FW. * * Revision 1.163 2014/08/21 13:17:55 manuel * Added new IOCTLs: SEND_X WRITE_X TAKE_X READ_X SET_BAUD_X GET_BAUD_X * Fixed vme include * * Revision 1.162 2014/07/08 07:44:48 matthias * remove printk * * Revision 1.161 2014/07/07 14:36:20 matthias * check fo CONFIG_OF_DEVICE or (!) CONFIG_OF_FLATTREE * * Revision 1.160 2014/07/04 10:00:08 hauke * Just include <nucleus.h> which has to include the removed header (in the expected sequence). * * Revision 1.159 2014/06/23 17:02:06 stefanm * Removed ESDCAN_ZONE_USR_INIT and replaced by OSIF_ZONE_USR_INIT used directly * because it did not work well with the new osif_dprint() function (no output). * Replaced wrong "linux-c" mode with atm. invalid "esdcan-c" mode. * * Revision 1.158 2014/01/27 11:26:15 andreas * Some cleanup, mainly tried to clear the ifdef-mess by adding some more comments... * * Revision 1.157 2013/12/30 23:45:10 ar * Better support for vmecan4. * * Revision 1.156 2013/12/30 16:13:01 frank * Added some debug output to can_attach_common() * * Revision 1.155 2013/11/19 15:13:33 frank * Added SPI support (BOARD_SPI) (see also esdcan_spi.c) * * Revision 1.154 2013/09/04 13:00:06 andreas * Startup banner cleaned up * * Revision 1.153 2013/08/19 14:17:01 manuel * Fixed procfile handling for kernel 3.8 and greater * * Revision 1.152 2013/08/09 13:01:41 andreas * Small change on startup message * * Revision 1.151 2013/08/02 09:36:58 andreas * Some whitespace deleted... * * Revision 1.150 2013/08/01 15:03:40 andreas * Changed can_board_detach_final() to macro * * Revision 1.149 2013/08/01 12:50:52 andreas * Added can_board_detach_final() * * Revision 1.148 2013/06/27 12:48:25 andreas * Removed driver parameter for TX-TS window size for boards which have NUC_TX_TS NOT defined * * Revision 1.147 2013/01/11 18:30:20 andreas * Forgot to register the new IOCTLs "old style" * * Revision 1.146 2013/01/11 18:29:11 andreas * Added driver parameter txtswin * Added IOCTLs: IOCTL_ESDCAN_ID_REGION_ADD, IOCTL_ESDCAN_ID_REGION_DEL, IOCTL_ESDCAN_SET_TX_TS_WIN, IOCTL_ESDCAN_GET_TX_TS_WIN, IOCTL_ESDCAN_SET_TX_TS_TIMEOUT, * IOCTL_ESDCAN_GET_TX_TS_TIMEOUT, IOCTL_ESDCAN_SET_HND_FILTER * * Revision 1.145 2013/01/03 16:21:00 andreas * Updated copyright notice * * Revision 1.144 2012/11/08 14:14:42 andreas * Fixed bug on handle close (two threads entering driver on same handle with ioctl_destroy) * * Revision 1.143 2012/02/17 18:53:57 andreas * Updated copyright * * Revision 1.142 2011/11/01 15:31:57 andreas * Waitqueue wqRx in CAN_NODE (used for select feature) got renamed to * wqRxNotify, when merging with preempt_rt branch * * Revision 1.141 2011/09/06 17:18:10 manuel * Fixed rcsid (for newer gcc) * * Revision 1.140 2011/08/31 12:50:43 manuel * Added EEI stuff * * Revision 1.139 2011/08/05 15:47:05 manuel * Beautified debug output only * * Revision 1.138 2011/07/12 17:37:42 manuel * From 2.6.19 on, the irq handler has no more pt_regs. * Fix for missing path_lookup in 2.6.39. * * Revision 1.137 2011/07/05 10:34:04 michael * nodes rx-queuesize can be configured. At the moment only used under nto * * Revision 1.136 2011/06/20 17:44:00 manuel * Added BOARD_SOFT support * * Revision 1.135 2011/05/18 16:01:10 andreas * Changed copyright header * * Revision 1.134 2010/12/15 14:26:14 manuel * Fixed memory leak in can_read_proc_nodeinit * * Revision 1.133 2010/10/26 12:48:56 manuel * There is no more ioctl field in struct file_operations from kernel 2.6.36 on * * Revision 1.132 2010/10/19 12:45:19 manuel * Revised proc dir/file creation; hopefully no more "badness" detections now... * * Revision 1.131 2010/05/21 17:28:05 manuel * Added linux/sched.h include. Needed for kernel 2.6.33 but shouldn't harm for older kernels. * * Revision 1.130 2010/03/16 10:49:44 andreas * Untabified * * Revision 1.129 2010/03/16 10:33:18 andreas * Added esdcan_poll to fops (select implementation) * * Revision 1.128 2010/03/11 12:38:07 manuel * Added sleep if pci405 u-boot update is running * * Revision 1.127 2010/03/09 10:07:22 matthias * Beginning with 2.6.33 linux/autoconf.h moved to generated/autoconf.h. Also there is no need to include it. The kernel's build system passes it via -include option to gcc. * * Revision 1.126 2010/03/08 16:45:58 matthias * Add support for esdcan_of_connector interface * * Revision 1.125 2009/12/04 12:28:37 andreas * Fixed 32-Bit IOCTLs for x86_64-Kernel < 2.6.10 * * Revision 1.124 2009/07/31 14:55:52 andreas * Added IOCTL_ESDCAN_SER_REG_READ and IOCTL_ESDCAN_SER_REG_WRITE * * Revision 1.123 2009/07/06 15:14:17 andreas * Removed IRQF_DISABLED flag * Updated copyright comment * * Revision 1.122 2009/04/01 14:34:03 andreas * Added driver command line parameter "clock". Used to override * timer tick frequency on certain embedded targets. * * Revision 1.121 2009/02/25 16:26:05 andreas * Removed bus statistics proc-file * * Revision 1.120 2008/12/02 13:18:37 andreas * Removed forgotten esdcan_proc_extra_info_-calls * * Revision 1.119 2008/12/02 11:07:39 andreas * Fix/Change: * - proc files were moved into /proc/bus/can/DRIVER_NAME/ * - Fixed problems, when loading different drivers concurrently * - Fixed problems with several identical CAN boards * - removed extrainfo file * * Revision 1.118 2008/11/18 16:00:49 matthias * add pcimsg module parameter * * Revision 1.117 2008/10/29 15:29:57 andreas * Fixed race condition on request_irq, which had pretty bad * consequences with shared interrupts. * * Revision 1.116 2008/09/17 16:42:07 manuel * Added missing MODULE_LICENSE * * Revision 1.115 2008/06/06 14:10:34 andreas * Fixed busload IOCTLs for x86_64 kernels < 2.6.10 * * Revision 1.114 2008/03/20 10:58:36 andreas * Fixed warning regarding deprecated IRQ flags * Changed IRQ flags to work with kernels >= 2.6.25 * * Revision 1.113 2007/11/09 16:33:32 manuel * Fix for newer kernels where ioctl32.h doesn't exist * * Revision 1.112 2006/12/22 09:59:24 andreas * Fixed for kernels 2.6.19 * Exchanged include order of version.h and config.h/autoconf.h * Including autoconf.h instead of config.h for kernels >= 2.6.19 * Added generation of inodeinit-script in /proc/bus/can/ * Currently this feature is for internal use, only and not documented * * Revision 1.111 2006/11/22 10:37:32 andreas * Added message to syslog, after a PCI405-Firmware update * * Revision 1.110 2006/11/13 11:35:08 matthias * added newline when last net number is printed * * Revision 1.109 2006/10/12 09:53:36 andreas * Replaced some forgotten CANIO_-error codes with the OSIF_ counterparts * Replaces some errnos with their OSIF_counterparts * Cleaned up return of error codes to user space, * please use positive error codes, only!!! * * Revision 1.108 2006/10/11 10:12:48 andreas * Fixed compilation problem with SuSE > 10.0 * * Revision 1.107 2006/08/17 13:26:59 michael * Rebirth of OSIF_ errorcodes * * Revision 1.106 2006/07/11 15:13:58 manuel * Replaced nuc_timestamp with data from CAN_STAT structure in can_read_proc * * Revision 1.105 2006/07/04 12:41:05 andreas * Added missing IOCTL_ESDCAN_SET_ALT_RTR_ID * * Revision 1.104 2006/06/29 11:53:17 andreas * Added module load parameter "errorinfo" to disable extended error info * * Revision 1.103 2006/06/27 13:12:43 andreas * Exchanged OSIF_errors with CANIO_errors * * Revision 1.102 2006/06/27 10:00:45 andreas * Removed usage of nuc_baudrate_get() * Moved baud_table into nucleus * Added TODO about timestamps on baudrate change events * * Revision 1.101 2006/04/28 12:30:36 andreas * Added warning in syslog, if debug driver * Changes to support recent kernel (>2.6.13) * Added usage of compat_ioctl and unlocked_ioctl * * Revision 1.100 2006/02/14 09:20:52 matthias * Don't use macros for esdcan_un/register_ioctl32 and * others when these functions are not used. Use empty * functions instead. This avoid compiler warnings * from gcc 4.x * * Revision 1.99 2005/12/08 11:35:26 andreas * For kernels below 2.4.0 legacy PCI support is used * instead of hotplugging * * Revision 1.98 2005/12/06 13:26:10 andreas * No functional changes. Removed old "#if 0" path and * small cleanup. * * Revision 1.97 2005/11/14 13:45:30 manuel * Added #if PLATFORM_64BIT around esdcan_register_ioctl32 * and esdcan_unregister_ioctl32 prototypes * * Revision 1.96 2005/11/02 07:12:46 andreas * Added IOCTL_ESDCAN_SET_20B_HND_FILTER (de-)registration * for 64-Bit platforms * * Revision 1.95 2005/10/06 07:39:17 matthias * temporarily disabled nuc_timestamp call for proc interface * * Revision 1.94 2005/08/29 14:33:48 andreas * Fixed bug in release of memory regions * * Revision 1.93 2005/07/29 08:19:43 andreas * crd-structure stores pointer (pCardIdent) into cardFlavours * structure instead of index (flavour), now * * Revision 1.92 2005/07/28 08:07:30 andreas * Separated initialization of different board types (pci, raw, usb,...). * From now on this file contains function common to all (or at least several) * board types. Everything specific to one board type is located in esdcan_pci.c, * esdcan_raw.c, esdcan_usb.c or esdcan_pci_legacy.c. * BOARD and BOARD_NAME defines have been removed. There's a ESDCAN_DRIVER_NAME defined * in each boardrc.h. * There's also an array cardFlavours defined in boardrc.c, which provides the * "spaces" and "irq" arrays, board name and type specific IDs for all boards supported * by the same driver binary. This means at least for PCI and hotplug PCI the driver * can support several different devices, now. * Bugfixes in ISA-initialization (behaviour, if more than one address space is defined), * located in esdcan_raw.c, now. * * Revision 1.91 2005/04/25 07:29:49 andreas * Fixed bug (irrelevant, since feature isn't used until now) in ISA module paramters * * Revision 1.90 2005/04/20 13:44:20 andreas * Changed for 64-Bit Linux (ioctl registration, C-types) * Cleanup * * Revision 1.89 2005/03/04 08:41:16 andreas * Added cpci200 * * Revision 1.88 2005/02/21 15:24:12 matthias * -because CM-size increased we have to copy CMSG and CMSG_T struct from/to userspace * -added pci405fw2 * -removed unused code * * Revision 1.87 2004/11/15 13:29:52 matthias * added cpci750 support * * Revision 1.86 2004/11/10 14:33:03 michael * Compilable with versioned symbols again * * Revision 1.85 2004/09/23 14:49:32 andreas * forgot to remove verbose-preset * * Revision 1.84 2004/09/23 14:48:17 andreas * Moved most of the USB code to esdcan_usb.c * Changed debug output to dprint * * 11.05.04 - Added OSIF_CALLTYPE, where needed * Removed warning (passing param 4 of nuc_extra_info) ab * 07.05.04 - Changes for kernel 2.6: * - module-parameters (and description) * - module open count * - check_region -> request_region * - EXPORT_NO_SYMBOLS removed * Some cleanup ab * 07.04.04 - changed major of gitane to 54 ab * 11.03.04 - added Gitane and GitaneLite majors * added IO-space mapping for PCI-cards ab * 17.12.03 - added pci266 ab * 01.12.03 - resetting USB-modules on driver-unload * some more small corrections for USB-modules ab * 26.11.03 - ifdefed release_region for kernel < 2.4.0 ab * 13.11.03 - USB331-Support added (THIS IS STILL BETA!!!) * USB-specific stuff is implemented here, to be able * reimplement USB-stuff for other systems. * There are NO effects for non-USB-cards. Nevertheless * some cleanup is still needed. ab * 05.11.03 - Added support for four subvendor and subsystem-IDs ab * 27.10.03 - Corrected usage of print-macros * Added verbose module parameter ab * 29.09.03 - read/write: get node-mutex before common call * (same as IRIX IOCTRL) sr * 05.09.03 - improved module parameter handling for irq and io * (only for RAW_BOARDS) * a) irq arg can be terminated by -1: irq=25,-1 * b) io arg can be temrinated by 0: io=0xf0000000,0 mf * 03.06.03 - undo change from 21.05.03 mf * 21.05.03 - release irq when nuc_node_attach failed (0.3.3) mf * 15.01.03 - common driver part extracted "../esdcan_common.c" sr * 18.11.02 - added callback interface for nucleus mf * 07.11.02 - Version 0.1.1 mf * 21.05.02 - added hardware timestamping (Version 0.1.0) mf * 17.05.02 - first release (Version 0.1.0) mf * 02.05.02 - first version mf */ /************************************************************************ * * Copyright (c) 1996 - 2015 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd.eu * Germany sales@esd.eu * *************************************************************************/ /*! \file esdcan.c \brief Linux driver entries This file contains the Linux entries for the esd CAN driver. */ #include <linux/version.h> #if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32)) # if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19)) # include <linux/autoconf.h> # else /* #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19)) */ # include <linux/config.h> # endif /* #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19)) */ #endif /* #if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32)) */ #ifdef DISTR_SUSE # undef CONFIG_MODVERSIONS #endif /* #ifdef DISTR_SUSE */ #ifdef CONFIG_MODVERSIONS # if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # include <config/modversions.h> # else /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ # include <linux/modversions.h> # endif /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ # ifndef MODVERSIONS # define MODVERSIONS # endif /* #ifndef MODVERSIONS */ #endif /* #ifdef CONFIG_MODVERSIONS */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/init.h> #include <linux/pci.h> #include <linux/proc_fs.h> #include <linux/interrupt.h> #include <linux/poll.h> #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # include <linux/moduleparam.h> # if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) # include <linux/ioctl32.h> # endif /* #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,21) */ #endif /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,0) # include <linux/ioport.h> #endif /* #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,0) */ #ifndef OSIF_OS_RTAI # include <asm/uaccess.h> #endif /* #ifndef OSIF_OS_RTAI */ #ifdef LTT # warning "Tracing enabled" # include <linux/trace.h> #endif /* #ifdef LTT */ #include <linux/sched.h> #include <nucleus.h> #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) # if defined(BOARD_PCI) # define ESDCAN_PCI_HOTPLUG # undef BOARD_PCI /* Disable legacy PCI support */ # endif /* #if defined(BOARD_PCI) */ #endif /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) */ #if defined(BOARD_USB) || defined(ESDCAN_PCI_HOTPLUG) # define ESDCAN_HOTPLUG_DRIVER #endif /* #if defined(BOARD_USB) || defined(ESDCAN_PCI_HOTPLUG) */ #if defined (BOARD_USB) # if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,0) # include <linux/usb.h> # endif /* #if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,0) */ #endif /* #if defined (BOARD_USB) */ #if defined (BOARD_VME) # include <linux/vme.h> # define ESDCAN_HOTPLUG_DRIVER #endif /* #if defined (BOARD_VME) */ #ifdef ESDDBG # define CAN_DEBUG #endif /* #ifdef ESDDBG */ #ifdef CAN_DEBUG # define CAN_DBG(fmt) OSIF_DPRINT(fmt) /*!< Macro for debug prints */ # define CAN_IRQ_DBG(fmt) OSIF_DPRINT(fmt) /*!< Macro for debug prints on interrupt-level */ #else /* #ifdef CAN_DEBUG */ # define CAN_DBG(fmt) /**< Empty expression */ # define CAN_IRQ_DBG(fmt) /**< Empty expression */ #endif /* #ifdef CAN_DEBUG */ #define CAN_PRINT(fmt) OSIF_PRINT(fmt) /**< Makro for output to the general user (NOT surpressed in release version) */ #define CAN_DPRINT(fmt) OSIF_DPRINT(fmt) /**< Makro for output to the general user (filtered by verbose level) */ #define CAN_IRQ_PRINT(fmt) OSIF_DPRINT(fmt) /**< Makro for output to the general user on interrupt level (NOT surpressed in release version) */ #define ESDCAN_ZONE_INIFU OSIF_ZONE_ESDCAN|OSIF_ZONE_INIT|OSIF_ZONE_FUNC #define ESDCAN_ZONE_INI OSIF_ZONE_ESDCAN|OSIF_ZONE_INIT #define ESDCAN_ZONE_FU OSIF_ZONE_ESDCAN|OSIF_ZONE_FUNC #define ESDCAN_ZONE OSIF_ZONE_ESDCAN #define ESDCAN_ZONE_IRQ OSIF_ZONE_IRQ /* DO NOT USE ANY MORE BITS (nto will thank you:) */ #define ESDCAN_ZONE_ALWAYS 0xFFFFFFFF #define ESDCAN_ZONE_WARN OSIF_ZONE_ESDCAN|OSIF_ZONE_WARN #ifdef LTT INT32 can_ltt0; UINT8 can_ltt0_byte; #endif /* #ifdef LTT */ /* module parameter verbose: default changes regarding to debug flag */ #ifndef CAN_DEBUG /* * The released driver writes load- and unload-messages to syslog, * if the user hasn't specified a verbose level. */ uint verbose = 0x00000001; #else /* #ifndef CAN_DEBUG */ /* * The debug-version of the driver writes all "release-version"-output * and warning- and error-messages, if the developer doesn't specify * otherwise. */ /* uint verbose = 0xF8F00001; */ /* AB setting */ /* uint verbose = 0xF7FFFFFF; */ /* AB all but IRQ */ /* uint verbose = (0xF7FFFFFF & (~OSIF_ZONE_FILTER)); */ /* AB all but IRQ and NUC (filter) */ /* uint verbose= (OSIF_ZONE_CTRL|OSIF_ZONE_BACKEND); */ uint verbose = 0xC00000FF; #endif /* #ifndef CAN_DEBUG */ unsigned int major = MAJOR_LINUX; /* MAJOR_LINUX is set in .cfg files */ VOID esdcan_show_card_info( CAN_CARD *crd ); VOID esdcan_show_card_info_all( VOID ); VOID esdcan_show_driver_info( VOID ); INT32 can_attach_common(CAN_CARD *crd); CAN_NODE *nodes[MAX_CARDS * NODES_PER_CARD]; /* index: minor */ int mode = 0; int errorinfo = 1; int pcimsg = 1; int clock = 0; int txtswin = TX_TS_WIN_DEF; #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) /* common module parameter */ module_param(major, uint, 0); MODULE_PARM_DESC(major, "major number to be used for the CAN card"); module_param(mode, int, 0); /* e.g. LOM */ MODULE_PARM_DESC(mode, "activate certain driver modes, e.g. LOM"); module_param(verbose, uint, 0); /* mask for output selection */ MODULE_PARM_DESC(verbose, "change verbose level of driver"); module_param(errorinfo, int, 0); /* flag for extended error info */ MODULE_PARM_DESC(errorinfo, "enable/disable extended error info (default: on)"); unsigned int compat32 = 1; module_param(compat32, int, 0); /* setting this to zero disables 32-bit compatibility on 64-bit systems */ MODULE_PARM_DESC(compat32, "disable 32-Bit compatibility on 64-Bit systems"); #if defined(BOARD_PCI) || defined(ESDCAN_PCI_HOTPLUG) module_param(pcimsg, int, 0); /* enable/disable pcimsg interface on firmware drivers */ MODULE_PARM_DESC(pcimsg, "enable/disable pcimsg interface on firmware drivers (default: on)"); #endif /* defined(BOARD_PCI) || defined(ESDCAN_PCI_HOTPLUG) */ module_param(clock, int, 0); /* override TS tick frequency */ MODULE_PARM_DESC(clock, "LEAVE THIS ONE ALONE, works with special hardware, only"); #ifdef NUC_TX_TS module_param(txtswin, int, 0); /* override TX TS window size (ms) */ MODULE_PARM_DESC(txtswin, "override default TX-TS-window size (in ms)"); #endif /* #ifdef NUC_TX_TS */ #else /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ /* common module parameter */ MODULE_PARM(major, "1i"); MODULE_PARM(mode, "1i"); /* e.g. LOM */ MODULE_PARM(verbose, "1i"); /* mask for output selection */ MODULE_PARM(errorinfo, "1i"); /* enable/disable extended error info (default: on) */ #if defined(BOARD_PCI) || defined(ESDCAN_PCI_HOTPLUG) MODULE_PARM(pcimsg, "1i"); /* enable/disable pcimsg interface on firmware drivers */ #endif /* defined(BOARD_PCI) || defined(ESDCAN_PCI_HOTPLUG) */ MODULE_PARM(clock, "1i"); /* override TS tick frequency */ #ifdef NUC_TX_TS MODULE_PARM(txtswin, "1i"); /* override TX TS window size (ms) */ #endif /* #ifdef NUC_TX_TS */ #endif /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # define INODE2CANNODE(inode) (iminor(inode)) #else /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ # define INODE2CANNODE(inode) (MINOR(inode->i_rdev) & 0xff) #endif /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ /* BL: Actually came into kernel.org with 2.6.18, * from 2.6.25 it is mandatory (old defines removed) * In 2.6.22 "deprecated warnings" came in */ # if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)) # if defined(ESDCAN_SPECIAL_IRQ_FLAGS) /* see e.g. mcp2515/cpuca8/boardrc.h */ # define ESDCAN_IRQ_FLAGS ESDCAN_SPECIAL_IRQ_FLAGS # else /* #if defined(ESDCAN_SPECIAL_IRQ_FLAGS) */ # define ESDCAN_IRQ_FLAGS IRQF_SHARED # endif /* #if defined(ESDCAN_SPECIAL_IRQ_FLAGS) */ # else /* #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)) */ # define ESDCAN_IRQ_FLAGS SA_SHIRQ | SA_INTERRUPT # endif /* #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)) */ #ifdef OSIF_OS_LINUX #define ESDCAN_IOCTL_PROTO \ static int esdcan_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg) # if (PLATFORM_64BIT) && (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,10)) static long esdcan_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg); # endif /* #if (PLATFORM_64BIT) && (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,10)) */ # if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,10) static long esdcan_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg); # endif /* #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,10) */ #endif /* OSIF_OS_LINUX */ #ifdef OSIF_OS_RTAI #define ESDCAN_IOCTL_PROTO \ INT32 esdcan_ctrl(INT32 hnd, UINT32 cmd, UINT32 arg) #endif /* OSIF_OS_RTAI */ static unsigned int esdcan_poll(struct file *pFile, struct poll_table_struct *pPollTable); static int esdcan_open(struct inode *inode, struct file *file); static int esdcan_release(struct inode *inode, struct file *file); ESDCAN_IOCTL_PROTO; void esdcan_unregister_ioctl32(void); int32_t esdcan_register_ioctl32(void); #define RETURN_TO_USER(ret) return(-ret) #ifndef OSIF_OS_RTAI struct file_operations esdcan_fops = { #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,0) NULL, NULL, NULL, NULL, NULL, /* no support of poll/select planned for 2.2.x */ esdcan_ioctl, NULL, esdcan_open, NULL, esdcan_release, NULL, NULL, NULL, NULL, NULL #elif LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) owner: THIS_MODULE, /* poll: esdcan_poll, */ /* no support for poll/select on 2.4.x, yet */ ioctl: esdcan_ioctl, open: esdcan_open, release: esdcan_release, #else /* LINUX_VERSION_CODE < KERNEL_VERSION(2,4,0) */ .owner = THIS_MODULE, .poll = esdcan_poll, # if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,36) .ioctl = esdcan_ioctl, # endif /* #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,36) */ # if (PLATFORM_64BIT) && (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,10)) .compat_ioctl = esdcan_compat_ioctl, # endif /* #if (PLATFORM_64BIT) && (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,10)) */ # if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,10) .unlocked_ioctl = esdcan_unlocked_ioctl, # endif /* #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,10) */ .open = esdcan_open, .release = esdcan_release, #endif /* LINUX_VERSION_CODE < KERNEL_VERSION(2,4,0) */ }; #endif /* OSIF_OS_RTAI */ #define PROCFN_LEN 30 #define PROC_NODEINIT #if (defined PROC_NODEINIT) && ( LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) ) && CONFIG_PROC_FS #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) #include <linux/namei.h> #else /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ #include <linux/fs.h> #endif /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ static UINT8 procfn_nodeinit[PROCFN_LEN]; static UINT8 procfn_cardpath[PROCFN_LEN]; static int esdcan_path_check(const char *name) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,39) struct path p; return kern_path(name, 0, &p); #else /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,39) */ struct nameidata nd; return path_lookup(name, 0, &nd); #endif /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,39) */ } #if LINUX_VERSION_CODE >= KERNEL_VERSION(3,8,0) /* the new way: provide file_ops table to proc_create() */ #include <linux/seq_file.h> static int esdcan_proc_show(struct seq_file *m, void *v) { int n, num = 0; seq_printf(m, "#!/bin/sh\n"); for (n = 0; n < MAX_CARDS * NODES_PER_CARD; n++) { CAN_NODE *node = nodes[n]; if ( node ) { num++; seq_printf(m,"net_num=$((${1}+%d))\n", node->net_no); seq_printf(m,"test -e /dev/can${net_num} || mknod -m 666 /dev/can${net_num} c %d %d\n", major, node->net_no); } } if ( !num ) { seq_printf(m,"echo \"No CAN card found!\"\n"); } return 0; } static int esdcan_proc_open(struct inode *inode, struct file *file) { return single_open(file, esdcan_proc_show, NULL); } static const struct file_operations esdcan_proc_file_ops = { .owner = THIS_MODULE, .open = esdcan_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #define ESDCAN_USE_PROC_CREATE #else /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(3,8,0) */ /* the old way: provide the following function to create_proc_read_entry() */ int can_read_proc_nodeinit(char *buf, char **start, off_t offset, int count, int *eof, void *data) { CAN_NODE **nodes = (CAN_NODE**)data; INT32 len = 0, num = 0, result; int n; char *tmp_buf; const int BUFSIZE = 4096; CAN_DBG((ESDCAN_ZONE_INI, "%s: buf: 0x%08X, start: 0x%08X, offs: %d, count: %d, eof: %d\n", OSIF_FUNCTION, buf, start, offset, count, *eof)); result = OSIF_MALLOC(BUFSIZE, &tmp_buf); if(OSIF_SUCCESS != result) { *eof = 1; return 0; } len += snprintf(tmp_buf+len, BUFSIZE-len, "#!/bin/sh\n"); for (n = 0; n < MAX_CARDS * NODES_PER_CARD; n++) { CAN_NODE *node = nodes[n]; if ( node ) { if ( 80 >= (BUFSIZE-len) ) { /* shouldn't happen */ CAN_DBG((ESDCAN_ZONE_INI, "%s: Not enough memory for inode script!\n", OSIF_FUNCTION)); break; } num++; len += snprintf(tmp_buf+len, BUFSIZE-len, "net_num=$((${1}+%d))\n", node->net_no); len += snprintf(tmp_buf+len, BUFSIZE-len, "test -e /dev/can${net_num} || mknod -m 666 /dev/can${net_num} c %d %d\n", major, node->net_no); } } if ( !num ) { len += snprintf(tmp_buf+len, BUFSIZE-len, "echo \"No CAN card found!\"\n"); } CAN_DBG((ESDCAN_ZONE_INI, "%s: complete script len: %d\n", OSIF_FUNCTION, len)); if ((offset+count) >= len) { *eof = 1; len -= offset; } else { len = count; } OSIF_MEMCPY(buf+offset, tmp_buf+offset, len); OSIF_FREE(tmp_buf); CAN_DBG((ESDCAN_ZONE_INI, "%s: len: %d, eof: %d\n", OSIF_FUNCTION, len, *eof)); return offset+len; } #endif /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(3,8,0) */ void esdcan_proc_nodeinit_create(void) { int err; char sPath[PROCFN_LEN+6]; OSIF_SNPRINTF((procfn_nodeinit, PROCFN_LEN, "bus/can/%s/inodes", ESDCAN_DRIVER_NAME)); OSIF_SNPRINTF((procfn_cardpath, PROCFN_LEN, "bus/can/%s" , ESDCAN_DRIVER_NAME)); CAN_DBG((ESDCAN_ZONE_INI, "%s: creating proc entry (%s)\n", OSIF_FUNCTION, procfn_nodeinit)); /* create /proc/bus/can */ err = esdcan_path_check("/proc/bus/can"); if (err) { struct proc_dir_entry *ent; ent=proc_mkdir("bus/can", NULL); if (ent==NULL) { CAN_PRINT(("%s: error creating proc entry (%s)\n", OSIF_FUNCTION, "bus/can")); procfn_nodeinit[0]=0; procfn_cardpath[0]=0; return; } } /* create /proc/bus/can/<DRIVER_NAME> */ OSIF_SNPRINTF((sPath, PROCFN_LEN+6,"/proc/%s", procfn_cardpath)); err = esdcan_path_check(sPath); if (err) { struct proc_dir_entry *ent; ent=proc_mkdir(procfn_cardpath, NULL); if (ent==NULL) { CAN_PRINT(("%s: error creating proc entry (%s)\n", OSIF_FUNCTION, procfn_cardpath)); procfn_nodeinit[0]=0; procfn_cardpath[0]=0; return; } } /* create /proc/bus/can/<DRIVER_NAME>/inodes */ #ifdef ESDCAN_USE_PROC_CREATE if (!proc_create( procfn_nodeinit, S_IFREG | S_IRUGO | S_IXUSR, /* read all, execute user */ NULL /* parent dir */, &esdcan_proc_file_ops)) { #else /* #ifdef ESDCAN_USE_PROC_CREATE */ if (!create_proc_read_entry( procfn_nodeinit, 0x16D /* default mode */, NULL /* parent dir */, can_read_proc_nodeinit, (VOID*)nodes /* arg */)) { #endif /* #ifdef ESDCAN_USE_PROC_CREATE */ CAN_PRINT(("%s: error creating proc entry (%s)\n", OSIF_FUNCTION, procfn_nodeinit)); procfn_nodeinit[0]=0; } } void esdcan_proc_nodeinit_remove(void) { if (procfn_nodeinit[0]) { CAN_DBG((ESDCAN_ZONE_INI, "%s: removing proc entry %s\n", OSIF_FUNCTION, procfn_nodeinit)); remove_proc_entry(procfn_nodeinit, NULL); procfn_nodeinit[0]=0; } if (procfn_cardpath[0]) { CAN_DBG((ESDCAN_ZONE_INI, "%s: removing proc entry %s\n", OSIF_FUNCTION, procfn_cardpath)); remove_proc_entry(procfn_cardpath, NULL); procfn_cardpath[0]=0; } } #else /* #if (defined PROC_NODEINIT) && ( LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) ) && CONFIG_PROC_FS */ void esdcan_proc_nodeinit_create(void) {} void esdcan_proc_nodeinit_remove(void) {} #endif /* #if (defined PROC_NODEINIT) && ( LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) ) && CONFIG_PROC_FS */ #if (PLATFORM_64BIT) && (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,10)) static int esdcan_ioctl_32(unsigned int fd, unsigned int cmd, unsigned long arg, struct file *file); void esdcan_unregister_ioctl32(void) { if (compat32) { UNREGISTER_IOCTL_32(IOCTL_ESDCAN_CREATE); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_ID_RANGE_ADD); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_ID_RANGE_DEL); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_BAUD); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_TIMEOUT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SEND); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TAKE); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_DEBUG); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BAUD); UNREGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_DESTROY); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_DESTROY_DEPRECATED); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TX_ABORT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_RX_ABORT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_CREATE); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_UPDATE); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_DESTROY); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_RX_OBJ); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_READ); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_WRITE); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_UPDATE); UNREGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_FLUSH_RX_FIFO); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_FLUSH_RX_FIFO_DEPRECATED); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_RX_MESSAGES); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_RX_TIMEOUT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TX_TIMEOUT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TIMESTAMP_FREQ); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TIMESTAMP); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TICKS_FREQ); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TICKS); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SEND_T); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_WRITE_T); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TAKE_T); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_READ_T); UNREGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_PURGE_TX_FIFO); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_PURGE_TX_FIFO_DEPRECATED); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_RX_TIMEOUT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_TX_TIMEOUT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_FEATURES); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_SCHEDULE); UNREGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_TX_OBJ_SCHEDULE_START); UNREGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_TX_OBJ_SCHEDULE_STOP); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_20B_HND_FILTER); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_SERIAL); UNREGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_SET_ALT_RTR_ID); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_BUSLOAD_INTERVAL); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BUSLOAD_INTERVAL); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BITRATE_DETAILS); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BUS_STATISTIC); UNREGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_RESET_BUS_STATISTIC); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_ERROR_COUNTER); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SER_REG_READ); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SER_REG_WRITE); UNREGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_RESET_CAN_ERROR_CNT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_ID_REGION_ADD); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_ID_REGION_DEL); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_TX_TS_WIN); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TX_TS_WIN); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_TX_TS_TIMEOUT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TX_TS_TIMEOUT); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_HND_FILTER); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_CREATE); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_DESTROY); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_STATUS); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_CONFIGURE); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_START); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_STOP); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_TRIGGER_NOW); UNREGISTER_IOCTL_COMPAT(IOCTL_CAN_SET_QUEUESIZE); /* special ioctl (from candev driver) for driver version detection */ UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SEND_X); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_WRITE_X); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_TAKE_X); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_READ_X); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_SET_BAUD_X); UNREGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BAUD_X); } } int32_t esdcan_register_ioctl32(void) { int32_t result = 0; if (compat32) { /* register 32-bit ioctls */ REGISTER_IOCTL_32(IOCTL_ESDCAN_CREATE, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_ID_RANGE_ADD, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_ID_RANGE_DEL, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SET_BAUD, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SET_TIMEOUT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SEND, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TAKE, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_DEBUG, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BAUD, result); REGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_DESTROY, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_DESTROY_DEPRECATED, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TX_ABORT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_RX_ABORT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_CREATE, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_UPDATE, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_DESTROY, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_RX_OBJ, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_READ, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_WRITE, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_UPDATE, result); REGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_FLUSH_RX_FIFO, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_FLUSH_RX_FIFO_DEPRECATED, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_RX_MESSAGES, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_RX_TIMEOUT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TX_TIMEOUT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TIMESTAMP_FREQ, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TIMESTAMP, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TICKS_FREQ, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TICKS, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SEND_T, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_WRITE_T, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TAKE_T, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_READ_T, result); REGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_PURGE_TX_FIFO, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_PURGE_TX_FIFO_DEPRECATED, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SET_RX_TIMEOUT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SET_TX_TIMEOUT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_FEATURES, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TX_OBJ_SCHEDULE, result); REGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_TX_OBJ_SCHEDULE_START, result); REGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_TX_OBJ_SCHEDULE_STOP, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SET_20B_HND_FILTER, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_SERIAL, result); REGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_SET_ALT_RTR_ID, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SET_BUSLOAD_INTERVAL, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BUSLOAD_INTERVAL, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BITRATE_DETAILS, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BUS_STATISTIC, result); REGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_RESET_BUS_STATISTIC, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_ERROR_COUNTER, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SER_REG_READ, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SER_REG_WRITE, result); REGISTER_IOCTL_COMPAT(IOCTL_ESDCAN_RESET_CAN_ERROR_CNT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_ID_REGION_ADD, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_ID_REGION_DEL, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SET_TX_TS_WIN, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TX_TS_WIN, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SET_TX_TS_TIMEOUT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_TX_TS_TIMEOUT, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_CREATE, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_DESTROY, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_STATUS, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_CONFIGURE, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_START, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_STOP, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_EEI_TRIGGER_NOW, result); REGISTER_IOCTL_COMPAT(IOCTL_CAN_SET_QUEUESIZE, result); /* special ioctl (from candev driver) for driver version detection */ REGISTER_IOCTL_32(IOCTL_ESDCAN_SEND_X, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_WRITE_X, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_TAKE_X, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_READ_X, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_SET_BAUD_X, result); REGISTER_IOCTL_32(IOCTL_ESDCAN_GET_BAUD_X, result); if ( 0 != result ) { CAN_PRINT(("esd CAN driver: An ioctl collides with an ioctl of another!\n")); CAN_PRINT(("esd CAN driver: driver on your system!\n")); CAN_PRINT(("esd CAN driver: Since this is a problem of the 32-bit compatibility\n")); CAN_PRINT(("esd CAN driver: layer of linux, you can still load the driver with\n")); CAN_PRINT(("esd CAN driver: module parameter \"compat32=0\", but you won't be\n")); CAN_PRINT(("esd CAN driver: able to use 32-bit applications.\n")); esdcan_unregister_ioctl32(); } } return result; } #else /* #if (PLATFORM_64BIT) && (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,10)) */ int32_t esdcan_register_ioctl32(void) {return 0;} void esdcan_unregister_ioctl32(void) {} #endif /* #if (PLATFORM_64BIT) && (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,10)) */ /* * The following includes contain system-specific code, which helps to reduce code * duplication and ifdefs for different hardware. */ #if defined (BOARD_USB) # if defined(OSIF_OS_LINUX) # include "esdcan_usb.c" # else /* #if defined(OSIF_OS_LINUX) */ # error "Currently USB is implemented for Linux, only!" # endif /* #if defined(OSIF_OS_LINUX) */ #elif defined(ESDCAN_PCI_HOTPLUG) # include "esdcan_pci.c" #elif defined(BOARD_SPI) # include "esdcan_spi.c" #elif defined(BOARD_RAW) # include "esdcan_raw.c" #elif defined(BOARD_PCI) # include "esdcan_pci_legacy.c" #elif defined(BOARD_VME) # include "esdcan_vme.c" #elif defined(BOARD_SOFT) # include "esdcan_soft.c" #else /* #if defined (BOARD_USB) */ # error "Board type not properly defined!!!" #endif /* #if defined (BOARD_USB) */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19) static irqreturn_t irq_stub( int irq, void *arg ) { return ((CARD_IRQ*)arg)->handler(((CARD_IRQ*)arg)->context); } #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) static irqreturn_t irq_stub( int irq, void *arg, struct pt_regs* regs ) { return ((CARD_IRQ*)arg)->handler(((CARD_IRQ*)arg)->context); } #else static void irq_stub( int irq, void *arg, struct pt_regs* regs ) { ((CARD_IRQ*)arg)->handler(((CARD_IRQ*)arg)->context); return; } #endif #include "esdcan_common.c" /* include common part of unix system layer */ #ifdef OSIF_OS_LINUX static int esdcan_open(struct inode *inode, struct file *file) { CAN_DBG((ESDCAN_ZONE_FU, "%s: pre LOCK\n", OSIF_FUNCTION)); HOTPLUG_GLOBAL_LOCK; # if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) MOD_INC_USE_COUNT; # endif /* # if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) */ CAN_DBG((ESDCAN_ZONE_FU, "%s: enter\n", OSIF_FUNCTION)); file->private_data = 0; HOTPLUG_GLOBAL_UNLOCK; CAN_DBG((ESDCAN_ZONE_FU, "%s: leave\n", OSIF_FUNCTION)); RETURN_TO_USER(OSIF_SUCCESS); } #endif /* #ifdef OSIF_OS_LINUX */ #ifdef OSIF_OS_LINUX static int esdcan_release(struct inode *inode, struct file *file) { INT32 result = OSIF_SUCCESS; CAN_OCB *ocb = (CAN_OCB*)file->private_data; CAN_DBG((ESDCAN_ZONE_FU, "%s: enter\n", OSIF_FUNCTION)); if (ocb) { CAN_NODE *node = ocb->node; if ( 0 != HOTPLUG_BOLT_USER_ENTRY( ((CAN_CARD*)node->crd)->p_mod ) ) { /* BL: seems no good, needs rework */ CAN_DBG((ESDCAN_ZONE_FU, "%s: release needs abort!!!\n", OSIF_FUNCTION)); RETURN_TO_USER(result); } OSIF_MUTEX_LOCK(&node->lock); file->private_data = 0; if (!(ocb->close_state & CLOSE_STATE_HANDLE_CLOSED)) { result = ocb_destroy(ocb); } OSIF_FREE(ocb->rx.cmbuf); OSIF_FREE(ocb); OSIF_MUTEX_UNLOCK(&node->lock); HOTPLUG_BOLT_USER_EXIT( ((CAN_CARD*)node->crd)->p_mod ); } # if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) MOD_DEC_USE_COUNT; # endif /* # if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) */ CAN_DBG((ESDCAN_ZONE_FU, "%s: leave\n", OSIF_FUNCTION)); RETURN_TO_USER(result); } #endif /* OSIF_OS_LINUX */ INT32 can_attach_common(CAN_CARD *crd) { VOID *vptr; INT32 idx_node, idx_irq; INT32 result = OSIF_SUCCESS, lastError = OSIF_SUCCESS; CARD_IDENT *pCardIdent; CAN_DBG((ESDCAN_ZONE_INI, "%s: enter (crd=%p)\n", OSIF_FUNCTION, crd)); for(idx_node = 0; idx_node < NODES_PER_CARD; idx_node++) { CAN_NODE *node; result = OSIF_MALLOC(sizeof(*node), &vptr); if(OSIF_SUCCESS != result) { break; } node = (CAN_NODE*)vptr; OSIF_MEMSET(node, 0, sizeof(*node)); node->crd = crd; node->mode = mode; /* insmod parameter */ node->net_no = crd->card_no*NODES_PER_CARD + idx_node; node->node_no = idx_node; init_waitqueue_head(&node->wqRxNotify); if (clock != 0) { node->ctrl_clock = clock; } node->tx_ts_win = txtswin; OSIF_MUTEX_CREATE(&node->lock); OSIF_IRQ_MUTEX_CREATE(&node->lock_irq); crd->node[idx_node] = node; } if( OSIF_SUCCESS != result ) { lastError = result; goto common_attach_1; } result = can_board_attach(crd); if( OSIF_SUCCESS != result ) { lastError = result; if( OSIF_ERESTART == result ) { CAN_PRINT(("esd CAN driver: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")); CAN_PRINT(("esd CAN driver: !!!!! Bootloader update necessary. !!!!!\n")); CAN_PRINT(("esd CAN driver: !!!!! Load a driver with version < 3.9.7 !!!!!\n")); CAN_PRINT(("esd CAN driver: !!!!! to automatically update the bootloader. !!!!!\n")); CAN_PRINT(("esd CAN driver: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")); } goto common_attach_1; /* AB TODO: this leads to an undestroyed crd->lock_irq !!! */ } pCardIdent = crd->pCardIdent; for(idx_irq = 0; (idx_irq < 8) && (pCardIdent->all.irqs[idx_irq].handler != (VOID*)(~0x0)); idx_irq++) { if (NULL == pCardIdent->all.irqs[idx_irq].handler) { continue; } /* BL TODO: timestamps on baudrate change events Idea: force affinity to the same CPU as DPC thread set_ioapic_affinity irq_desc[irq].handler->set_affinity(irq, new_value) UINT32 cpus = num_online_cpus(); cpumask_t mask; cpus_clear(mask); cpus -= 1; cpu_set(cpus, mask); long sched_setaffinity(pid_t pid, cpumask_t new_mask) */ crd->irqs[idx_irq] = pCardIdent->all.irqs[idx_irq]; if (0 != request_irq(crd->irq[idx_irq], (void*)irq_stub, ESDCAN_IRQ_FLAGS, pCardIdent->all.name, &crd->irqs[idx_irq])) { crd->irqs[idx_irq].handler = NULL; crd->irqs[idx_irq].context = NULL; result = CANIO_EBUSY; CAN_DBG((ESDCAN_ZONE_INI, "%s: IRQ request FAILURE: IRQ: %d, Stub: %p, Param: %p\n", OSIF_FUNCTION, crd->irq[idx_irq], (void*)irq_stub, &crd->irqs[idx_irq])); break; } CAN_DBG((ESDCAN_ZONE_INI, "%s: irq requested: IRQ: %d, Stub: %p, Param: %p\n", OSIF_FUNCTION, crd->irq[idx_irq], (void*)irq_stub, &crd->irqs[idx_irq])); } if( OSIF_SUCCESS != result ) { lastError = result; goto common_attach_2; } crd->num_nodes = 0; for( idx_node = 0; idx_node < NODES_PER_CARD; idx_node++ ) { CAN_NODE *node = crd->node[idx_node]; if(NULL == node) { continue; } node->features |= crd->features; CAN_DBG((ESDCAN_ZONE_INI, "%s: calling nuc_node_attach\n", OSIF_FUNCTION)); result = nuc_node_attach( node, 0 ); if (OSIF_SUCCESS != result) { CAN_DBG((ESDCAN_ZONE_INI, "%s: nuc_node_attach failed (%d)\n", OSIF_FUNCTION, result)); OSIF_IRQ_MUTEX_DESTROY( &node->lock_irq ); OSIF_MUTEX_DESTROY( &node->lock ); OSIF_FREE( node ); crd->node[idx_node] = NULL; } nodes[crd->card_no*NODES_PER_CARD + idx_node] = crd->node[idx_node]; if ( NULL == crd->node[idx_node]) { continue; } CAN_DBG((ESDCAN_ZONE_INI, "%s: Node attached (features=%08x)\n", OSIF_FUNCTION, node->features)); ++crd->num_nodes; } if( 0 == crd->num_nodes ) { CAN_DBG((ESDCAN_ZONE_INI, "%s: no node working\n", OSIF_FUNCTION)); lastError = result; goto common_attach_3; } result = can_board_attach_final(crd); if( OSIF_SUCCESS != result ) { lastError = result; goto common_attach_3; } CAN_DBG((ESDCAN_ZONE_INI, "%s: leave (result=%d)\n", OSIF_FUNCTION, result)); return result; common_attach_3: CAN_DBG((ESDCAN_ZONE_INI, "%s: common_attach_3: can_board_attach_final or nuc_node_attach failed\n", OSIF_FUNCTION)); for( idx_node = 0; idx_node < NODES_PER_CARD; idx_node++ ) { CAN_NODE *node = crd->node[idx_node]; if ( NULL == node ) { continue; } nodes[crd->card_no * NODES_PER_CARD + idx_node] = NULL; nuc_node_detach( node ); } common_attach_2: CAN_DBG((ESDCAN_ZONE_INI, "%s: common_attach_2: Failed to request IRQ\n", OSIF_FUNCTION)); for( idx_irq = 0; (idx_irq < 8) && (pCardIdent->all.irqs[idx_irq].handler != (VOID*)(-1)); idx_irq++ ) { if( NULL != crd->irqs[idx_irq].context ) { free_irq(crd->irq[idx_irq], &crd->irqs[idx_irq]); } } can_board_detach(crd); common_attach_1: CAN_DBG((ESDCAN_ZONE_INI, "%s: common_attach_1: Allocation of node-struct or can_board_attach failed\n", OSIF_FUNCTION)); for( idx_node-- /* current idx did't get the mem */; idx_node >= 0; idx_node--) { CAN_NODE *node = crd->node[idx_node]; if ( NULL == node ) { continue; } OSIF_IRQ_MUTEX_DESTROY(&node->lock_irq); OSIF_MUTEX_DESTROY(&node->lock); OSIF_FREE(node); } CAN_DBG((ESDCAN_ZONE_INI, "%s: leave (error=%d)\n", OSIF_FUNCTION, lastError)); return lastError; } VOID can_detach_common( CAN_CARD *crd, INT32 crd_no ) { UINT32 j; CARD_IDENT *pCardIdent = crd->pCardIdent; CAN_DBG((ESDCAN_ZONE_INI, "%s: enter\n", OSIF_FUNCTION)); can_board_detach(crd); for ( j = 0; (j < 8) && ((VOID *)(~0x0) != pCardIdent->all.irqs[j].handler); j++ ) { if ( NULL != crd->irqs[j].context ) { free_irq(crd->irq[j], &crd->irqs[j]); CAN_DBG((ESDCAN_ZONE_INI, "%s:%d: free irq IRQ: %d\n", OSIF_FUNCTION, j, crd->irq[j])); } } for ( j = 0; j < NODES_PER_CARD; j++ ) { CAN_NODE *node = crd->node[j]; if ( NULL == node ) { continue; } nodes[crd_no * NODES_PER_CARD + j] = NULL; nuc_node_detach( node ); OSIF_IRQ_MUTEX_DESTROY( &node->lock_irq); OSIF_MUTEX_DESTROY( &node->lock); OSIF_FREE(node); } CAN_BOARD_DETACH_FINAL(crd); #ifdef ESDCAN_PCI_HOTPLUG for ( j = 0; j < 8; j++ ) { if ( 0 != crd->range[j] ) { if ( pci_resource_flags(crd->pciDev, j) & IORESOURCE_MEM ) { /* Memory space */ iounmap(crd->base[j]); } else if ( pci_resource_flags(crd->pciDev, j) & IORESOURCE_IO ) { /* IO-space */ release_region((UINTPTR)crd->base[j], crd->range[j]); } } } #else /* !ESDCAN_PCI_HOTPLUG */ # ifndef BOARD_SPI for ( j = 0; (j < 8) && (0xFFFFFFFF != pCardIdent->all.spaces[j]); j++ ) { if( 0 != (pCardIdent->all.spaces[j] & 0x00000001) ) { /* if io-space */ # if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) release_region((UINTPTR)crd->base[j], crd->range[j]); # else /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) */ # warning "AB TODO: Still need mechanism to release mem-regions in 2.2.x kernels!!!" # endif /* #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) */ } else { # if !(defined(CONFIG_OF_DEVICE) || defined(ONFIG_OF_FLATTREE)) iounmap(crd->base[j]); # endif /* !(CONFIG_OF_DEVICE || COFIG_OF_FLATTREE)*/ } } # endif /* !BOARD_SPI */ #endif /* ESDCAN_PCI_HOTPLUG */ CAN_DBG((ESDCAN_ZONE_INI, "%s: leave\n", OSIF_FUNCTION)); return; } VOID esdcan_show_card_info( CAN_CARD *crd ) { INT32 i, n; if ( (crd->version_firmware.level != 0) || (crd->version_firmware.revision != 0) || (crd->version_firmware.build != 0) ) { CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: Firmware-version = %1X.%1X.%02X (hex)\n", crd->version_firmware.level, crd->version_firmware.revision, crd->version_firmware.build)); } if ( (crd->version_hardware.level != 0) || (crd->version_hardware.revision != 0) || (crd->version_hardware.build != 0) ) { CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: Hardware-version = %1X.%1X.%02X (hex)\n", crd->version_hardware.level, crd->version_hardware.revision, crd->version_hardware.build)); } else { CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: Hardware-version = 1.0.00\n")); } CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: Card = %d Minor(s) =", crd->card_no)); for ( i = 0, n = 0; NODES_PER_CARD > i; i++ ) { if ( NULL == crd->node[i] ) { continue; } CAN_DPRINT((OSIF_ZONE_USR_INIT, "%s%d", n++?", ":" ", crd->card_no * NODES_PER_CARD + i)); } CAN_DPRINT((OSIF_ZONE_USR_INIT, "\n")); return; } /*! * \brief This function prints all information, that might be useful to the user * at the time the driver is loaded. Use this function in init-functions (such as * esdcan_init()) */ VOID esdcan_show_driver_info( VOID ) { CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: %s\n", ESDCAN_DRIVER_NAME)); CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: mode=0x%08x, major=%d, verbose=0x%08x\n", mode, major, verbose)); CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: Version %d.%d.%d ("__TIME__", "__DATE__")\n", LEVEL, REVI, BUILD)); CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: successfully loaded\n")); #if defined(CAN_DEBUG) CAN_PRINT(("esd CAN driver: !!! DEBUG VERSION !!!\n")); CAN_PRINT(("Please note:\n")); CAN_PRINT(("You're using a debug version of the esd CAN driver.\n")); CAN_PRINT(("This version is NOT intended for productive use.\n")); CAN_PRINT(("The activated debug code might have bad influence\n")); CAN_PRINT(("on performance and system load.\n")); CAN_PRINT(("If you received this driver from somebody else than\n")); CAN_PRINT(("esd support, please report to \"support@esd.eu\".\n")); CAN_PRINT(("Thank you!\n")); #endif /* #if defined(CAN_DEBUG) */ return; } #if !defined(ESDCAN_HOTPLUG_DRIVER) && !defined(BOARD_SPI) VOID esdcan_show_card_info_all( VOID ) { UINT32 i; for ( i = 0; i < MAX_CARDS; i++ ) { CAN_CARD *crd; HOTPLUG_BOLT_SYSTEM_ENTRY(modules[i]); crd = GET_CARD_POINTER(i); if ( NULL == crd ) { HOTPLUG_BOLT_SYSTEM_EXIT(modules[i]); continue; } esdcan_show_card_info(crd); HOTPLUG_BOLT_SYSTEM_EXIT(modules[i]); CAN_DPRINT((OSIF_ZONE_USR_INIT, "\n")); } return; } INT32 can_detach_legacy( VOID ) { INT32 result = OSIF_SUCCESS; UINT32 i; CAN_DBG((ESDCAN_ZONE_INIFU, "%s: enter\n", OSIF_FUNCTION)); for( i = 0; i < MAX_CARDS; i ++) { CAN_CARD *crd = GET_CARD_POINTER(i); if ( NULL == crd ) { continue; } GET_CARD_POINTER(i) = NULL; can_detach_common(crd, i); OSIF_FREE( crd ); } CAN_DBG((ESDCAN_ZONE_INIFU, "%s: leave\n", OSIF_FUNCTION)); return result; } /*! Executed ONCE when driver module is loaded */ int OSIF__INIT esdcan_init_legacy(void) { INT32 result = 0; CAN_DBG((ESDCAN_ZONE_INIFU, "%s: enter\n", OSIF_FUNCTION)); CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: init start\n")); # ifdef LTT can_ltt0 = trace_create_event("CAN_LTT_0", NULL, CUSTOM_EVENT_FORMAT_TYPE_HEX, NULL); # endif /* LTT */ if (esdcan_register_ioctl32()) { RETURN_TO_USER(OSIF_INVALID_PARAMETER); } if ( OSIF_ATTACH() ) { CAN_DBG((ESDCAN_ZONE_INI, "%s: osif_attach failed!!!\n", OSIF_FUNCTION)); esdcan_unregister_ioctl32(); RETURN_TO_USER(OSIF_INSUFFICIENT_RESOURCES); } result = can_attach(); if ( result != OSIF_SUCCESS ) { OSIF_DETACH(); esdcan_unregister_ioctl32(); RETURN_TO_USER(result); } esdcan_show_driver_info(); esdcan_show_card_info_all(); # ifndef OSIF_OS_RTAI /* register device */ if ( 0 != register_chrdev( major, ESDCAN_DRIVER_NAME, &esdcan_fops ) ) { CAN_PRINT(("esd CAN driver: cannot register character device for major=%d\n", major)); CAN_DETACH; OSIF_DETACH(); esdcan_unregister_ioctl32(); RETURN_TO_USER(EBUSY); } # endif /* OSIF_OS_RTAI */ esdcan_proc_nodeinit_create(); CAN_DBG((ESDCAN_ZONE_INIFU, "%s: leave\n", OSIF_FUNCTION)); RETURN_TO_USER(result); } /*! Executed when driver module is unloaded */ void OSIF__EXIT esdcan_exit_legacy(void) { CAN_DBG((ESDCAN_ZONE_INIFU, "%s: enter, unloading esd CAN driver\n", OSIF_FUNCTION)); unregister_chrdev(major, ESDCAN_DRIVER_NAME); esdcan_unregister_ioctl32(); CAN_DETACH; # ifdef LTT trace_destroy_event(can_ltt0); # endif /* #ifdef LTT */ esdcan_proc_nodeinit_remove(); OSIF_DETACH(); CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: unloaded\n")); CAN_DBG((ESDCAN_ZONE_INIFU, "%s: leave\n", OSIF_FUNCTION)); } OSIF_MODULE_INIT(esdcan_init_legacy); OSIF_MODULE_EXIT(esdcan_exit_legacy); #endif /* !defined(ESDCAN_HOTPLUG_DRIVER) && !defined(BOARD_SPI) */ MODULE_AUTHOR("esd gmbh, support@esd.eu"); MODULE_DESCRIPTION("esd CAN driver"); MODULE_LICENSE("Proprietary"); #ifdef OSIF_OS_RTAI EXPORT_SYMBOL(esdcan_read); EXPORT_SYMBOL(esdcan_write); EXPORT_SYMBOL(esdcan_ctrl); #else /* #ifdef OSIF_OS_RTAI */ # if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) EXPORT_NO_SYMBOLS; # endif /* #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) */ #endif /* #ifdef OSIF_OS_RTAI */ /* Id for RCS version system */ #if ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >=1)) /* GCC >= 3.1 */ static char* rcsid __attribute__((unused,used)) = "$Id: esdcan.c 14790 2015-07-13 18:56:47Z stefanm $"; #elif ((__GNUC__ > 2) || (__GNUC__ == 2 && __GNUC_MINOR__ >=7)) static char* rcsid __attribute__((unused)) = "$Id: esdcan.c 14790 2015-07-13 18:56:47Z stefanm $"; #else /* No or old GNU compiler */ # define USE(var) static void use_##var(void *x) {if(x) use_##var((void *)var);} static char* rcsid = "$Id: esdcan.c 14790 2015-07-13 18:56:47Z stefanm $"; USE(rcsid); #endif /* of GNU compiler */ /*---------------------------------------------------------------------------*/ /* EOF */ /*---------------------------------------------------------------------------*/
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/boardrc.h
/************************************************************************ * * Copyright (c) 1996 - 2016 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd.eu * Germany sales@esd.eu * *************************************************************************/ /*! \file boardrc.h \brief Board specific board API This file contains board specific constants for a particular board implementation. This file may be empty for some boards. */ #ifndef __BOARDRC_H__ #define __BOARDRC_H__ /* Check if <osif.h> is included */ #if !defined(__OSIF_H__) #error "Header <osif.h> has to be included BEFORE <boardrc.h> !!" #endif #ifndef OSIF_KERNEL #error "This file may be used in the kernel-context, only! Not for application-use!!!" #endif /* Valid esdACC version range */ #define ESDACC_VERSION_MIN 0x0035 #define ESDACC_VERSION_MAX 0x1000 #define ESDCAN_DRIVER_NAME "CAN_PCIe402" #define BOARD_PCI #define BOARD_BUSMASTER #define BOARD_MSI #undef BOARD_CAN_FD #define NUC_IRQ_NOSYNC #define NUC_TX_TIMEOUT_IGNORE_COUNTING #define NUC_TX_TS #define BUS_STATISTICS #undef ESDACC_IRIG_B #undef ESDACC_PXI #define ESDACC_ARINC825 #define ESDACC_HW_TIMESTAMP /* used in windows system layer */ #undef ESDACC_USE_NO_HW_TIMER #define ESDACC_MEASURED_AUTOBAUD #undef ESDACC_MEASURED_BUSLOAD #include <esdaccrc.h> /* Has to be included BEHIND those config defines above */ /* BL TODO: remove HARDTS defines (still used in VxWorks and Win esdcan layers...) */ #define HARDTS #define HARDTS_FREQ INT64_C(80000000) /* BL TODO: needed? */ /* default driver features - more feature flags will be set after hardware probing */ #define CARD_FEATURES (FEATURE_CAN_20B | FEATURE_LOM | \ FEATURE_TS | FEATURE_SMART_DISCONNECT | \ FEATURE_DIAGNOSTIC) #define MAX_CARDS 8 #define NODES_PER_CARD 4 #define EEI_MAX_UNITS 1 /* actually zero... */ #define NUC_MAX_BRP_ESDACC 512 #define NUC_MAX_TSEG1 15 #define NUC_MAX_TSEG2 7 #define NUC_MAX_SJW 3 #define NUC_MASK_BRP 0x000001FF #define NUC_MASK_TSEG1 0x0000F000 #define NUC_MASK_TSEG2 0x00700000 #define NUC_MASK_SJW 0x06000000 #define NUC_MASK_SAM 0x08000000 #define PCI_VENDOR_ESD 0x12FE #define PCI_SUB_VENDOR_ESD 0x12FE #define PCI_DEVICE_PCIE402 0x0402 #define PCI_DEVICE_PCIE402_DEV 0x4334 /* DEVELOPMENT IDs */ #define PCI_SUB_SYSTEM_PCIE402_S 0x0401 /* with Altera CGX15 */ #define PCI_SUB_SYSTEM_PCIE402_M 0x0402 /* with Altera CGX22 */ #define PCI_SUB_SYSTEM_PCIE402_L 0x0403 /* with Altera CGX30 */ #define PCI_SUB_SYSTEM_PCIE402_DEV 0x0001 /* DEVELOPMENT IDs */ #define PCI_TYPE0_ADDRESSES 6 #define SPI_FLASH #define SPI_FLASH_SIZE 0x200000 /* 2MB */ #define SPI_SECTOR_SIZE 0x10000 /* 64kB Micron M25P80/M25P16 (while Spansion has 4kB!) */ #define SPI_FLASH_PAGE_SIZE 0x100 /* 256 Byte */ /* esd products */ #define IDX_BOARD "C402" #define ESDCAN_IDS_PCIE402_S { \ PCI_VENDOR_ESD, PCI_DEVICE_PCIE402, \ PCI_SUB_VENDOR_ESD, PCI_SUB_SYSTEM_PCIE402_S, \ 0, 0, 0 } #define ESDCAN_IDS_PCIE402_M { \ PCI_VENDOR_ESD, PCI_DEVICE_PCIE402, \ PCI_SUB_VENDOR_ESD, PCI_SUB_SYSTEM_PCIE402_M, \ 0, 0, 0 } #define ESDCAN_IDS_PCIE402_L { \ PCI_VENDOR_ESD, PCI_DEVICE_PCIE402, \ PCI_SUB_VENDOR_ESD, PCI_SUB_SYSTEM_PCIE402_L, \ 0, 0, 0 } #define ESDCAN_IDS_PCIE402_DEV { \ PCI_VENDOR_ESD, PCI_DEVICE_PCIE402_DEV, \ PCI_SUB_VENDOR_ESD, PCI_SUB_SYSTEM_PCIE402_DEV, \ 0, 0, 0 } #define ESDCAN_IDS_PCI ESDCAN_IDS_PCIE402_S, ESDCAN_IDS_PCIE402_M, ESDCAN_IDS_PCIE402_L, ESDCAN_IDS_PCIE402_DEV #define C402_BUS_TYPE_PCIE 0x00 /* PCIe version */ #define C402_BUS_TYPE_PCI 0x01 /* PCI version */ #define C402_BUS_TYPE_CPCIS 0x02 /* CPCIserial version */ #define C402_BUS_TYPE_CPCI 0x03 /* CPCI version */ typedef struct _PCIE_EP PCIE_EP; typedef struct _SPI_CTRL SPI_CTRL; typedef struct _SYSTEM_ID SYSTEM_ID; typedef struct _FLASH_TAIL FLASH_TAIL; typedef struct _FPGA_SYSTEM FPGA_SYSTEM; struct _PCIE_EP { UINT32 reserved0[16]; /* 0x0000-0x003C */ volatile UINT32 intStat; /* 0x0040 */ UINT32 reserved1[3]; /* 0x0044-0x004C */ volatile UINT32 intEnable; /* 0x0050 */ UINT32 reserved2[3]; /* 0x0054-0x005C */ UINT32 reserved3[488]; /* 0x0060-0x07FC */ volatile UINT32 pcie2AvalonMb[8]; /* 0x0800-0x081C */ UINT32 reserved4[56]; /* 0x0820-0x08FC */ volatile UINT32 avalon2PcieMb[8]; /* 0x0900-0x091C */ UINT32 reserved5[56]; /* 0x0920-0x09FC */ UINT32 reserved6[384]; /* 0x0A00-0x0FFC */ volatile UINT32 avalon2PcieAT[1024]; /* 0x1000-0x1FFC */ UINT32 reserved7[1024]; /* 0x2000-0x2FFC, reserved by Altera */ UINT32 reserved8[1024]; /* 0x3000-0x3FFC, reserved for Avalon access */ }; struct _SPI_CTRL { volatile UINT32 rx; /* 0x0000 */ volatile UINT32 tx; /* 0x0004 */ volatile UINT32 status; /* 0x0008 */ volatile UINT32 control; /* 0x000C */ volatile UINT32 reserved; /* 0x0010 */ volatile UINT32 slave_select; /* 0x0014 */ }; struct _SYSTEM_ID { UINT32 uiId; UINT32 uiTime; }; #include "flashtail.h" struct _FPGA_SYSTEM { ESDACCRC_OVERVIEW_PARTITION_1; /* UP TO HERE IDENTICAL FOR ALL ESDACC BOARDS */ UINT32 reserved3[512]; /* 2kB or 512 longwords per "partition"/"sub unit" */ UINT32 reserved4[512]; /* 2kB or 512 longwords per "partition"/"sub unit" */ UINT32 reserved7[512]; /* 2kB or 512 longwords per "partition"/"sub unit" */ UINT32 reserved9[0x4C00]; /* IRIG-B module */ volatile UINT32 irigbImpID; volatile UINT32 irigbImpRev; volatile UINT32 irigbImpCfg; volatile UINT32 irigbImpReserved; volatile UINT32 irigbImpTimestampHigh; volatile UINT32 irigbImpTimestampLow; volatile UINT32 irigbImpFrequency; UINT32 reserved10[0x1F9]; volatile UINT32 irigBStatus; /* 0x15800: one status byte, 0x15801: one config byte, 0x15802: 16 bit IRIG info value */ volatile UINT32 irigBInfo1; /* 0x15804: 2x 16 bit IRIG Info values */ volatile UINT32 irigBInfo2; /* 0x15808: 2x 16 bit IRIG Info values */ volatile UINT32 irigBInfo3; /* 0x1580C: 2x 16 bit IRIG Info values */ volatile UINT16 irigBAdc[8]; /* 0x15810: ADC1, 0x15812: ADC2, ... ADC5, 0x1581E: ADC counter */ UINT32 reserved5[36]; volatile INT8 irigBFrame[16]; /* 0x158B0 */ volatile INT8 irigBInfo[64]; /* 0x158C0 */ volatile INT8 irigBYearMode; /* 0x16800 */ volatile INT8 irigBYear; /* 0x16801 */ INT8 reserved6[2]; /* 0x16802-0x16803 */ volatile UINT32 irigBTimeStart; /* 0x16804 */ volatile UINT32 irigBSyncMode; /* 0x16808 */ /* Write 0x0001 to increase tolerance */ }; #define CIF_CARD \ FPGA_SYSTEM *pBaseOverview; \ SPI_CTRL *pBaseSpi; \ SYSTEM_ID *pBaseSystemId; \ PCIE_EP *pBasePcieEP; \ INT32 numCores; \ INT32 numCoresInFpga; \ UINT8 fpgaType; \ UINT8 busType; \ UINT32 irigBFrame[4]; \ CHAR8 irigBStrModule[16]; \ CHAR8 irigBStrFirmware[24]; \ CHAR8 irigBStrDate[8]; \ CHAR8 irigBStrTime[8]; \ VOID *us_pcimsgram; \ UINT32 us_pcimsgram_phy_addr; \ OSIF_PCIDEV pciDev; \ OSIF_PCI_VADDR pcibuf_virt_addr; \ OSIF_PCI_VADDR pcibuf_virt_addr_alloc; \ UINT32 pcibuf_phy_addr; \ OSIF_PCI_PADDR pcibuf_phy_addr_alloc; \ OSIF_PCI_MADDR buffer_map; \ UINTPTR cacheDmaCtxt; \ UINT32 flagIrqInit; \ BM_STUFF bm[NODES_PER_CARD+1]; /* +1 for overview module */ \ OSIF_IRQ_MUTEX lockIrqUnMask; \ INT32 idxCoreIrq; \ VOID *eei_base; \ OSIF_MUTEX eei_lock; \ UINT32 eei_units_count; \ CAN_OCB *eei_units[EEI_MAX_UNITS]; \ OSIF_TS_FREQ timestamp_freq; \ CIF_TIMER_BASE hwTimer; \ UINT32 flagMsi; /* needs BOARD_MSI define */ \ UINT32 flagFlashSectorNotErased; \ UINT32 flagPageAllFF; \ UINT32 flashEraseSector; \ INT32 iCntPassWdRetry; \ CARD_IDENT ident; #define STRAPPING_BIT_2ND_CAN 0 #define STRAPPING_BIT_B4 1 #define STRAPPING_BIT_STRAP_0 2 #define STRAPPING_BIT_STRAP_1 3 #define STRAPPING_BIT_STRAP_2 4 #define STRAPPING_BIT_STRAP_3 5 #define STRAPPING_BIT_JP_0 6 #define STRAPPING_BIT_JP_1 7 #define STRAPPING_BIT_JP_2 8 #define STRAPPING_BIT_JP_3 9 #define STRAPPING_BIT_ADDON 10 #define STRAPPING_BIT_ADDON_STRAP_0 11 #define STRAPPING_BIT_ADDON_STRAP_1 12 #define STRAPPING_BIT_ADDON_STRAP_2 13 #define STRAPPING_BIT_ADDON_STRAP_3 14 #define STRAPPING_MASK_2ND_CAN (1 << STRAPPING_BIT_2ND_CAN) #define STRAPPING_MASK_B4 (1 << STRAPPING_BIT_B4) #define STRAPPING_MASK_STRAP_0 (1 << STRAPPING_BIT_STRAP_0) #define STRAPPING_MASK_STRAP_1 (1 << STRAPPING_BIT_STRAP_1) #define STRAPPING_MASK_STRAP_2 (1 << STRAPPING_BIT_STRAP_2) #define STRAPPING_MASK_STRAP_3 (1 << STRAPPING_BIT_STRAP_3) #define STRAPPING_MASK_STRAPS_0_3 (STRAPPING_BIT_STRAP_0 | STRAPPING_BIT_STRAP_1 | STRAPPING_BIT_STRAP_2 | STRAPPING_BIT_STRAP_3) #define STRAPPING_MASK_JP_0 (1 << STRAPPING_BIT_JP_0) #define STRAPPING_MASK_JP_1 (1 << STRAPPING_BIT_JP_1) #define STRAPPING_MASK_JP_2 (1 << STRAPPING_BIT_JP_2) #define STRAPPING_MASK_JP_3 (1 << STRAPPING_BIT_JP_3) #define STRAPPING_MASK_JPS_0_3 (STRAPPING_BIT_JP_0 | STRAPPING_BIT_JP_1 | STRAPPING_BIT_JP_2 | STRAPPING_BIT_JP_3) #define STRAPPING_MASK_ADDON (1 << STRAPPING_BIT_ADDON) #define STRAPPING_MASK_ADDON_STRAP_0 (1 << STRAPPING_BIT_ADDON_STRAP_0) #define STRAPPING_MASK_ADDON_STRAP_1 (1 << STRAPPING_BIT_ADDON_STRAP_1) #define STRAPPING_MASK_ADDON_STRAP_2 (1 << STRAPPING_BIT_ADDON_STRAP_2) #define STRAPPING_MASK_ADDON_STRAP_3 (1 << STRAPPING_BIT_ADDON_STRAP_3) #define STRAPPING_MASK_ADDON_STRAPS_0_3 (STRAPPING_MASK_ADDON_STRAP_0 | STRAPPING_MASK_ADDON_STRAP_1 | STRAPPING_MASK_ADDON_STRAP_2 | STRAPPING_MASK_ADDON_STRAP_3) INT32 boardrc_ts_set(VOID *dummy, OSIF_TS *pTs); INT32 boardrc_tsfreq_get(VOID *dummy, OSIF_TS_FREQ *pFreq); INT32 boardrc_corefreq_get(VOID *dummy, UINT32 *pFreq); UINT32 boardrc_fpga_type_get(VOID *pCrd); INT32 boardrc_timer_set(VOID *dummy, OSIF_TS *pTs); INT32 boardrc_timer_get(VOID *dummy, OSIF_TS *pTs); VOID boardrc_spi_sector_erase(SPI_CTRL *pSpiCtrl, UINT32 uiAddr); VOID boardrc_spi_bulk_erase(SPI_CTRL *pSpiCtrl); VOID boardrc_spi_page_program(SPI_CTRL *pSpiCtrl, const UINT8 *pArr, INT32 iLen, UINT32 uiAddr); VOID boardrc_spi_read_data(SPI_CTRL *pSpiCtrl, UINT8 *pArr, INT32 iLen, UINT32 uiAddr); VOID boardrc_strappings_print(UINT16 uiStrappings); #define BOARDRC_STRAPPINGS_PRINT(strap) boardrc_strappings_print(strap) #if defined(OSIF_PNP_OS) # define CAN_BOARD_DETACH_FINAL(pCrd, targetState) can_board_detach_final(pCrd, targetState) #else # define CAN_BOARD_DETACH_FINAL(pCrd) can_board_detach_final(pCrd) #endif #endif
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/Makefile
DRVVERSION=-DLEVEL=3 -DREVI=10 -DBUILD=4 ESD_CPPFLAGS += -DBOARD_pcie402 ESD_CPPFLAGS +=-DOSIF_OS_LINUX $(DRVVERSION) ESD_CPPFLAGS += -I $(src) ESD_CPPFLAGS += -DMAJOR_LINUX=52 -DHOST_DRIVER=1 ESD_CPPFLAGS += $(shell if ( cat /proc/version | grep -i suse 2>&1 > /dev/null ); then echo -DDISTR_SUSE; fi;) ifdef KBUILD_CPPFLAGS KBUILD_CPPFLAGS += $(ESD_CPPFLAGS) else ifdef ccflags-y ccflags-y += $(ESD_CPPFLAGS) else CPPFLAGS += $(ESD_CPPFLAGS) endif endif obj-m += esdcan-pcie402.o esdcan-pcie402-objs := esdcan.o osif.o nucleus.o esdacc.o board.o boardrc.o crc32.o
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/sys_osiftypes.h
#ifndef __SYS_OSIFTYPES_H__ #define __SYS_OSIFTYPES_H__ #include <linux/types.h> typedef void VOID; typedef u8 UINT8; typedef s8 INT8; typedef u16 UINT16; typedef s16 INT16; typedef u32 UINT32; typedef s32 INT32; typedef u64 UINT64; typedef s64 INT64; typedef char CHAR8; typedef unsigned long UINTPTR; typedef signed long INTPTR; /* Some definitions for POSIX conform constant declaration, * not present in all linux kernels */ #ifndef INT32_C # define INT32_C(c) (c ## L) # define UINT32_C(c) (c ## UL) # define INT64_C(c) (c ## LL) # define UINT64_C(c) (c ## ULL) #endif #endif /* __SYS_OSIFTYPES_H__ */
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/esdcan_pci.c
/* -*- esdcan-c -*- * FILE NAME esdcan_pci.c * copyright 2005-2014 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * This file contains entries common to PCI devices * for Linux/RTAI/IRIX * for the esd CAN driver * * * Author: Andreas Block * andreas.block@esd-electronics.com * * history: * * $Log$ * Revision 1.29 2014/06/23 17:02:19 stefanm * Removed ESDCAN_ZONE_USR_INIT and replaced by OSIF_ZONE_USR_INIT used directly * because it did not work well with the new osif_dprint() function (no output). * Replaced wrong "linux-c" mode with atm. invalid "esdcan-c" mode. * * Revision 1.28 2014/05/22 11:18:21 manuel * Fixed a warning * * Revision 1.27 2014/02/27 15:47:43 andreas * Busmaster fix for at least kernel 3.11 (issue occured on MJ's new PC) * * Revision 1.26 2013/10/21 13:35:59 andreas * Changed esd support mail address * Added output of version number, if loading of driver failed * * Revision 1.25 2013/08/19 13:16:27 manuel * Fixes for kernel greater 3.7 * * Revision 1.24 2013/07/16 14:17:43 andreas * Added MSI support * * Revision 1.23 2011/11/01 11:09:33 andreas * Updated copyright * * Revision 1.22 2011/05/18 16:02:09 andreas * Changed copyright header * * Revision 1.21 2010/02/23 08:59:16 andreas * Changed access to private data in device structure * (needed for kernels >= 2.6.32) * * Revision 1.20 2009/02/25 16:26:21 andreas * Removed bus statistics proc-file * * Revision 1.19 2008/12/02 11:06:11 andreas * Fix/Change: * - proc files were moved into /proc/bus/can/DRIVER_NAME/ * - Fixed problems, when loading different drivers concurrently * - Fixed problems with several identical CAN boards * * Revision 1.18 2008/05/29 11:29:09 manuel * Added debug output of crd pointer * * Revision 1.17 2006/12/22 10:00:06 andreas * Added creation of /proc/bus/can/inodeinit * * Revision 1.16 2006/11/10 15:49:03 matthias * also check pci classcode * * Revision 1.15 2006/10/30 11:24:08 andreas * No changes. * Cosmetic firlefanz, only * * Revision 1.14 2006/10/12 09:53:36 andreas * Replaced some forgotten CANIO_-error codes with the OSIF_ counterparts * Replaces some errnos with their OSIF_counterparts * Cleaned up return of error codes to user space, * please use positive error codes, only!!! * * Revision 1.13 2006/08/17 13:26:59 michael * Rebirth of OSIF_ errorcodes * * Revision 1.12 2006/06/27 13:12:24 andreas * Exchanged OSIF_errors with CANIO_errors * * Revision 1.11 2006/06/27 10:01:53 andreas * No functional change * Only whitespace change due to save in xemacs * * Revision 1.10 2006/06/16 09:14:13 andreas * owner field in driver structure has been removed again * * Revision 1.9 2005/12/06 16:53:38 andreas * Removed forgotten test code (which made unloading impossible with last checkin) * Corrected bug in PCI_DATA macro * * Revision 1.8 2005/12/06 13:28:42 andreas * Rewrote error exit in attach. * Corrected support email address. * Cleanup. * * Revision 1.7 2005/09/28 06:27:42 andreas * Fixed/changed kernel version comparisons for pci_register_driver to * decrease problems with certain Fedora Core 3 kernels. * * Revision 1.6 2005/08/29 14:35:31 andreas * Fixed bug (sanity check identified IO-spaces, * which were disabled in board layer as memory spaces) * * Revision 1.5 2005/08/23 14:47:26 andreas * Fix for pci360 (driver attempted to wromngly map PCI space six), * using information from cardFlavours.pci.spaces again. * * Revision 1.4 2005/07/29 08:22:07 andreas * crd-structure stores pointer (pCardIdent) into cardFlavours structure instead of index (flavour), now. * Some minor cleanup. * * Revision 1.3 2005/07/28 14:09:22 andreas * Forgot to set error code if probe is called for a non-supported device * (This should never happen in real life). * * Revision 1.2 2005/07/28 13:49:25 andreas * Added header comment. * Added log entry for CVS history. * Small cleanup. * * * 28.07.2005 - Separated initialization of different board types AB * (raw, pci, usb,...). This file contains the PCI * specific part, realized as a hotplugable driver * (although functions for power management still * need to be connected). */ /************************************************************************ * * Copyright (c) 1996 - 2014 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd-electronics.com * Germany sales@esd-electronics.com * *************************************************************************/ /*! \file esdcan_pci.c \brief Hotplugable PCI device support This file contains the PCI device initialization of the esdcan hotplug driver. */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30) # define PCI_DRIVER_DATA_GET(pdev) dev_get_drvdata(&pdev->dev) # define PCI_DRIVER_DATA_SET(pdev, d) dev_set_drvdata(&pdev->dev, d) #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # define PCI_DRIVER_DATA_GET(pdev) pdev->dev.driver_data # define PCI_DRIVER_DATA_SET(pdev, d) pdev->dev.driver_data = d #else # define PCI_DRIVER_DATA_GET(pdev) pdev->driver_data # define PCI_DRIVER_DATA_SET(pdev, d) pdev->driver_data = d #endif /* Bolts not needed for PCI hotplug driver, * but are used in common files * (namely esdcan.c and esdcan_common.c) */ #define HOTPLUG_BOLT_SYSTEM_ENTRY(mod) #define HOTPLUG_BOLT_SYSTEM_EXIT(mod) #define HOTPLUG_BOLT_USER_ENTRY(mod) 0 #define HOTPLUG_BOLT_USER_EXIT(mod) #define HOTPLUG_GLOBAL_LOCK #define HOTPLUG_GLOBAL_UNLOCK /* * Forward declarations */ VOID can_detach_common( CAN_CARD *crd, INT32 crd_no ); /* implemented in esdcan.c */ static int OSIF__INIT esdcan_init(struct pci_dev *dev, const struct pci_device_id *pci_id); static VOID OSIF__EXIT esdcan_exit(struct pci_dev *dev); /* * Table of devices that work with this driver */ static struct pci_device_id esdcan_pci_tbl[] = { ESDCAN_IDS_PCI, {0,} }; #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,9) /* AB: Actually .owner came in with 2.6.9 in most distributions. * Except Fedora 3, where it was introduced with 2.6.10 :( */ static struct pci_driver esdcan_pci_driver = { # if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,15) /* AB: kernel developers love consistence :( */ .owner = THIS_MODULE, # endif .name = ESDCAN_DRIVER_NAME, .id_table = esdcan_pci_tbl, .probe = esdcan_init, #if LINUX_VERSION_CODE <= KERNEL_VERSION(3,7,0) .remove = __devexit_p(esdcan_exit), #else .remove = esdcan_exit, /* back to the roots */ #endif }; #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) static struct pci_driver esdcan_pci_driver = { .name = ESDCAN_DRIVER_NAME, .id_table = esdcan_pci_tbl, .probe = esdcan_init, .remove = __devexit_p(esdcan_exit), }; #else static struct pci_driver esdcan_pci_driver = { name: ESDCAN_DRIVER_NAME, id_table: esdcan_pci_tbl, probe: esdcan_init, remove: esdcan_exit, }; #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) /* AB TODO: since version 2.4.x???*/ MODULE_DEVICE_TABLE(pci, esdcan_pci_tbl); #endif /* Version Information */ #define DRIVER_VERSION LEVEL"."REVI"."BUILD #define DRIVER_AUTHOR "esd gmbh, support@esd.eu" #define DRIVER_DESC "PCI-CAN-driver" static int esdcan_pci_driver_registered = 0; static int esdcan_pci_attached_cards = 0; int can_attach(struct pci_dev *pciDev, const struct pci_device_id *pci_id) { UINT32 j; INT32 lastError = OSIF_SUCCESS; INT32 result; CAN_CARD *crd; VOID *vptr; CARD_IDENT *pCardIdent = 0; /* This shouldn't occurr in real life! */ if ( NULL == cardFlavours ) { CAN_PRINT(("esd CAN driver: Severe problem with board layer! Card flavour missing!\n")); lastError = ENODEV; return lastError; } /* Determine flavour (needed to get name of card, etc...) */ for ( pCardIdent = &cardFlavours[0]; NULL != pCardIdent->pci.irqs; pCardIdent++ ) { if ( (pciDev->vendor == pCardIdent->pci.ids.vendor) && (pciDev->device == pCardIdent->pci.ids.device) && (pciDev->subsystem_vendor == pCardIdent->pci.ids.subVendor) && (pciDev->subsystem_device == pCardIdent->pci.ids.subDevice) && ((! pCardIdent->pci.ids.class) || ((pciDev->class >> 8) == pCardIdent->pci.ids.class)) ) { break; } } if ( NULL == pCardIdent->pci.irqs ) { CAN_PRINT(("esd CAN driver: This PCI-hardware is not supported by this driver.\n")); lastError = ENODEV; return lastError; } result = OSIF_MALLOC(sizeof(*crd), &vptr); if ( OSIF_SUCCESS != result ) { lastError = result; CAN_PRINT(("%s: Not enough memory for crd-struct\n", pCardIdent->pci.name)); return lastError; } crd = (CAN_CARD*)vptr; CAN_DBG((ESDCAN_ZONE_INI, "crd @%p\n", crd )); OSIF_MEMSET( crd, 0, sizeof(*crd) ); crd->pCardIdent = pCardIdent; crd->card_no = esdcan_pci_attached_cards; crd->features = CARD_FEATURES; CAN_DBG((ESDCAN_ZONE_INI, "PCI-Bus : %d\n", pciDev->bus->number )); CAN_DBG((ESDCAN_ZONE_INI, "PCI-Slot : %d\n", pciDev->devfn )); CAN_DBG((ESDCAN_ZONE_INI, "PCI-Ven.-ID : %04x\n", pciDev->vendor)); CAN_DBG((ESDCAN_ZONE_INI, "PCI-Dev.-ID : %04x\n", pciDev->device)); CAN_DBG((ESDCAN_ZONE_INI, "PCI-SubVen.ID: %04x\n", pciDev->subsystem_vendor)); CAN_DBG((ESDCAN_ZONE_INI, "PCI-SubSys.ID: %04x\n", pciDev->subsystem_device)); CAN_DBG((ESDCAN_ZONE_INI, "PCI-Class : %04x\n", pciDev->class)); CAN_DBG((ESDCAN_ZONE_INI, "PCI-Irq : %d\n", pciDev->irq)); if ( pci_enable_device(pciDev) ) { result = EIO; goto release_1; } crd->pciDev = pciDev; /* used by pci405, only */ for ( j = 0; (j < 8) && (pCardIdent->pci.spaces[j] != 0xFFFFFFFF); j++ ) { if ( pci_resource_flags(pciDev, j) & IORESOURCE_MEM ) { /* PCI Memory space */ /* Sanity check, if board layer expected memory space, too */ if ( pCardIdent->pci.spaces[j] & 0x00000001 ) { CAN_DBG((ESDCAN_ZONE_INI, "%s: PCI-space %d:\nConfig space says memory space,\n" \ " board layer says IO-space!!!\n", OSIF_FUNCTION, j)); result = ENOMEM; break; } /* Use smallest requested range * (from board layer or PCI config space) */ crd->range[j] = pCardIdent->pci.spaces[j]; if ( crd->range[j] > pci_resource_len(pciDev, j) ) { crd->range[j] = pci_resource_len(pciDev, j); } if ( crd->range[j] ) { crd->base[j] = ioremap_nocache( pci_resource_start(pciDev, j) + OSIF_PCI_OFFSET, crd->range[j] ); if ( crd->base[j] == NULL ) { CAN_DBG((ESDCAN_ZONE_INI, "%s: cannot map pci-addr[%d]=0x%08x\n", OSIF_FUNCTION, j, pci_resource_start(pciDev, j))); result = ENOMEM; break; } else { CAN_DBG((ESDCAN_ZONE_INI, "%s: pci-addr[%x]: phyaddr=%p virtaddr=%p\n", OSIF_FUNCTION, j, pci_resource_start(pciDev, j), crd->base[j] )); } } } else if ( pci_resource_flags(pciDev, j) & IORESOURCE_IO ) { /* PCI IO space */ /* Sanity check, if board layer expected IO space, too */ if ( (0 == (pCardIdent->pci.spaces[j] & 0x00000001)) && (0 != pCardIdent->pci.spaces[j]) ) { CAN_DBG((ESDCAN_ZONE_INI, "%s: PCI-space %d:\nConfig space says IO space,\n board layer says memory space!!!\n", OSIF_FUNCTION, j)); result = ENOMEM; break; } /* Use smallest requested range * (from board layer or PCI config space) */ crd->range[j] = pCardIdent->pci.spaces[j] & 0xFFFFFFFE; if ( crd->range[j] > pci_resource_len(pciDev, j) ) { crd->range[j] = pci_resource_len(pciDev, j); } if ( crd->range[j] ) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) if ( !request_region(pci_resource_start(pciDev, j), crd->range[j], pCardIdent->pci.name) ) { CAN_PRINT(("%s: Resource-Conflict: " "I/O-Arena %0X - %0X already occupied!\n", pCardIdent->pci.name, pci_resource_start(pciDev, j), pci_resource_start(pciDev, j) + crd->range[j] - 1 )); result = EBUSY; break; } #else if ( check_region(pci_resource_start(pciDev, j), crd->range[j]) ) { CAN_PRINT(("%s: Resource-Conflict: " "I/O-Arena %0X - %0X already occupied!\n", pCardIdent->pci.name, pci_resource_start(pciDev, j), pci_resource_start(pciDev, j) + crd->range[j] - 1 )); result = EBUSY; break; } request_region( pci_resource_start(pciDev, j), crd->range[j], pCardIdent->pci.name ); #endif crd->base[j] = (VOID*)(UINTPTR)pci_resource_start(pciDev, j); } } } if ( OSIF_SUCCESS != result ) { lastError = result; goto release_2; } #if defined(BOARD_BUSMASTER) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,33)) /* LXR is currently out of order, in 2.6.33 this function was available for sure, probably way earlier */ pci_set_master(pciDev); #endif #ifdef BOARD_MSI #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,1) if (pci_enable_msi(pciDev)) { crd->flagMsi = 0; } else { crd->flagMsi = 1; } #else crd->flagMsi = 0; #endif #endif crd->irq[0] = pciDev->irq; result = can_attach_common(crd); if ( OSIF_SUCCESS != result ) { lastError = result; goto release_2; } PCI_DRIVER_DATA_SET(pciDev, crd); esdcan_pci_attached_cards++; return 0; release_2: CAN_DBG((ESDCAN_ZONE_INI, "%s: Release_2:\n", OSIF_FUNCTION)); for ( j = 0; j < 8; j++ ) { if( NULL == crd->base[j] ) { continue; } if ( pci_resource_flags(pciDev, j) & IORESOURCE_MEM ) { /* Memory space */ iounmap(crd->base[j]); } else if ( pci_resource_flags(pciDev, j) & IORESOURCE_IO ) { /* IO-space */ release_region((UINTPTR)crd->base[j], crd->range[j]); } } release_1: CAN_DBG((ESDCAN_ZONE_INI, "%s: Release_1:\n", OSIF_FUNCTION)); #if defined(BOARD_MSI) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,1)) if (crd->flagMsi) { pci_disable_msi(pciDev); } #endif #if defined(BOARD_BUSMASTER) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,33)) /* LXR is currently out of order, in 2.6.33 this function was available for sure, probably way earlier */ pci_clear_master(pciDev); #endif OSIF_FREE(crd); return lastError; } INT32 can_detach( struct pci_dev *pciDev ) { INT32 result = OSIF_SUCCESS; UINT32 card_no; CAN_CARD *crd; CAN_DBG((ESDCAN_ZONE_INIFU, "%s: enter\n", OSIF_FUNCTION)); crd = PCI_DRIVER_DATA_GET(pciDev); /* crd-pointer is stored as driver's private data in pciDev */ if (NULL == crd) { return 0; } card_no = crd->card_no; PCI_DRIVER_DATA_SET(pciDev, NULL); can_detach_common(crd, card_no); #if defined(BOARD_MSI) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,1)) if (crd->flagMsi) { pci_disable_msi(pciDev); } #endif #if defined(BOARD_BUSMASTER) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,33)) /* LXR is currently out of order, in 2.6.33 this function was available for sure, probably way earlier */ pci_clear_master(pciDev); #endif OSIF_FREE(crd); esdcan_pci_attached_cards--; CAN_DBG((ESDCAN_ZONE_INIFU, "%s: leave\n", OSIF_FUNCTION)); return result; } /* Executed, when PCI card is plugged into the system * (this means actually, on driver load, by pci_register_driver()) * Called ONCE FOR EVERY CAN-BOARD! */ static int OSIF__INIT esdcan_init(struct pci_dev *dev, const struct pci_device_id *pci_id) { INT32 result = 0; CAN_DBG((ESDCAN_ZONE_INIFU, "%s: enter\n", OSIF_FUNCTION)); #ifdef LTT can_ltt0 = trace_create_event("CAN_LTT_0", NULL, CUSTOM_EVENT_FORMAT_TYPE_HEX, NULL); #endif /* LTT */ result = can_attach( dev, pci_id ); if ( OSIF_SUCCESS != result ) { RETURN_TO_USER(result); } esdcan_show_card_info(PCI_DRIVER_DATA_GET(dev)); CAN_DBG((ESDCAN_ZONE_INIFU, "%s: leave\n", OSIF_FUNCTION)); RETURN_TO_USER(result); } /* Executed, when PCI card is unplugged * (this means actually, on driver unload, by pci_unregister_driver()) */ static VOID OSIF__EXIT esdcan_exit(struct pci_dev *dev) { CAN_DBG((ESDCAN_ZONE_INIFU, "%s: enter, unloading esd CAN driver\n", OSIF_FUNCTION)); can_detach(dev); #ifdef LTT trace_destroy_event(can_ltt0); #endif CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: unloaded\n")); CAN_DBG((ESDCAN_ZONE_INIFU, "%s: leave\n", OSIF_FUNCTION)); } /*! Executed when driver module is loaded */ OSIF_STATIC int __init esdcan_pci_init(VOID) { INT32 result; CAN_DBG((ESDCAN_ZONE_INIFU, "%s: enter\n", OSIF_FUNCTION)); CAN_DPRINT((OSIF_ZONE_USR_INIT, "esd CAN driver: init start\n")); esdcan_pci_driver_registered = 0; if (esdcan_register_ioctl32()) { CAN_DBG((ESDCAN_ZONE_INI, "%s: Failed to register 32-Bit IOCTLs!!!\n", OSIF_FUNCTION)); result = OSIF_INVALID_PARAMETER; goto INIT_ERR_0; } if ( OSIF_ATTACH() ) { CAN_DBG((ESDCAN_ZONE_INI, "%s: osif_attach failed!!!\n", OSIF_FUNCTION)); result = OSIF_INSUFFICIENT_RESOURCES; goto INIT_ERR_1; } /* register driver as PCI-driver */ CAN_DBG((ESDCAN_ZONE_INI, "%s: Registering PCI driver...\n", OSIF_FUNCTION)); result = pci_register_driver(&esdcan_pci_driver); #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,8) /* NOTE: Fedora Core 3 customers with kernel 2.6.9: * For whatever reason Fedora chose not to use the patch, which fixes the problem * with pci_register_driver return values. We don't support this kernel-version, * please update to the next kernel-release (2.6.10 or following). */ if ( result ) { /* Now: zero is success, everything else is considered an error */ if ( result == 1 ) { CAN_PRINT(("esd CAN driver: If you're a Fedora 3 user with kernel 2.6.9,\n")); CAN_PRINT(("esd CAN driver: please update to kernel 2.6.10!\n")); } #else if ( 0 > result ) { /* Older kernels were pretending to return a counter with initialized devices, * actually pci-functions were sometimes cheating and returned always one!!! */ #endif CAN_PRINT(("esd CAN driver: Initialization of PCI module failed (0x%08x)!\n", result)); if ( 0 > result ) { /* To prevent linux from actually registering the driver */ /* result is inverted on return */ result = -result; } goto INIT_ERR_2; } /* If we did not find any card, we cancel driver initialization, * in order to reduce user confusion */ if ( 0 >= esdcan_pci_attached_cards ) { CAN_PRINT(("esd CAN driver: Version: 0x%08X\n", MAKE_VERSION(LEVEL, REVI, BUILD))); CAN_PRINT(("esd CAN driver: No esd CAN card found!\n")); result = OSIF_NET_NOT_FOUND; goto INIT_ERR_3; } /* register device for major-number */ CAN_DBG((ESDCAN_ZONE_INI, "%s: Registering character device...\n", OSIF_FUNCTION)); if ( 0 != register_chrdev( major, ESDCAN_DRIVER_NAME, &esdcan_fops ) ) { CAN_PRINT(("esd CAN driver: cannot register character device for major=%d\n", major)); result = OSIF_EBUSY; goto INIT_ERR_3; } esdcan_proc_nodeinit_create(); esdcan_pci_driver_registered = 1; esdcan_show_driver_info(); CAN_DBG((ESDCAN_ZONE_INIFU, "%s: leave\n", OSIF_FUNCTION)); RETURN_TO_USER(0); INIT_ERR_3: /* No card found or failed to register driver for major number */ pci_unregister_driver(&esdcan_pci_driver); INIT_ERR_2: /* Failed to register PCI driver */ OSIF_DETACH(); INIT_ERR_1: /* Failed to initialize OSIF layer */ esdcan_unregister_ioctl32(); INIT_ERR_0: /* Failed to register 32-Bit IOCTLs (on 64-Bit system) */ RETURN_TO_USER(result); } /*! Executed when driver module is unloaded */ OSIF_STATIC VOID __exit esdcan_pci_exit(VOID) { CAN_DBG((ESDCAN_ZONE_INIFU, "%s: enter\n", OSIF_FUNCTION)); if ( 1 == esdcan_pci_driver_registered ) { unregister_chrdev( major, ESDCAN_DRIVER_NAME ); pci_unregister_driver(&esdcan_pci_driver); esdcan_unregister_ioctl32(); esdcan_proc_nodeinit_remove(); esdcan_pci_driver_registered = 0; OSIF_DETACH(); } CAN_DBG((ESDCAN_ZONE_INIFU, "%s: leave\n", OSIF_FUNCTION)); } OSIF_MODULE_INIT(esdcan_pci_init); OSIF_MODULE_EXIT(esdcan_pci_exit);
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/cm.h
/* -*- esdcan-c -*- * FILE NAME cm.h * copyright 2002-2015 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * * * * history: * * $Log$ * Revision 1.63 2015/05/27 13:32:43 stefanm * Avoid name clash under LynxOS with 96-bit version structure now named VERSION96. * * Revision 1.62 2015/05/08 16:39:08 stefanm * Rename CAN_TS and CAN_TS_FREQ to OSIF_TS and OSIF_TS_FREQ. * This should now also be used instead of CAN_TIMESTAMP / TIMESTAMP * in the whole esdcan driver tree. * * Revision 1.61 2014/09/26 12:06:22 michael * Bugfix: FD Drivers have compile errors * * Revision 1.60 2014/09/26 11:00:54 michael * OBJ-MODE for RX rewritten. 11 Bit CAN-ID limit removed. * * Revision 1.59 2014/09/15 08:38:09 oliver * - Added ESDCAN_CTL_CAN_INFO * - Extended CARD_IDENT structure for USB devices with endpoint description. * * Revision 1.58 2014/07/24 15:24:13 hauke * Changed from BAUDRATE_FD to BAUDRATE_X * * Revision 1.57 2014/07/04 10:12:23 oliver * - Removed include of <osif.h>. * - Added sanity check that <boardrc.h> is already included. * - Moved C_ASSERT macro into osif.h. * * Revision 1.56 2014/07/04 09:37:17 hauke * Moved CAN_TS and CAN_TS_FREQ from cm.h to osif.h * Moved LNK definitions and macros from cm.h to osif.h * * Revision 1.55 2014/06/06 13:45:58 michael * CAN FD Support: NULL-Device, Driver Kernel and QNX Layer. Untested and not ready. * * Revision 1.54 2013/08/27 13:38:43 andreas * Added defines for driver parameters * * Revision 1.53 2013/08/16 12:31:19 andreas * Fixed online comments (// does not compile well under VxWorks) * * Revision 1.52 2013/05/22 13:52:15 oliver * Fixed MSC compiler warning if /Wp4 is enabled. * * Revision 1.51 2013/05/16 13:50:37 frank * Adaptions for CAN-USB/2 with OnTime RTOS-32 * * Revision 1.50 2013/01/07 15:34:24 andreas * Added ESDCAN_CTL_TX_TS_WIN_SET, ESDCAN_CTL_TX_TS_WIN_GET, ESDCAN_CTL_TX_TS_TIMEOUT_SET, ESDCAN_CTL_TX_TS_TIMEOUT_GET * * Revision 1.49 2013/01/03 16:17:27 andreas * Updated copyright notice * * Revision 1.48 2012/11/22 12:38:00 andreas * Improved C_ASSERT macro * * Revision 1.47 2011/10/24 14:34:43 andreas * changed copyright notice * * Revision 1.46 2011/08/22 13:43:26 hauke * added errorInjection ioctls * * Revision 1.45 2011/06/20 18:28:21 manuel * Added CARD_IDENT_TERMINATE, removed CARD_IDENT_xxx_TERMINATE * * Revision 1.44 2011/04/05 10:29:36 andreas * Changed to make use of new CHAR8 data type * * Revision 1.43 2010/12/10 16:36:48 andreas * Added ESDCAN_CTL_RESET_CAN_ERROR_CNT * * Revision 1.42 2010/08/30 11:59:56 andreas * Added C_ASSERT macro to do compile time size checking of data types * * Revision 1.41 2010/04/20 12:47:04 andreas * Removed Win32 compile time warning * * Revision 1.40 2010/04/16 16:20:45 andreas * Moved most of linked list stuff from nucleus into this file * * Revision 1.39 2009/07/31 14:14:55 andreas * Add ESDCAN_CTL_SER_REG_READ and ESDCAN_CTL_SER_REG_WRITE * Untabbified * * Revision 1.38 2009/02/25 15:45:52 andreas * Removed CAN_STAT structure (now in canio.h) * Added ESDCAN_CTL_BUS_STATISTIC_GET, ESDCAN_CTL_BUS_STATISTIC_RESET, * ESDCAN_CTL_ERROR_COUNTER_GET, ESDCAN_CTL_BITRATE_DETAILS_GET * * Revision 1.37 2008/02/28 15:44:25 michael * ESDCAN_CTL_DEBUG added. * * Revision 1.36 2007/12/13 14:02:24 michael * Member countStart/countStop added to CMSCHED * * Revision 1.35 2007/11/05 14:44:38 andreas * Added ESDCAN_CTL_BUSLOAD_INTERVAL_GET and ESDCAN_CTL_BUSLOAD_INTERVAL_SET * * Revision 1.34 2006/11/22 10:29:45 andreas * Fixed (already deprecated) FILTER_OBJ_RTR_ENABLE define * * Revision 1.33 2006/07/11 15:12:41 manuel * Added ts and ts_freq to CAN_STAT * * Revision 1.32 2006/06/27 09:53:56 andreas * Added ESDCAN_CTL_BAUDRATE_AUTO and ESDCAN_CTL_BAUDRATE_BTR * Added baud to CAN_STAT (quick fix in order to remove nuc_baudrate_get()) * * Revision 1.31 2005/09/29 07:22:47 michael * internal ioctl-codes added * * Revision 1.30 2005/09/14 13:25:36 manuel * Added CM_LEN2DATALEN macro * * Revision 1.29 2005/07/27 15:53:01 andreas * Added CARD_IDENT structure (see some boardrc.c/h for usage info) * * 27.05.02 - first version mf * */ /************************************************************************ * * Copyright (c) 1996 - 2013 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd-electronics.com * Germany sales@esd-electronics.com * *************************************************************************/ /*! \file cm.h * \brief Contains common CAN-message-structure (CM) and defines such as * feature-flags, mode-flags. These defines are visible to the user, * nevertheless: Dear user, please, use the defines in ntcan.h! * */ #ifndef __CM_H__ #define __CM_H__ #ifndef OSIF_KERNEL #error "This file may be used in the kernel-context, only! Not for application-use!!!" #endif /* Check if <boardrc.h> is included with the presence of the CARD_FEATURES macro */ #if !defined(CARD_FEATURES) # error "Header <boardrc.h> has to be included BEFORE <cm.h> !!" #endif /* calculate the data length from a given frame length value */ #ifdef BOARD_CAN_FD # define CM_LEN_MASK 0x9f #else # define CM_LEN_MASK 0x1f #endif /* command-flags for nuc_id_filter */ #define FILTER_ON 0x00000000 /* enable flag */ #define FILTER_OFF 0x80000000 /* disable flag */ #define FILTER_DATA 0x00000001 /* enabled for queued data input */ #define FILTER_RTR 0x00000002 /* enabled for queued rtr input */ #define FILTER_OBJ 0x00000004 /* enabled for object data input */ #define FILTER_OBJ_RTR 0x00000008 /* enabled for object rtr input */ #define FILTER_DATA_FD 0x00000010 /* enabled for queued fd data input*/ #ifdef BOARD_CAN_FD #define FILTER_ALL (FILTER_DATA | FILTER_RTR | FILTER_OBJ | FILTER_OBJ_RTR | FILTER_DATA_FD) #else #define FILTER_ALL (FILTER_DATA | FILTER_RTR | FILTER_OBJ | FILTER_OBJ_RTR) #endif /* Following is defined for the board files but DEPRECATED */ /* DEPRECATED BEGIN */ #define FILTER_DATA_ENABLE FILTER_DATA #define FILTER_RTR_ENABLE FILTER_RTR #define FILTER_OBJ_ENABLE FILTER_OBJ #define FILTER_OBJ_RTR_ENABLE FILTER_OBJ_RTR #define FILTER_DISABLE 0x00000000 /* DEPRECATED END */ /* Driver flags (aka driver start parameter) used in node->mode */ #define DRIVER_PARAM_LOM FEATURE_LOM #define DRIVER_PARAM_SMART_DISCONNECT FEATURE_SMART_DISCONNECT #define DRIVER_PARAM_SMART_SUSPEND 0x01000000 #define DRIVER_PARAM_ESDACC_AUTOBAUD 0x02000000 #define DRIVER_PARAM_PCIE402_FORCE 0x04000000 #define DRIVER_PARAM_PXI_TRIG_INVERT 0x08000000 #define DRIVER_PARAM_ESDACC_TS_SOURCE 0x10000000 #define DRIVER_PARAM_I20_NO_FAST_MODE 0x20000000 #define DRIVER_PARAM_ESDACC_TS_MODE 0x20000000 #define DRIVER_PARAM_PLX_FIFO_MODE 0x40000000 /* Driver internal IOCTL codes */ #define ESDCAN_CTL_TIMESTAMP_GET 1 #define ESDCAN_CTL_TIMEST_FREQ_GET 2 #define ESDCAN_CTL_BAUDRATE_GET 3 #define ESDCAN_CTL_BAUDRATE_SET 4 #define ESDCAN_CTL_ID_FILTER 5 #define ESDCAN_CTL_BAUDRATE_AUTO 6 #define ESDCAN_CTL_BAUDRATE_BTR 7 #define ESDCAN_CTL_BUSLOAD_INTERVAL_GET 8 #define ESDCAN_CTL_BUSLOAD_INTERVAL_SET 9 #define ESDCAN_CTL_DEBUG 10 #define ESDCAN_CTL_BUS_STATISTIC_GET 11 #define ESDCAN_CTL_BUS_STATISTIC_RESET 12 #define ESDCAN_CTL_ERROR_COUNTER_GET 13 #define ESDCAN_CTL_BITRATE_DETAILS_GET 14 #define ESDCAN_CTL_SER_REG_READ 15 #define ESDCAN_CTL_SER_REG_WRITE 16 #define ESDCAN_CTL_RESET_CAN_ERROR_CNT 17 #define ESDCAN_CTL_EEI_CREATE 18 #define ESDCAN_CTL_EEI_DESTROY 19 #define ESDCAN_CTL_EEI_STATUS 20 #define ESDCAN_CTL_EEI_CONFIGURE 21 #define ESDCAN_CTL_EEI_START 22 #define ESDCAN_CTL_EEI_STOP 23 #define ESDCAN_CTL_EEI_TRIGGER_NOW 24 #define ESDCAN_CTL_TX_TS_WIN_SET 25 #define ESDCAN_CTL_TX_TS_WIN_GET 26 #define ESDCAN_CTL_TX_TS_TIMEOUT_SET 27 #define ESDCAN_CTL_TX_TS_TIMEOUT_GET 28 #define ESDCAN_CTL_BAUDRATE_X_GET 29 #define ESDCAN_CTL_BAUDRATE_X_SET 30 #define ESDCAN_CTL_CAN_INFO 31 typedef union { UINT64 ul64[1]; UINT32 ul32[2]; VOID* ptr; } HOST_HND; typedef struct _CMSCHED CMSCHED; struct _CMSCHED { UINT32 id; INT32 flags; OSIF_TS timeStart; OSIF_TS timeInterval; UINT32 countStart; /* Start value for counting*/ UINT32 countStop; /* Stop value for counting. After reaching this value, the counter is loaded with the countStart value. */ }; typedef struct _CM CM; struct _CM { UINT32 id; /* can-id */ UINT8 len; /* length of message: 0-8 */ UINT8 msg_lost; /* count of lost rx-messages */ UINT8 reserved[1]; /* reserved */ UINT8 ecc; /* ECC (marks "broken" frames) */ #ifdef BOARD_CAN_FD UINT8 data[64]; /* 64 data-bytes */ #else UINT8 data[8]; /* 8 data-bytes */ #endif OSIF_TS timestamp; /* 64 bit timestamp */ HOST_HND host_hnd; }; typedef struct _VERSION96 { UINT32 level; UINT32 revision; UINT32 build; } VERSION96; typedef struct _CARD_IRQ { OSIF_IRQ_HANDLER( *handler, context); VOID *context; } CARD_IRQ; /* Use this to terminate cardFlavours arrays */ #define CARD_IDENT_TERMINATE {{ NULL, NULL, NULL, {0, 0, 0, 0, 0, 0, 0} }} /* Do not use these any more, just use the one above */ /* #define CARD_IDENT_PCI_TERMINATE {{ NULL, NULL, NULL, {0, 0, 0, 0, 0, 0, 0} }} */ /* #define CARD_IDENT_RAW_TERMINATE {{ NULL, NULL, NULL }} */ /* fj todo remove usage of CARD_IDENT_USB_TERMINATE */ #define CARD_IDENT_USB_TERMINATE {{ NULL, NULL, NULL, {0, 0} }} #define CARD_MAX_USB_ENDPOINTS 4 /* Devices may have up to 4 endpoints */ typedef union _CARD_IDENT { struct { CARD_IRQ *irqs; UINT32 *spaces; const CHAR8 *name; struct { UINT32 vendor; UINT32 device; UINT32 subVendor; UINT32 subDevice; UINT32 class; /* For future use, init with 0 */ UINT32 classMask; /* For future use, init with 0 */ UINTPTR misc; /* For future use, init with NULL */ } ids; } pci; struct { CARD_IRQ *irqs; UINT32 *spaces; const CHAR8 *name; } raw; struct { CARD_IRQ *irqs; UINT32 *spaces; const CHAR8 *name; struct { UINT32 vendor; UINT32 device; UINT32 numEndpoints; UINT32 endpoint[CARD_MAX_USB_ENDPOINTS]; } desc; } usb; struct { /* This part needs to be identical for all kinds of boards */ CARD_IRQ *irqs; UINT32 *spaces; const CHAR8 *name; } all; } CARD_IDENT; #define MAKE_VERSION(l,r,b) (UINT16)(((l) << 12) | ((r) << 8) | ((b) << 0)) #endif /* #ifndef __CM_H__ */
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/osif.h
/* -*- esdcan-c -*- * FILE NAME osif.h * * BRIEF MODULE DESCRIPTION * ... * * * history: * * 24.05.02 - first version mf * 27.10.03 - New output function osif_dprint (with verbose mask) ab * 13.11.03 - OSIF_BUSY_MUTEX_xxx added mt * 11.05.04 - Removed OSIF_EXTERN, added OSIF_CALLTYPE ab * 23.09.04 - Corrected endianess-macros and memcmp (please define * them in the osifi.h the respective system) ab * 28.09.06 - Added OSIF_PRIx64, OSIF_PRId64, OSIF_PRIu64 mk * 05.06.07 - Added OSIF_USLEEP and C_ASSERT ab * */ /************************************************************************ * * Copyright (c) 1996 - 2015 by esd electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd.eu * Germany sales@esd.eu * *************************************************************************/ /*! \file osif.h \brief OSIF header This file contains the OSIF prototypes and user macros. Any driver should call the OSIF_<xxx> macros instead of the osif_<xxx> functions. */ #ifndef __OSIF_H__ #define __OSIF_H__ #define OSIF_KERNEL #define OSIF_CALLTYPE #define OSIF_INLINE inline #define OSIF_STATIC static #define OSIF_REGISTER register #define OSIF_FUNCTION __FUNCTION__ /* Leave _before_ including osifi.h */ typedef struct _OSIF_TIMER OSIF_TIMER; #include <osiftypes.h> #include <osifi.h> #include <canio.h> #ifdef OSIF_MEMDBG # include <memdbg.h> #endif /* * Default definition for a pattern of the type * * do { code; } OSIF_ONCE * * where OSIF_ONCE can be defined in osifi.h in a target specific way that the * compiler does not generate warnings like 'condition always constant' or * 'code without effect'. */ #ifndef OSIF_ONCE # define OSIF_ONCE while(0) #endif #define OSIF_ATTACH() osif_attach() #define OSIF_DETACH() osif_detach() #ifdef OSIF_MEMDBG # define OSIF_MALLOC(s,p) osif_memdbg_malloc((s),(VOID**)(p), __FILE__, __LINE__) # define OSIF_FREE(p) osif_memdbg_free((p)) #else # define OSIF_MALLOC(s,p) osif_malloc((s),(VOID**)(p)) /*!< see osif_malloc(...) */ # define OSIF_FREE(p) osif_free((p)) /*!< see osif_free(...) */ #endif #define OSIF_MEMSET(p,v,s) osif_memset((p),(v),(s)) /*!< see osif_memset(...) */ #define OSIF_MEMCPY(d,s,n) osif_memcpy((d),(s),(n)) #define OSIF_MEMCMP(d,s,n) osif_memcmp((d),(s),(n)) #define OSIF_MEMMEM(s,sl,p,pl) osif_memmem((s),(sl),(p),(pl)) #define OSIF_MUTEX_CREATE(m) osif_mutex_create(m) #define OSIF_MUTEX_DESTROY(m) osif_mutex_destroy(m) #define OSIF_MUTEX_LOCK(m) osif_mutex_lock(m) #define OSIF_MUTEX_UNLOCK(m) osif_mutex_unlock(m) #define OSIF_IRQ_MUTEX_CREATE(im) osif_irq_mutex_create(im) #define OSIF_IRQ_MUTEX_DESTROY(im) osif_irq_mutex_destroy(im) #define OSIF_IRQ_MUTEX_LOCK(im) osif_irq_mutex_lock(im) #define OSIF_IRQ_MUTEX_UNLOCK(im) osif_irq_mutex_unlock(im) #define OSIF_IN_IRQ_MUTEX_LOCK(im) osif_in_irq_mutex_lock(im) #define OSIF_IN_IRQ_MUTEX_UNLOCK(im) osif_in_irq_mutex_unlock(im) #define OSIF_STRTOUL(pc,pe,b) osif_strtoul(pc,pe,b) #define OSIF_PRINT(fmt) osif_print fmt #define OSIF_DPRINT(fmt) osif_dprint fmt #define OSIF_SNPRINTF(args) osif_snprintf args #define OSIF_SLEEP(ms) osif_sleep(ms) #define OSIF_USLEEP(us) osif_usleep(us) #define OSIF_DPC_CREATE(d,f,a) osif_dpc_create((d),(f),(a)) #define OSIF_DPC_DESTROY(d) osif_dpc_destroy(d) #define OSIF_DPC_TRIGGER(d) osif_dpc_trigger(d) #ifndef OSIF_TIMER_SYS_PART #error "No system specific OSIF_TIMER_SYS_PART definition!" #endif /* General part of timer structure, equal on all systems */ /* Note: typedef _before_ including osifi.h */ struct _OSIF_TIMER { VOID *pTimerExt; /* Used for dynamic timer extensions, be it HW timers or OS specific stuff */ OSIF_TIMER_SYS_PART; /* On systems with stable and well defined APIs (ALL except Linux), this can be used to statically add the system specific stuff */ }; typedef struct _OSIF_CALLBACKS OSIF_CALLBACKS; struct _OSIF_CALLBACKS { INT32 (OSIF_CALLTYPE *timer_create)( OSIF_TIMER *t, VOID (OSIF_CALLTYPE *func)(VOID *), VOID *arg, VOID *pCanNode ); INT32 (OSIF_CALLTYPE *timer_destroy)( OSIF_TIMER *t ); INT32 (OSIF_CALLTYPE *timer_set)( OSIF_TIMER *t, UINT32 ms ); INT32 (OSIF_CALLTYPE *timer_get)( OSIF_TIMER *t, UINT32 *ms ); }; extern OSIF_CALLBACKS osif_callbacks; #define OSIF_TIMER_CREATE(t,f,a,n) osif_callbacks.timer_create((t),(f),(a),(n)) #define OSIF_TIMER_DESTROY(t) osif_callbacks.timer_destroy(t) #define OSIF_TIMER_SET(t,m) osif_callbacks.timer_set((t),(m)) #define OSIF_TIMER_GET(t,m) osif_callbacks.timer_get((t),(m)) /* ---------------------------------------------------------------- * DMA handling abstraction for forced flush and invalidate. * c = UINTPTR as context (pointer or value) * pc = address of UINTPTR context (pointer or value) * p = physical memory address of DMA area * b = virtual (CPU) base address of section to flush / invalidate * s = size of section */ #if OSIF_CACHE_DMA_DEFAULTS /* * Provide a default implementation for the * OSIF_DMA stuff if selected from osifi.h * by defining OSIF_CACHE_DMA_DEFAULTS. */ #ifndef OSIF_CACHE_DMA_ATTACH # define OSIF_CACHE_DMA_ATTACH(pc,p) (*(pc) = (UINTPTR)0) #endif #ifndef OSIF_CACHE_DMA_DETACH # define OSIF_CACHE_DMA_DETACH(pc,p) (*(pc) = (UINTPTR)0) #endif #ifndef OSIF_CACHE_DMA_FLUSH # define OSIF_CACHE_DMA_FLUSH(c,b,s) #endif #ifndef OSIF_CACHE_DMA_INVAL # define OSIF_CACHE_DMA_INVAL(c,b,s) #endif #endif /* OSIF_CACHE_DMA_DEFAULTS */ /* For documentation purposes prototypes for the functions that may be needed to implement in osif.c are added here. void osif_cache_dma_attach(UINTPTR *pContext, OSIF_PCI_PADDR *pBase); void osif_cache_dma_detach(UINTPTR *pContext, OSIF_PCI_PADDR *pBase); void osif_cache_dma_flush(UINTPTR context, OSIF_PCI_VADDR *pBase, UINT32 size); void osif_cache_dma_inval(UINTPTR context, OSIF_PCI_VADDR *pBase, UINT32 size); */ /* DMA handling abstraction done */ /* OSIF_PCI_MALLOC: * v - virtual address, p - bus address (e.g. PCI address), m - physical address */ #define OSIF_PCI_MALLOC(d,v,p,m,s) osif_pci_malloc((d),(v),(p),(m),(s)) #define OSIF_PCI_FREE(d,v,p,m,s) osif_pci_free((d),(v),(p),(m),(s)) #define OSIF_PCI_GET_PHY_ADDR(p) osif_pci_get_phy_addr(p) #define OSIF_PCI_READ_CONFIG_BYTE(a,b,c) osif_pci_read_config_byte((a),(b),(c)) #define OSIF_PCI_READ_CONFIG_WORD(a,b,c) osif_pci_read_config_word((a),(b),(c)) #define OSIF_PCI_READ_CONFIG_LONG(a,b,c) osif_pci_read_config_long((a),(b),(c)) #define OSIF_PCI_WRITE_CONFIG_BYTE(a,b,c) osif_pci_write_config_byte((a),(b),(c)) #define OSIF_PCI_WRITE_CONFIG_WORD(a,b,c) osif_pci_write_config_word((a),(b),(c)) #define OSIF_PCI_WRITE_CONFIG_LONG(a,b,c) osif_pci_write_config_long((a),(b),(c)) #define OSIF_SPI_XFER(a,b) osif_spi_xfer((a), (b)) #define OSIF_IRQ_ATTACH(i,h,n,a) osif_irq_attach((i),(h),(n),(a)) #define OSIF_IRQ_DETACH(i,a) osif_irq_detach((i),(a)) #define OSIF_TICKS osif_ticks() #ifndef OSIF_TICK_FREQ # define OSIF_TICK_FREQ osif_tick_frequency() #endif #define OSIF_IO_OUT8( addr, data ) osif_io_out8( (addr), (data) ) #define OSIF_IO_IN8( addr ) osif_io_in8( (addr) ) #define OSIF_IO_OUT16( addr, data ) osif_io_out16( (addr), (data) ) #define OSIF_IO_IN16( addr ) osif_io_in16( (addr) ) #define OSIF_IO_OUT32( addr, data ) osif_io_out32( (addr), (data) ) #define OSIF_IO_IN32( addr ) osif_io_in32( (addr) ) #define OSIF_MEM_OUT8( addr, data ) osif_mem_out8( (addr), (data) ) #define OSIF_MEM_IN8( addr ) osif_mem_in8( (addr) ) #define OSIF_MEM_OUT16( addr, data ) osif_mem_out16( (addr), (data) ) #define OSIF_MEM_IN16( addr ) osif_mem_in16( (addr) ) #define OSIF_MEM_OUT32( addr, data ) osif_mem_out32( (addr), (data) ) #define OSIF_MEM_IN32( addr ) osif_mem_in32( (addr) ) #define OSIF_READW(base, reg) (*(volatile UINT16*)((base)+(reg))) #define OSIF_WRITEW(base, reg, data) (*(volatile UINT16*)((base)+(reg))) = (data) #define OSIF_READLB(base, reg) (*(volatile UINT32*)((base)+(reg))) #define OSIF_WRITEL(base, reg, data) (*(volatile UINT32*)((base)+(reg))) = (data) #define OSIF_CPU2BE16(x) osif_cpu2be16(x) #define OSIF_CPU2BE32(x) osif_cpu2be32(x) #define OSIF_CPU2BE64(x) osif_cpu2be64(x) #define OSIF_BE162CPU(x) osif_be162cpu(x) #define OSIF_BE322CPU(x) osif_be322cpu(x) #define OSIF_BE642CPU(x) osif_be642cpu(x) #define OSIF_CPU2LE16(x) osif_cpu2le16(x) #define OSIF_CPU2LE32(x) osif_cpu2le32(x) #define OSIF_CPU2LE64(x) osif_cpu2le64(x) #define OSIF_LE162CPU(x) osif_le162cpu(x) #define OSIF_LE322CPU(x) osif_le322cpu(x) #define OSIF_LE642CPU(x) osif_le642cpu(x) #define OSIF_SWAP16(x) osif_swap16(x) #define OSIF_SWAP32(x) osif_swap32(x) #define OSIF_SWAP64(x) osif_swap64(x) #define OSIF_LOAD_FROM_FILE( d, f ) osif_load_from_file( d, f ) #define OSIF_DIV64_32(n, div) osif_div64_32(n, div) extern INT32 osif_div64_sft; /* if your board needs to divide by values larger than 0xFFFFFFFF, set osif_div64_sft respectively */ #define OSIF_DIV64_64(n, div) \ do { \ osif_div64_32((n), (UINT32)((div) >> osif_div64_sft)); \ (n) >>= osif_div64_sft; \ } OSIF_ONCE #ifndef OSIF_DIV64_SFT_FIXUP #define OSIF_DIV64_SFT_FIXUP() \ do { \ OSIF_TS_FREQ f; \ INT32 min_sft=0; \ f.tick=OSIF_TICK_FREQ; \ while(f.h.HighPart != 0) { \ min_sft++; \ f.tick >>= 1; \ } \ if (osif_div64_sft < min_sft) { \ osif_div64_sft = min_sft; \ } \ } OSIF_ONCE #endif #define OSIF_SER_OUT(str) osif_ser_out((str)) #define OSIF_MAKE_NTCAN_SERIAL(pszSerial, pulSerial) \ osif_make_ntcan_serial(pszSerial, pulSerial) /* * Macros to round up/down a value to a given multiple which has to be a power of 2. */ #define OSIF_ALIGN_UP(x, align) (((x) + (align - 1)) & ~((unsigned)(align - 1))) #define OSIF_ALIGN_DOWN(x, align) ((x) & ~((unsigned)(align - 1))) /* * Output-zones, use these defines together with OSIF_DPRINT to restrict output * of messages to certain zones. Only zones marked with the lowest byte can produce * output to the user in release-versions. All other versions are debug-only. */ #define OSIF_ZONE_NONE 0x00000000 /* no output */ #define OSIF_ZONE_USR_INIT 0x00000001 /* driver load/unload messages */ #define OSIF_ZONE_USR_INFO 0x00000002 /* detailed driver information and runtime msgs */ #define OSIF_ZONE_USR_RES3 0x00000004 /* reserved for future use */ #define OSIF_ZONE_USR_STAT 0x00000008 /* driver statistics on unload */ #define OSIF_ZONE_USR_RES5 0x00000010 /* reserved for future use */ #define OSIF_ZONE_USR_DBG 0x00000020 /* driver troubleshooting information */ #define OSIF_ZONE_USR_RES7 0x00000040 /* reserved for future use */ #define OSIF_ZONE_USR_RES8 0x00000080 /* reserved for future use */ #define OSIF_ZONE_BAUD 0x00020000 /* messages from bitrate calculation */ #define OSIF_ZONE_BM_MSI 0x00040000 /* messages from busmaster or MSI stuff */ #define OSIF_ZONE_FILTER 0x00080000 /* messages from id filter stuff */ #define OSIF_ZONE_ESDCAN 0x00100000 /* messages from esdcan-layer */ #define OSIF_ZONE_NUC 0x00200000 /* messages from nucleus */ #define OSIF_ZONE_BOARD 0x00400000 /* messages from board-layer */ #define OSIF_ZONE_CTRL 0x00800000 /* messages from controller-layer */ #define OSIF_ZONE_OSIF 0x01000000 /* messages from osif-layer */ #define OSIF_ZONE_FUNC 0x02000000 /* function entry/exit-messages */ #define OSIF_ZONE_PARAM 0x04000000 /* parameter output */ #define OSIF_ZONE_IRQ 0x08000000 /* messages from ISR (USE THIS ZONE ALONE!!!) */ #define OSIF_ZONE_BACKEND 0x10000000 /* output from backend run level */ #define OSIF_ZONE_INIT 0x20000000 /* output from drivers initialization */ #define OSIF_ZONE_WARN 0x40000000 /* warnings */ #define OSIF_ZONE_ERROR 0x80000000 /* error-messages */ /* * Under PCI, each device has 256 bytes of configuration address space, * of which the first 64 bytes are standardized as follows: */ #define OSIF_PCI_VENDOR_ID 0x00 /* 16 bits */ #define OSIF_PCI_DEVICE_ID 0x02 /* 16 bits */ #define OSIF_PCI_COMMAND 0x04 /* 16 bits */ #define OSIF_PCI_COMMAND_IO 0x01 /* Enable response in I/O space */ #define OSIF_PCI_COMMAND_MEMORY 0x02 /* Enable response in Memory space */ #define OSIF_PCI_COMMAND_MASTER 0x04 /* Enable bus mastering */ #define OSIF_PCI_COMMAND_SPECIAL 0x08 /* Enable response to special cycles */ #define OSIF_PCI_COMMAND_INVALIDATE 0x10 /* Use memory write and invalidate */ #define OSIF_PCI_COMMAND_VGA_PALETTE 0x20 /* Enable palette snooping */ #define OSIF_PCI_COMMAND_PARITY 0x40 /* Enable parity checking */ #define OSIF_PCI_COMMAND_WAIT 0x80 /* Enable address/data stepping */ #define OSIF_PCI_COMMAND_SERR 0x100 /* Enable SERR */ #define OSIF_PCI_COMMAND_FAST_BACK 0x200 /* Enable back-to-back writes */ #define OSIF_PCI_STATUS 0x06 /* 16 bits */ #define OSIF_PCI_STATUS_66MHZ 0x20 /* Support 66 Mhz PCI 2.1 bus */ #define OSIF_PCI_STATUS_UDF 0x40 /* Support User Definable Features */ #define OSIF_PCI_STATUS_FAST_BACK 0x80 /* Accept fast-back to back */ #define OSIF_PCI_STATUS_PARITY 0x100 /* Detected parity error */ #define OSIF_PCI_STATUS_DEVSEL_MASK 0x600 /* DEVSEL timing */ #define OSIF_PCI_STATUS_DEVSEL_FAST 0x000 #define OSIF_PCI_STATUS_DEVSEL_MEDIUM 0x200 #define OSIF_PCI_STATUS_DEVSEL_SLOW 0x400 #define OSIF_PCI_STATUS_SIG_TARGET_ABORT 0x800 /* Set on target abort */ #define OSIF_PCI_STATUS_REC_TARGET_ABORT 0x1000 /* Master ack of " */ #define OSIF_PCI_STATUS_REC_MASTER_ABORT 0x2000 /* Set on master abort */ #define OSIF_PCI_STATUS_SIG_SYSTEM_ERROR 0x4000 /* Set when we drive SERR */ #define OSIF_PCI_STATUS_DETECTED_PARITY 0x8000 /* Set on parity error */ #define OSIF_PCI_CLASS_REVISION 0x08 /* High 24 bits are class, low 8 revision */ #define OSIF_PCI_REVISION_ID 0x08 /* Revision ID */ #define OSIF_PCI_CLASS_PROG 0x09 /* Reg. Level Programming Interface */ #define OSIF_PCI_CLASS_DEVICE 0x0A /* Device class */ #define OSIF_PCI_CACHE_LINE_SIZE 0x0C /* 8 bits */ #define OSIF_PCI_LATENCY_TIMER 0x0D /* 8 bits */ #define OSIF_PCI_HEADER_TYPE 0x0E /* 8 bits */ #define OSIF_PCI_HEADER_TYPE_NORMAL 0 #define OSIF_PCI_HEADER_TYPE_BRIDGE 1 #define OSIF_PCI_HEADER_TYPE_CARDBUS 2 #define OSIF_PCI_BIST 0x0F /* 8 bits */ #define OSIF_PCI_BIST_CODE_MASK 0x0F /* Return result */ #define OSIF_PCI_BIST_START 0x40 /* 1 to start BIST, 2 secs or less */ #define OSIF_PCI_BIST_CAPABLE 0x80 /* 1 if BIST capable */ /* * Base addresses specify locations in memory or I/O space. * Decoded size can be determined by writing a value of * 0xffffffff to the register, and reading it back. Only * 1 bits are decoded. */ #define OSIF_PCI_BASE_ADDRESS_0 0x10 /* 32 bits */ #define OSIF_PCI_BASE_ADDRESS_1 0x14 /* 32 bits [htype 0,1 only] */ #define OSIF_PCI_BASE_ADDRESS_2 0x18 /* 32 bits [htype 0 only] */ #define OSIF_PCI_BASE_ADDRESS_3 0x1C /* 32 bits */ #define OSIF_PCI_BASE_ADDRESS_4 0x20 /* 32 bits */ #define OSIF_PCI_BASE_ADDRESS_5 0x24 /* 32 bits */ #define OSIF_PCI_BASE_ADDR_SPACE 0x01 /* 0 = memory, 1 = I/O */ #define OSIF_PCI_BASE_ADDR_SPACE_IO 0x01 #define OSIF_PCI_BASE_ADDR_SPACE_MEMORY 0x00 #define OSIF_PCI_BASE_ADDR_MEM_TYPE_MASK 0x06 #define OSIF_PCI_BASE_ADDR_MEM_TYPE_32 0x00 /* 32 bit address */ #define OSIF_PCI_BASE_ADDR_MEM_TYPE_1M 0x02 /* Below 1M */ #define OSIF_PCI_BASE_ADDR_MEM_TYPE_64 0x04 /* 64 bit address */ #define OSIF_PCI_BASE_ADDR_MEM_PREFETCH 0x08 /* prefetchable? */ #define OSIF_PCI_BASE_ADDR_MEM_MASK (~0x0FUL) #define OSIF_PCI_BASE_ADDR_IO_MASK (~0x03UL) /* bit 1 is reserved if address_space = 1 */ /* Header type 0 (normal devices) */ #define OSIF_PCI_CARDBUS_CIS 0x28 #define OSIF_PCI_SUBSYSTEM_VENDOR_ID 0x2C #define OSIF_PCI_SUBSYSTEM_ID 0x2E #define OSIF_PCI_ROM_ADDRESS 0x30 /* Bits 31..11 are address, 10..1 reserved */ #define OSIF_PCI_ROM_ADDRESS_ENABLE 0x01 #define OSIF_PCI_ROM_ADDRESS_MASK (~0x7FFUL) /* 0x34-0x3b are reserved */ #define OSIF_PCI_INTERRUPT_LINE 0x3C /* 8 bits */ #define OSIF_PCI_INTERRUPT_PIN 0x3D /* 8 bits */ #define OSIF_PCI_MIN_GNT 0x3E /* 8 bits */ #define OSIF_PCI_MAX_LAT 0x3F /* 8 bits */ /* Device power states */ typedef UINT32 OSIF_POWER_STATE; #define POWER_STATE_UNSPECIFIED 0U /* Power state undefined */ #define POWER_STATE_D0 1U /* Fully On is the operating state */ #define POWER_STATE_D1 2U /* Intermediate power-state */ #define POWER_STATE_D2 3U /* Intermediate power-state */ #define POWER_STATE_D3 4U /* Device powered off and unresponsive to its bus */ /* * System independent definition of USB relevant stuff, used in board layers */ typedef struct __OSIF_USB_EP OSIF_USB_EP; struct __OSIF_USB_EP { INT32 iDir; INT32 iType; INT32 iUse; }; #ifndef OSIF_USB_EP_DIR_DUMMY # define OSIF_USB_EP_DIR_DUMMY 0x00 /* Use to ignore entry */ #endif #ifndef OSIF_USB_EP_DIR_IN # define OSIF_USB_EP_DIR_IN 0x01 /* Endpoint direction IN (device->host) */ #endif #ifndef OSIF_USB_EP_DIR_OUT # define OSIF_USB_EP_DIR_OUT 0x02 /* Endpoint direction OUT (host->device) */ #endif #ifndef OSIF_USB_EP_TYPE_DUMMY # define OSIF_USB_EP_TYPE_DUMMY 0x00 /* Use to ignore entry */ #endif #ifndef OSIF_USB_EP_TYPE_CTRL # define OSIF_USB_EP_TYPE_CTRL 0x01 /* Endpoint type: Control */ #endif #ifndef OSIF_USB_EP_TYPE_ISOC # define OSIF_USB_EP_TYPE_ISOC 0x02 /* Endpoint type: Isochronous */ #endif #ifndef OSIF_USB_EP_TYPE_BULK # define OSIF_USB_EP_TYPE_BULK 0x03 /* Endpoint type: Bulk */ #endif #ifndef OSIF_USB_EP_TYPE_INT # define OSIF_USB_EP_TYPE_INT 0x04 /* Endpoint type: Interrupt */ #endif #ifndef OSIF_USB_EP_USE_NONE # define OSIF_USB_EP_USE_NONE -1 /* Endpoint usage: Don't use */ #endif #ifndef OSIF_USB_EP_USE_RX # define OSIF_USB_EP_USE_RX 0x00 /* Endpoint usage: RX channel */ #endif #ifndef OSIF_USB_EP_USE_TX # define OSIF_USB_EP_USE_TX 0x01 /* Endpoint usage: TX channel */ #endif #ifndef OSIF_USB_EP_USE_CMD # define OSIF_USB_EP_USE_CMD 0x02 /* Endpoint usage: Command channel */ #endif #define OSIF_USB_TYPE_CONTROL 0x00 #define OSIF_USB_TYPE_ISOCHRONOUS 0x01 #define OSIF_USB_TYPE_BULK 0x02 #define OSIF_USB_TYPE_INTERRUPT 0x03 #define OSIF_USB_DIR_OUT 0x00 #define OSIF_USB_DIR_IN 0x01 #define OSIF_USB_EP_DESC(no, dir, type) \ (((no) & 0x0F) | (((dir) & 0x1) << 7) | (((type) & 0x3) << 8)) #define OSIF_USB_REQ_HOST_TO_DEVICE 0x8000 #define OSIF_USB_REQ_DEVICE_TO_HOST 0x0000 /* * Macro to do a compile time size check */ #ifndef C_ASSERT # if defined(_MSC_VER) # define C_ASSERT(e) typedef char __C_ASSERT__[(e)?1:-1] # elif defined(__GNUC__) # define C_ASSERT(e) extern char __C_ASSERT__[(e)?1:-1] __attribute__((unused)) # else # define C_ASSERT(e) # endif #endif /* * Define the highest address which can be stored in a pointer */ #define OSIF_PTR_MAX (~(UINTPTR)0x0) /* * Macro with default definition for a pattern to mark a parameter as unused * in a function. */ #ifndef OSIF_UNUSED # define OSIF_UNUSED(arg) ((void)(arg)) #endif /* * Error codes (if not defined system specific) */ #ifndef OSIF_SUCCESS # define OSIF_SUCCESS CANIO_SUCCESS #endif #ifndef OSIF_ERROR # define OSIF_ERROR CANIO_ERROR #endif #ifndef OSIF_INVALID_PARAMETER # define OSIF_INVALID_PARAMETER CANIO_INVALID_PARAMETER #endif #ifndef OSIF_INVALID_HANDLE # define OSIF_INVALID_HANDLE CANIO_INVALID_HANDLE #endif #ifndef OSIF_NET_NOT_FOUND # define OSIF_NET_NOT_FOUND CANIO_NET_NOT_FOUND #endif #ifndef OSIF_INSUFFICIENT_RESOURCES # define OSIF_INSUFFICIENT_RESOURCES CANIO_INSUFFICIENT_RESOURCES #endif #ifndef OSIF_EAGAIN # define OSIF_EAGAIN CANIO_EAGAIN #endif #ifndef OSIF_EBUSY # define OSIF_EBUSY CANIO_EBUSY #endif #ifndef OSIF_RX_TIMEOUT # define OSIF_RX_TIMEOUT CANIO_RX_TIMEOUT #endif #ifndef OSIF_TX_TIMEOUT # define OSIF_TX_TIMEOUT CANIO_TX_TIMEOUT #endif #ifndef OSIF_TX_ERROR # define OSIF_TX_ERROR CANIO_TX_ERROR #endif #ifndef OSIF_CONTR_OFF_BUS # define OSIF_CONTR_OFF_BUS CANIO_CONTR_OFF_BUS #endif #ifndef OSIF_CONTR_BUSY # define OSIF_CONTR_BUSY CANIO_CONTR_BUSY #endif #ifndef OSIF_CONTR_WARN # define OSIF_CONTR_WARN CANIO_CONTR_WARN #endif #ifndef OSIF_OLDDATA # define OSIF_OLDDATA CANIO_OLDDATA #endif #ifndef OSIF_NO_ID_ENABLED # define OSIF_NO_ID_ENABLED CANIO_NO_ID_ENABLED #endif #ifndef OSIF_ID_ALREADY_ENABLED # define OSIF_ID_ALREADY_ENABLED CANIO_ID_ALREADY_ENABLED #endif #ifndef OSIF_ID_NOT_ENABLED # define OSIF_ID_NOT_ENABLED CANIO_ID_NOT_ENABLED #endif #ifndef OSIF_INVALID_FIRMWARE # define OSIF_INVALID_FIRMWARE CANIO_INVALID_FIRMWARE #endif #ifndef OSIF_MESSAGE_LOST # define OSIF_MESSAGE_LOST CANIO_MESSAGE_LOST #endif #ifndef OSIF_INVALID_HARDWARE # define OSIF_INVALID_HARDWARE CANIO_INVALID_HARDWARE #endif #ifndef OSIF_PENDING_WRITE # define OSIF_PENDING_WRITE CANIO_PENDING_WRITE #endif #ifndef OSIF_PENDING_READ # define OSIF_PENDING_READ CANIO_PENDING_READ #endif #ifndef OSIF_INVALID_DRIVER # define OSIF_INVALID_DRIVER CANIO_INVALID_DRIVER #endif #ifndef OSIF_WRONG_DEVICE_STATE # define OSIF_WRONG_DEVICE_STATE CANIO_WRONG_DEVICE_STATE #endif #ifndef OSIF_OPERATION_ABORTED # define OSIF_OPERATION_ABORTED CANIO_OPERATION_ABORTED #endif #ifndef OSIF_WRONG_DEVICE_STATE # define OSIF_WRONG_DEVICE_STATE CANIO_WRONG_DEVICE_STATE #endif #ifndef OSIF_HANDLE_FORCED_CLOSE # define OSIF_HANDLE_FORCED_CLOSE CANIO_HANDLE_FORCED_CLOSE #endif #ifndef OSIF_NOT_IMPLEMENTED # define OSIF_NOT_IMPLEMENTED CANIO_NOT_IMPLEMENTED #endif #ifndef OSIF_NOT_SUPPORTED # define OSIF_NOT_SUPPORTED CANIO_NOT_SUPPORTED #endif #ifndef OSIF_CONTR_ERR_PASSIVE # define OSIF_CONTR_ERR_PASSIVE CANIO_CONTR_ERR_PASSIVE #endif #ifndef OSIF_EFAULT # define OSIF_EFAULT CANIO_EFAULT #endif #ifndef OSIF_EIO # define OSIF_EIO CANIO_EIO #endif #ifndef OSIF_ERROR_NO_BAUDRATE # define OSIF_ERROR_NO_BAUDRATE CANIO_ERROR_NO_BAUDRATE #endif #ifndef OSIF_ERROR_LOM # define OSIF_ERROR_LOM CANIO_ERROR_LOM #endif #ifndef OSIF_EIO # define OSIF_EIO CANIO_EIO #endif #ifndef OSIF_ERESTART # define OSIF_ERESTART CANIO_ERESTART #endif /* macros used for printing 64 bit numbers */ #ifndef OSIF_PRIx64 # define OSIF_PRIx64 "llx" #endif #ifndef OSIF_PRId64 # define OSIF_PRId64 "lld" #endif #ifndef OSIF_PRIu64 # define OSIF_PRIu64 "llu" #endif /* Double stringification to convert value into "value" */ #define OSIF_STRINGIZE(str) #str #define OSIF_INT2STRING(val) OSIF_STRINGIZE(val) /* Build info string for several compilers/platforms */ #if defined(_MSC_VER) /* Microsoft C/C++ Compiler */ # ifdef _M_X64 # define OSIF_BUILD_INFO __DATE__ " @ " __TIME__ \ " with MSC V" OSIF_INT2STRING(_MSC_VER) " (64-Bit)" # else # define OSIF_BUILD_INFO __DATE__ " @ " __TIME__ \ " with MSC V" OSIF_INT2STRING(_MSC_VER) " (32-Bit)" # endif /* of _M_X64 */ #elif defined(__GNUC__) /* GNU Compiler Collection */ # if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)) /* GCC >= 4.9 */ # pragma GCC diagnostic ignored "-Wdate-time" # endif # define OSIF_BUILD_INFO __DATE__ " @ " __TIME__ \ " with GCC V" OSIF_INT2STRING(__GNUC__) "." OSIF_INT2STRING(__GNUC_MINOR__) #elif defined(_UCC) /* OS/9 Ultra C */ #define OSIF_BUILD_INFO __DATE__ " @ " __TIME__ \ " with UCC V" OSIF_INT2STRING(_MAJOR_REV) "." OSIF_INT2STRING(_MINOR_REV) #else # define OSIF_BUILD_INFO __DATE__ " @ " __TIME__ #endif /* of _MSC_VER */ /* * Macros to suppress MSC warnings. The MSC specific __pragma complements * the #pragma preprocessor directive but allows a usage in macros. See * http://msdn.microsoft.com/en-us/library/d9x1s805.aspx for details. */ #if defined(_MSC_VER) /*lint -emacro(19, MSC_DISABLE_*, MSC_ENABLE_*) */ /* Useless Declaration */ /* * MSC_SUPPRESS_WARNING stores the current state for all warnings, disables * the specified warning w for the next line, and then restores the warning * stack. */ # define MSC_DISABLE_WARNING_ONCE(w) __pragma(warning(suppress:w)) /* * MSC_DISABLE_WARNING stores the current state for all warnings and disables * the specified warning(s) |w|. The warning(s) remain disabled until the * warning stack is restored by MSC_ENABLE_WARNING. Several warning numbers * have to be separated by blanks. */ # define MSC_DISABLE_WARNING(w) __pragma(warning(push)) \ __pragma(warning(disable:w)) /* * MSC_DISABLE_WARNING_LEVEL stores the current state for all warnings and * sets the global warning level to l (1..4). The level remains in effect * until restored by MSC_ENABLE_WARNING. Use 0 to disable all warnings. */ # define MSC_DISABLE_WARNING_LEVEL(l) __pragma(warning(push, l)) /* Reverses effects of innermost MSC_DISABLE_* macro. */ # define MSC_ENABLE_WARNING __pragma(warning(pop)) /* Control the MSC optimizer */ # define MSC_DISABLE_OPTIMIZER __pragma(optimize("", off)) # define MSC_ENABLE_OPTIMIZER __pragma(optimize("", on)) #else /* Define this for !MSC compilers to use it without compiler check */ # define MSC_VERSION_AT_LEAST(version) 0 /* Empty defines for !MSC compilers to suppress warnings */ # define MSC_DISABLE_WARNING_ONCE(w) # define MSC_DISABLE_WARNING(w) # define MSC_DISABLE_WARNING_LEVEL(l) # define MSC_ENABLE_WARNING /* Empty defines for !MSC compilers to control the optimizer */ # define MSC_DISABLE_OPTIMIZER # define MSC_ENABLE_OPTIMIZER #endif /* of _MSC_VER */ /* * Used for internal split handling of 64-bit timestamps */ typedef union { UINT64 tick; struct { #ifdef OSIF_LITTLE_ENDIAN UINT32 LowPart; UINT32 HighPart; #endif #ifdef OSIF_BIG_ENDIAN UINT32 HighPart; UINT32 LowPart; #endif } h; } OSIF_TS, OSIF_TS_FREQ; /* * Used for double linked list with reference to base object. * * Helper macros and code are part of the nucleus as OSIF has no common code */ typedef struct _LNK LNK; struct _LNK { LNK *next; LNK *prev; VOID *base; }; #endif
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/esdcan_common.c
/* -*- esdcan-c -*- * FILE NAME esdcan_common.c * copyright 2002-2014 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * This file contains the common entries * for Linux/IRIX * for the esd CAN driver * * * Author: Matthias Fuchs * matthias.fuchs@esd-electronics.com * * history: * * $Log$ * Revision 1.126 2015/06/30 13:20:52 stefanm * Changes and fixes to adapt the sources to the split of CAN_STAT into * CAN_BUS_STAT and an enclosing CAN_NODE_STAT structure. * * Revision 1.125 2015/05/08 18:13:44 stefanm * Replaced CAN_TIMESTAMP with size of structure field to get * rid of CAN_TIMESTAMP. * * Revision 1.124 2015/05/08 16:39:07 stefanm * Rename CAN_TS and CAN_TS_FREQ to OSIF_TS and OSIF_TS_FREQ. * This should now also be used instead of CAN_TIMESTAMP / TIMESTAMP * in the whole esdcan driver tree. * * Revision 1.123 2015/03/06 16:52:57 mschmidt * Adapted drv/esdcan_common.c to changes in linux kernel versions 3.19 and 4.0. * * Revision 1.122 2015/01/13 15:31:02 stefanm * Added support for NTCAN_IOCTL_GET_INFO / IOCTL_ESDCAN_GET_INFO. * Will now count active nodes in <num_nodes> of card structure. * New <version_firmware2> is needed for USB400 Cypress updateable FW. * * Revision 1.121 2015/01/09 15:17:53 stefanm * Provide a real board status for the canStatus() call which is kept * now in the card structure. * Keep the updater working by NOT checking for wrong FW in the * IOCTL_ESDCAN_SET_TIMEOUT which is called by canOpen() implicitely. * * Revision 1.120 2014/12/18 11:45:15 manuel * Need to set tx.state before nuc_tx call because nuc_tx might call esdcan_tx_done synchronously. * * Revision 1.119 2014/12/17 18:49:16 hauke * Fixed missing closing bracket in esdcan_read_common * * Revision 1.118 2014/11/04 15:34:50 stefanm * Merged changes from fixes-for-RST-1 into trunk. * The fix was already included by Manuel's last commit * so there are only log updates. * * Revision 1.113.2.1 2014/10/31 17:45:20 stefanm * Moving the ocb->tx.state update after the the successful * return of nuc_tx() preserves an old valid ocb->tx.state. * This fixes the hang on canClose() that was detected by * RST (see Mantis #2461). * * Revision 1.117 2014/11/03 12:43:45 manuel * Improved state check in esdcan_rx_done and esdcan_tx_done. * Added code for debugging hanging close. * Fixed clobbering of tx.state in case nuc_tx fails. * Completely removed PENDING_TXOBJ states (TXOBJ does not use tx_done!). * * Revision 1.116 2014/10/07 12:44:12 manuel * Fixed brackets * * Revision 1.115 2014/09/26 11:00:54 michael * OBJ-MODE for RX rewritten. 11 Bit CAN-ID limit removed. * * Revision 1.114 2014/08/21 13:19:11 manuel * Added CAN_FD support * * Revision 1.113 2014/05/20 13:22:54 andreas * Comment changed * * Revision 1.112 2013/09/19 16:20:39 manuel * Fixed missing setting cm_count in tx_done (non PREEMT_RT version) * * Revision 1.111 2013/09/11 13:27:28 andreas * Fixed cast * * Revision 1.110 2013/08/30 16:57:33 manuel * Fixed a bug where canRead falls through using old frames after a canTake has taken some frames. * The canRead was then pending in the nucleus although it returned to the user. * * Revision 1.109 2013/08/01 14:42:32 andreas * Two (!) bugfixes in esdcan_tx_done: * - one typo without implications: RX_STATE_SIGNAL_INTERRUPT was used instead of TX_STATE_SIGNAL_INTERRUPT * - major fix: tx.cm_count was not reset on end of canSend(), leading to wrongly returned len on following TX calls * * Revision 1.108 2013/06/27 12:09:10 andreas * Changes of TX-TS window size (IOCTL) are handled by nucleus, now * * Revision 1.107 2013/04/26 14:35:24 andreas * canWriteT() works the same as canSendT() from now on * * Revision 1.106 2013/01/18 16:59:54 andreas * Fixed forgotten change for new structure of CAN_OCB (with RX and TX substructures) * * Revision 1.105 2013/01/11 18:25:38 andreas * Added IOCTL_SET_HND_FILTER * Added canRegionAdd()/canRegionDelete() * Added TX_TS IOCTLs * Changes for timestamped TX (zeroing timestamp on canWriteT CMSG_Ts) * Reworked CAN_OCB structure with rx and tx substructures (like in other esdcan layers) * * Revision 1.104 2013/01/03 16:21:27 andreas * Updated copyright notice * * Revision 1.103 2012/11/21 16:04:31 manuel * Fixed signed/unsigned mixup * * Revision 1.102 2012/11/08 14:14:42 andreas * Fixed bug on handle close (two threads entering driver on same handle with ioctl_destroy) * * Revision 1.101 2012/02/17 18:52:51 andreas * Fixed OSIF_CALLTYPE position * * Revision 1.100 2011/11/04 14:46:32 andreas * Removed single line comments * Tiny cleanup * * Revision 1.99 2011/11/01 15:29:20 andreas * Merged with preempt_rt branch * With OSIF_USE_PREEMPT_RT_IMPLEMENTATION the new implementation is used for * all kernels > 2.6.20 * Cleanup and whitespace changes * Updated copyright notice * * Revision 1.98 2011/08/31 12:52:03 manuel * Added EEI stuff * * Revision 1.97 2011/05/18 15:59:51 andreas * Changed to make use of CHAR8 * Changed CAN_ACTION_CHECK macro slightly * Another fix in esdcan_read_common (removed sema_rx_abort) * Some cleanup * * Revision 1.96 2010/12/10 16:44:55 andreas * Added IOCTL_ESDCAN_RESET_CAN_ERROR_CNT * * Revision 1.95 2010/11/26 15:49:58 andreas * Removed redundant parameter on esdcan_ioctl_internal() * * Revision 1.94 2010/08/30 10:15:19 andreas * Fixed 29-Bit filter (AMR wrongly initialized) * * Revision 1.93 2010/06/16 15:18:52 manuel * Made compileable for linux again * * Revision 1.92 2010/06/16 14:50:31 michael * Smart id filter nucleus support. * New filter not yet connected to user api. * 2nd trial. * * Revision 1.91 2010/06/16 12:49:13 manuel * Use CANIO_ID_20B_BASE instead of CANIO_20B_BASE * * Revision 1.90 2010/04/16 16:24:25 andreas * "Fixed" boardstatus in CAN_DEBUG ioctl (actually removed wrong code, only * and made room for a fix in phase two ;) * Correctly added ctrl_type to CAN_DEBUG ioctl * * Revision 1.89 2010/03/16 10:31:20 andreas * Added esdcan_rx_notify() and esdcan_poll() for select implementation * * Revision 1.88 2010/03/11 12:35:22 manuel * Added nuc_check_links (used only if NUC_CHECK_LINKS is set) * * Revision 1.87 2009/07/31 14:17:05 andreas * FUNCTIONAL CHANGE (!!!): Timeout is no longer multiplied with number of * frames on canWrite() * Add IOCTL_ESDCAN_SER_REG_READ and IOCTL_ESDCAN_SER_REG_WRITE * * Revision 1.86 2009/07/29 05:01:38 tkoerper * - Fixed copying bus statistics * * Revision 1.85 2009/06/16 12:54:02 andreas * Fixed canRead(), length wasn't returned correctly anymore since last checkin * * Revision 1.84 2009/04/22 14:32:03 andreas * Another fix for signal handling in canRead(). * Forgot to reset rx.cm_count. * * Revision 1.83 2009/02/25 16:45:00 andreas * Added IOCTL_ESDCAN_GET_BUS_STATISTIC, IOCTL_ESDCAN_RESET_BUS_STATISTIC, * IOCTL_ESDCAN_GET_ERROR_COUNTER, IOCTL_ESDCAN_GET_BITRATE_DETAILS * Fixed IOCTL_ESDCAN_SET_BUSLOAD_INTERVAL, IOCTL_ESDCAN_GET_BUSLOAD_INTERVAL * Fixed canRead() and canWrite(), when interrupted by signal * (several bugs), SIGSTOP and SIGCONT should work as expected, now * Replaced usage of OSIF_SEMA_- with direct usage of down(), up(), etc. * Removed old RTAI-paths * * Revision 1.82 2008/08/27 13:48:11 andreas * Fixed zone of several debug outputs to OSIF_ZONE_IRQ * * Revision 1.81 2008/06/06 14:12:48 andreas * Fixed IOCTLS without parameter (DESTROY, FLUSH_RX_FIFO, PURGE_TX_FIFO, * SCHEDULE_START, SCHEDULE_STOP, SET_ALT_RTR_ID) for 32-Bit applications * on x86_64 Linux with kernels > 2.6.10 * * Revision 1.80 2008/06/03 19:15:20 manuel * Removed IOCTL_ESDCAN_DEBUG support when ocb==0 * (when no IOCTL_ESDCAN_CREATE was done) for now. * This breaks the support for very old firmware-updaters. * * Revision 1.79 2008/05/23 13:49:08 andreas * Removed timeout on canSend() (finally!!!) * * Revision 1.78 2008/03/20 11:27:46 andreas * Adapted new way of I20 firmware update * * Revision 1.77 2007/11/05 14:58:07 andreas * Added IOCTL_ESDCAN_SET_BUSLOAD_INTERVAL and IOCTL_ESDCAN_GET_BUSLOAD_INTERVAL * * Revision 1.76 2006/11/16 12:39:44 andreas * Fixed rx object (flat) mode * * Revision 1.75 2006/10/12 09:53:26 andreas * Replaced some forgotten CANIO_-error codes with the OSIF_ counterparts * Replaces some errnos with their OSIF_counterparts * Cleaned up return of error codes to user space, * please use positive error codes, only!!! * * Revision 1.74 2006/10/11 10:13:31 andreas * Fixed warnings about ignoring return value from copy_to_user * * Revision 1.73 2006/08/17 13:26:59 michael * Rebirth of OSIF_ errorcodes * * Revision 1.72 2006/07/04 12:40:35 andreas * Added some missing (although deprecated) IOCTLs. * Sorted OSIF_NOT_IMPLEMENTED and OSIF_NOT_SUPPORTED errors. * * Revision 1.71 2006/06/27 13:13:12 andreas * Exchanged OSIF_errors with CANIO_errors * * Revision 1.70 2006/06/27 09:55:19 andreas * Added CAN controller type to canStatus info * Use CANIO defines for baudrates, where possible * * Revision 1.69 2006/04/28 12:31:59 andreas * Added compat_ioctl and unlocked_ioctl * * Revision 1.68 2006/03/07 19:20:25 manuel * canWrite will now work after a canSend on the same handle which has not completely been sent. Timeout applies to all frames from old canSend and canWrite. Len will count only frames from the canWrite. Won\'t work with deferred_tx. If deferred_tx is in the queue, canWrite will return with PENDING_WRITE. * * Revision 1.67 2005/12/06 13:25:16 andreas * No functional changes. Removed some old "#if 0" paths and small cleanup. * * Revision 1.66 2005/11/02 14:12:46 andreas * Added missing OSIF_CALLTYPE to esdcan_ioctl_done() * * Revision 1.65 2005/11/02 07:11:04 andreas * Change for PCI405: sleep_on() is deprecated in kernels > 2.6.x * Corrected canStatus (status field is zero now and not driver mode, * features are masked with FEATURE_MASK_DOCUMENTED) * Added IOCTL_ESDCAN_SET_RX_TIMEOUT * Added IOCTL_ESDCAN_SET_TX_TIMEOUT * Added IOCTL_ESDCAN_GET_SERIAL * Added IOCTL_ESDCAN_GET_FEATURES * * Revision 1.64 2005/10/06 07:37:54 matthias * -added esdcan_ioctl handling * * Revision 1.63 2005/09/14 15:59:11 michael * filter 20b added * * Revision 1.62 2005/08/23 14:45:54 andreas * Fixed broken canIdDelete * * Revision 1.61 2005/07/29 08:19:11 andreas * crd-structure stores pointer (pCardIdent) into cardFlavours structure instead of index (flavour), now * * Revision 1.60 2005/07/28 07:21:53 andreas * Added calltype to esdcan_tx_obj_sched_get * Removed BOARD define, board name is retrieved from "cardFlavours" array (defined in boardrc.c) * * Revision 1.59 2005/06/21 10:48:12 michael * TX_OBJ_SCHEDULING added * * Revision 1.58 2005/06/08 09:20:24 andreas * Removed timeout for canTake (nuc_rx call with timeout zero) * * Revision 1.57 2005/04/28 15:27:00 andreas * Changed board names (match old candev-driver, now) * * Revision 1.56 2005/04/20 13:42:54 andreas * Changed for 64-Bit Linux (ioctl-wrapper, C-types,...) * Cleanup * * Revision 1.55 2005/03/22 09:53:10 matthias * added debug output to see timestamp just before they reac hthe userspace * * Revision 1.54 2005/03/10 17:01:09 michael * CAN_ACTION_CHECK Macro for Hardware/Firmware validation * * Revision 1.53 2005/02/21 15:24:39 matthias * -because CM-size increased we have to copy CMSG and CMSG_T struct from/to userspace * * Revision 1.52 2004/12/02 15:53:48 stefan * Please don't use "//" comments!!! * * Revision 1.51 2004/10/29 14:59:51 matthias * -removed TICKS code for DEFERRED TX (now use real timestamps) * -removed unused code * * Revision 1.50 2004/10/11 09:16:38 andreas * Changed debug output to use zones * Fixed deadlock for USB331 * * 11.05.04 - Changed OSIF_EXTERN into extern and OSIF_CALLTYPE ab * 03.03.04 - TX_OBJ-ioctl-case changed * TX_OBJ_ENABLE-ioctl added ab * 26.02.04 - New IOCTL Interface (=> No use of cm->reserved) * canRead and canWrite as IOCTL for linux too * New IOCTLS: ...READ_T...TAKE_T...WRITE_T mt * 04.02.04 - Corrected read+write to return ERESTARTSYS after * they've been interrupted by a signal ab * 13.11.03 - USB331-Support added (THIS IS STILL BETA!!!) * USB-specific stuff is implemented in esdcan.c. * There are NO effects for non-USB-cards. Nevertheless * some cleanup is still needed. ab * 29.09.03 - canTake doesn't return EIO anymore (also library * changed) * - read/write common: linux also has node-mutex already * (same as IRIX IOCTRL) sr * 15.01.03 - esdcan_common started for Linux/RTAI/IRIX sr * 21.11.02 - start of irix version based on linux version sr * 18.11.02 - added callback interface for nucleus mf * 07.11.02 - Version 0.1.1 mf * 21.05.02 - added hardware timestamping (Version 0.1.0) mf * 17.05.02 - first release (Version 0.1.0) mf * 02.05.02 - first version mf * */ /************************************************************************ * * Copyright (c) 1996 - 2014 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd-electronics.com * Germany sales@esd-electronics.com * *************************************************************************/ /*! \file esdcan_common.c \brief common driver entries This file contains the common entries for the es CAN driver. */ #if LINUX_VERSION_CODE < KERNEL_VERSION(3,19,0) # define file_inode(x) (x->f_dentry->d_inode) #elif LINUX_VERSION_CODE < KERNEL_VERSION(4,0,0) # define file_inode(x) (x->f_path.dentry->d_inode) #endif /* block attempts to access cards with wrong firmware or hardware version */ #define CAN_ACTION_CHECK(ocb, result, action) \ if ( (ocb->node->status) & (CANIO_STATUS_WRONG_HARDWARE | CANIO_STATUS_WRONG_FIRMWARE) ) { \ if ( (ocb->node->status) & CANIO_STATUS_WRONG_HARDWARE ) { \ result = OSIF_INVALID_HARDWARE; \ } else { \ result = OSIF_INVALID_FIRMWARE; \ } \ action; \ } INT32 OSIF_CALLTYPE esdcan_close_done( CAN_OCB *ocb ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: enter (ocb = %p)\n", OSIF_FUNCTION, ocb)); #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION ocb->close_state |= CLOSE_STATE_CLOSE_DONE; wake_up(&ocb->wqCloseDelay); #else up(&ocb->sema_close); #endif CAN_DBG((ESDCAN_ZONE_FU, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE esdcan_tx_done( CAN_OCB *ocb, INT32 result, UINT32 cm_count ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: enter, result=%d, cm_count=%d\n", OSIF_FUNCTION, result, cm_count)); ocb->tx.result = result; #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION if (ocb->tx.state & TX_STATE_PENDING_SEND) { /* asynchronous TX done, nobody's waiting, but yet needed as canSend() left without resetting state */ ocb->tx.cm_count = 0; ocb->tx.state = 0; } else if (ocb->tx.state & TX_STATE_SIGNAL_INTERRUPT) { ocb->tx.cm_count = cm_count; ocb->tx.state &= ~TX_STATE_SIGNAL_INTERRUPT; wake_up(&ocb->wqTx); } else if (ocb->tx.state & TX_STATE_PENDING_WRITE) { /* synchronous TX finished normally */ ocb->tx.cm_count = cm_count; if (cm_count == 0) { ocb->tx.state |= TX_STATE_ABORT; } wake_up_interruptible(&ocb->wqTx); } else { OSIF_PRINT(("%s: spurious tx_done? tx.state=0x%x\n", ESDCAN_DRIVER_NAME, (unsigned int)ocb->tx.state)); } #else if ( ocb->tx.state & TX_STATE_PENDING_SEND ) { ocb->tx.cm_count = 0; ocb->tx.state = 0; } else if (ocb->tx.state & TX_STATE_ABORTING) { ocb->tx.cm_count = cm_count; up( &ocb->sema_tx_abort ); } else if (ocb->tx.state & TX_STATE_PENDING_WRITE) { ocb->tx.cm_count = cm_count; up( &ocb->sema_tx ); } else { OSIF_PRINT(("%s: spurious tx_done? tx.state=0x%x\n", ESDCAN_DRIVER_NAME, (unsigned int)ocb->tx.state)); } #endif CAN_DBG((ESDCAN_ZONE_FU, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE esdcan_tx_get( CAN_OCB *ocb, CM *cm ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: enter (tx.user_buf tx_obj_size=%d)\n", OSIF_FUNCTION, ocb->tx.cm_size)); /* copy the first CAN_MSG/CM from user space to cm */ #ifndef BOARD_CAN_FD if (ocb->tx.cm_size == sizeof(CAN_MSG_X)) { /* we need to copy a CAN_MSG_X into a CAN_MSG_T */ CAN_MSG_X tmp; if (copy_from_user(&tmp, ocb->tx.user_buf, sizeof(CAN_MSG_X))) { CAN_DBG((ESDCAN_ZONE_FU, "%s: copy_from_user failed (ocb=%x)\n", OSIF_FUNCTION, ocb)); return OSIF_EFAULT; } memcpy(cm,&tmp,sizeof(CAN_MSG)); cm->timestamp.tick = tmp.timestamp.tick; goto esdcan_tx_get_done; } #endif if (copy_from_user(cm, ocb->tx.user_buf, ocb->tx.cm_size)) { CAN_DBG((ESDCAN_ZONE_FU, "%s: copy_from_user failed (ocb=%x)\n", OSIF_FUNCTION, ocb)); return OSIF_EFAULT; } if (ocb->tx.cm_size == sizeof(CAN_MSG)) { cm->timestamp.tick = 0LL; #ifdef BOARD_CAN_FD } else if (ocb->tx.cm_size == sizeof(CAN_MSG_T)) { /* we have just copied a CAN_MSG_T into a CAN_MSG_X, fix the timestamp */ cm->timestamp.tick = ((CAN_MSG_T *)cm)->timestamp.tick; #endif } #ifndef BOARD_CAN_FD esdcan_tx_get_done: #endif ocb->tx.user_buf += ocb->tx.cm_size; CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (id= %x len=%x)\n", OSIF_FUNCTION, cm->id, cm->len)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE esdcan_tx_obj_get( CAN_OCB *ocb, CM *cm ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: enter\n", OSIF_FUNCTION)); /* copy the first 16 bytes (CAN_MSG) from user space to cm */ if (copy_from_user(cm, ocb->tx.user_buf, sizeof(CAN_MSG))) { return OSIF_EFAULT; } ocb->tx.user_buf += sizeof(CAN_MSG); CAN_DBG((ESDCAN_ZONE_FU, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE esdcan_tx_obj_sched_get( CAN_OCB *ocb, CMSCHED *sched) { CAN_DBG((ESDCAN_ZONE_FU, "%s: enter\n", OSIF_FUNCTION)); /* copy the first 16 bytes (CAN_MSG) from user space to cm */ if (copy_from_user(sched, ocb->tx.user_buf, sizeof(CMSCHED))) { return OSIF_EFAULT; } ocb->tx.user_buf += sizeof(CMSCHED); CAN_DBG((ESDCAN_ZONE_FU, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE esdcan_rx_done( CAN_OCB *ocb, INT32 result, UINT32 cm_count ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: enter, result=%d, cm_count=%d\n", OSIF_FUNCTION, result, cm_count)); ocb->rx.result = result; ocb->rx.cm_count = cm_count; #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION if (ocb->rx.state & RX_STATE_PENDING_TAKE) { ocb->rx.state = 0; /* actually redundant */ } else if (ocb->rx.state & RX_STATE_SIGNAL_INTERRUPT) { /* This was triggered by "interrupted by signal" branch in esdcan_read_common */ ocb->rx.state &= ~RX_STATE_SIGNAL_INTERRUPT; wake_up(&ocb->wqRx); } else if (ocb->rx.state & RX_STATE_PENDING_READ) { /* Wake pending canRead() */ if (ocb->rx.cm_count == 0) { /* timeout occurred */ ocb->rx.state |= RX_STATE_ABORT; /* set only to wake esdcan_read_common, with no frames received */ } wake_up_interruptible(&ocb->wqRx); } else { OSIF_PRINT(("%s: spurious rx_done? rx.state=0x%x\n", ESDCAN_DRIVER_NAME, (unsigned int)ocb->rx.state)); } #else if ( ocb->rx.state & RX_STATE_PENDING_TAKE ) { ocb->rx.state = 0; } else if (ocb->rx.state & RX_STATE_PENDING_READ) { /* Wake pending canRead() (normal branch, if RX works without interruption) */ up( &ocb->sema_rx ); } else { OSIF_PRINT(("%s: spurious rx_done? rx.state=0x%x\n", ESDCAN_DRIVER_NAME, (unsigned int)ocb->rx.state)); } #endif CAN_DBG((ESDCAN_ZONE_FU, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } /*! \fn esdcan_rx_put( CAN_OCB *ocb, CM *cm ); * \brief copy received CM into ocb's rx buffer * \param ocb open control block for this driver instance * \cm pointer to a CM structure that contains the recieved CAN message. * Only the first part containing a CAN_MSG is copied to the \a rx.cmbuf of the ocb structure. * \return OSIF_SUCCESS */ INT32 OSIF_CALLTYPE esdcan_rx_put( CAN_OCB *ocb, CM *cm ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: enter\n", OSIF_FUNCTION)); /* Attention: we only copy the CAN_MSG_[TX] part (16 bytes) of the CM into the receive buffer */ OSIF_MEMCPY(ocb->rx.cmbuf_in++, cm, sizeof(*ocb->rx.cmbuf_in)); CAN_DBG((ESDCAN_ZONE_FU, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE esdcan_rx_obj_put( CAN_OCB *ocb, CM *cm, UINT32 *next_id ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: enter\n", OSIF_FUNCTION)); OSIF_MEMCPY(ocb->rx.cmbuf_in++, cm, sizeof(*ocb->rx.cmbuf_in)); ocb->rx.user_buf += ocb->rx.cm_size; if (next_id) { UINT32 id = CANIO_ID_INVALID; if (get_user(id, &((CAN_MSG*)ocb->rx.user_buf)->id)) { return OSIF_EFAULT; } *next_id = id; } CAN_DBG((ESDCAN_ZONE_FU, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE esdcan_rx_notify( CAN_OCB *ocb ) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) wake_up_interruptible(&ocb->node->wqRxNotify); /* wake select */ #endif return OSIF_SUCCESS; } typedef struct { INT32 status; wait_queue_head_t wq; } IOCTL_WAIT_CONTEXT; INT32 OSIF_CALLTYPE esdcan_ioctl_done( CAN_OCB *ocb, VOID *waitContext, UINT32 cmd, INT32 status, UINT32 len_out ) { IOCTL_WAIT_CONTEXT *wait = (IOCTL_WAIT_CONTEXT *)waitContext; CAN_DBG((OSIF_ZONE_IRQ, "%s: enter (waitContext = %p)\n", OSIF_FUNCTION, waitContext)); wait->status = status; wake_up(&wait->wq); CAN_DBG((OSIF_ZONE_IRQ, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } NUC_CALLBACKS esdcan_callbacks = { esdcan_close_done, esdcan_tx_done, esdcan_tx_get, esdcan_tx_obj_get, esdcan_tx_obj_sched_get, esdcan_rx_done, esdcan_rx_put, esdcan_rx_obj_put, esdcan_ioctl_done, esdcan_rx_notify }; static INT32 id_filter( CAN_OCB *ocb, CAN_NODE *node, UINT32 cmd, UINT32 id_start, UINT32 *count ) { INT32 result = OSIF_SUCCESS; UINT32 count_to_do; UINT32 count_done; if (id_start & CANIO_ID_20B_BASE) { count_to_do = CANIO_IDS_20B; result = nuc_id_filter(ocb, cmd, CANIO_ID_20B_BASE, &count_to_do); if (result == OSIF_SUCCESS) { nuc_id_filter_mask(ocb, id_start, ocb->filter20b.amr, CANIO_IDS_REGION_20B); ocb->filter20b.acr = id_start; } else { *count = 0; } } else { count_to_do = *count; count_done = 0; do { result = nuc_id_filter(ocb, cmd, id_start + count_done, &count_to_do); CAN_DBG((ESDCAN_ZONE, "%s: nuc_id_filter returns %x\n", OSIF_FUNCTION, result)); count_done += count_to_do; count_to_do = *count - count_done; if (OSIF_EAGAIN == result) { OSIF_MUTEX_UNLOCK(&node->lock); OSIF_SLEEP(1); OSIF_MUTEX_LOCK(&node->lock); } } while ( (result == OSIF_EAGAIN) && (count_done < *count) ); *count = count_done; } return result; } /* only allocate ocb... */ static INT32 ocb_create( INT32 net_no, CAN_OCB **newocb ) { INT32 result = OSIF_SUCCESS; CAN_OCB *ocb; VOID *vptr; CAN_DBG((ESDCAN_ZONE_FU, "%s:ocb_create: enter\n", OSIF_FUNCTION)); /* check if node is available */ if ( (net_no >= (MAX_CARDS * NODES_PER_CARD)) || (NULL == nodes[net_no]) ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: node %d not available\n", OSIF_FUNCTION,net_no)); return OSIF_NET_NOT_FOUND; } #if defined (BOARD_USB) if (USB_OK != ((USB_MODULE*)((CAN_CARD*)nodes[net_no]->crd)->p_mod)->usb_status) { CAN_DBG((ESDCAN_ZONE_FU, "%s: node %d not available (usb not ready)\n", OSIF_FUNCTION, net_no)); return OSIF_NET_NOT_FOUND; } #endif /* allocate an OCB */ CAN_DBG((ESDCAN_ZONE, "%s: allocate OCB\n", OSIF_FUNCTION)); result = OSIF_MALLOC(sizeof(CAN_OCB),&vptr); if (result != OSIF_SUCCESS) { return result; } ocb = (CAN_OCB*)vptr; OSIF_MEMSET(ocb, 0, sizeof(CAN_OCB)); #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION init_waitqueue_head(&ocb->wqRx); init_waitqueue_head(&ocb->wqTx); init_waitqueue_head(&ocb->wqCloseDelay); #else sema_init(&ocb->sema_rx, 0); sema_init(&ocb->sema_tx, 0); sema_init(&ocb->sema_tx_abort, 0); sema_init(&ocb->sema_close, 0); #endif ocb->minor = net_no; /* TODO rename minor -> net_no */ ocb->node = nodes[ocb->minor]; *newocb = ocb; CAN_DBG((ESDCAN_ZONE_FU, "%s:ocb_create: leave, ocb=%p\n", OSIF_FUNCTION, ocb)); return result; } /* now do the main action... */ static INT32 ocb_create2( CAN_OCB *ocb, INT32 net_no, CAN_INIT_ARG *can_init ) { INT32 result = OSIF_SUCCESS; UINT32 queue_size_rx, queue_size_tx; UINT32 cmd; CAN_DBG((ESDCAN_ZONE_FU, "%s:ocb_create: enter\n", OSIF_FUNCTION)); /* check if node is available */ if ( (net_no >= (MAX_CARDS * NODES_PER_CARD)) || (NULL == nodes[net_no]) ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: node %d not available\n", OSIF_FUNCTION, net_no)); return OSIF_NET_NOT_FOUND; } #if defined (BOARD_USB) if (USB_OK != ((USB_MODULE*)((CAN_CARD*)nodes[net_no]->crd)->p_mod)->usb_status) { CAN_DBG((ESDCAN_ZONE_FU, "%s: node %d not available (usb not ready)\n", OSIF_FUNCTION,net_no)); return OSIF_NET_NOT_FOUND; } #endif queue_size_rx = can_init->queue_size_rx; queue_size_tx = can_init->queue_size_tx; /* patch queue sizes to at least 1 / check on -1 for CANopen */ if ( (queue_size_tx == 0) || (queue_size_tx == ~0x0) ) { queue_size_tx = 1; } if ( (queue_size_rx == 0) || (queue_size_rx == ~0x0) ) { queue_size_rx = 1; } /* range check for queue sizes */ if ( (queue_size_tx > CANIO_MAX_TX_QUEUESIZE) || (queue_size_rx > CANIO_MAX_RX_QUEUESIZE) ) { return OSIF_INVALID_PARAMETER; } ocb->mode = can_init->mode; /* TODO: use open_count !!!! */ if (can_init->mode & FEATURE_LOM) { /* If LOM is set this way, it can never be reset except by unloading the driver */ if (ocb->node->features & FEATURE_LOM) { ocb->node->mode |= FEATURE_LOM; } else { CAN_DBG((ESDCAN_ZONE, "%s: LOM not support by this node\n", OSIF_FUNCTION)); OSIF_FREE(ocb); return OSIF_INVALID_PARAMETER; } } /* Calculate command for ID-filter */ cmd = 0; if (!(ocb->mode & CANIO_MODE_OBJECT)) { cmd |= (ocb->mode & CANIO_MODE_NO_RTR) ? 0 : FILTER_RTR; cmd |= (ocb->mode & CANIO_MODE_NO_DATA) ? 0 : FILTER_DATA; #ifdef BOARD_CAN_FD if(ocb->mode & CANIO_MODE_FD) { cmd |= (ocb->mode & CANIO_MODE_NO_DATA) ? 0 : FILTER_DATA_FD; } #endif } if (ocb->node->features & FEATURE_FULL_CAN) { cmd &= ~FILTER_RTR; } /* * BL: RTR needs to be enabled on full CAN-controller, when the * handle is opened with the NO_DATA-flag (compatibility with candev-driver) */ if ( (ocb->node->features & FEATURE_FULL_CAN) && (ocb->mode & CANIO_MODE_NO_DATA) && !(ocb->mode & CANIO_MODE_AUTO_ANSWER) ) { cmd |= FILTER_RTR; } ocb->filter_cmd = cmd; ocb->filter20b.amr = 0xFFFFFFFF; /* rx buffer */ CAN_DBG((ESDCAN_ZONE, "%s: requesting rx buffer\n", OSIF_FUNCTION)); result = OSIF_MALLOC((UINT32)(sizeof(*ocb->rx.cmbuf) * queue_size_rx), &ocb->rx.cmbuf); if (result != OSIF_SUCCESS) { OSIF_FREE(ocb); return result; } CAN_DBG((ESDCAN_ZONE, "%s: calling nuc_open@%p\n", OSIF_FUNCTION, nuc_open)); OSIF_MUTEX_LOCK(&ocb->node->lock); result = nuc_open(ocb, ocb->node, &esdcan_callbacks, ocb->mode, queue_size_tx, queue_size_rx); OSIF_MUTEX_UNLOCK(&ocb->node->lock); if (result != OSIF_SUCCESS) { OSIF_FREE(ocb->rx.cmbuf); OSIF_FREE(ocb); return result; } CAN_DBG((ESDCAN_ZONE_FU, "%s:ocb_create: leave, ocb=%p\n", OSIF_FUNCTION, ocb)); return result; } INT32 ocb_destroy( CAN_OCB *ocb ) { INT32 result; CAN_DBG((ESDCAN_ZONE_FU, "%s:ocb_destroy: enter\n", OSIF_FUNCTION)); ocb->close_state |= CLOSE_STATE_HANDLE_CLOSED; #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION /* * We need to wait for esdcan_close_done to be called by nucleus. * Additionally while closing the ocb, the nucleus might have aborted * a RX and/or a TX job. Since we have no control, when these jobs * will exit the driver, we mark this ocb as CLOSING, until the jobs * have left the driver. * Freeing of ocb ressources is done in final close(). */ if (ocb->rx.state) { ocb->rx.state |= RX_STATE_CLOSING; } if (ocb->tx.state) { ocb->tx.state |= TX_STATE_CLOSING; } CAN_DBG((ESDCAN_ZONE, "%s: calling nuc_close\n", OSIF_FUNCTION)); result = nuc_close(ocb); CAN_DBG((ESDCAN_ZONE, "%s: nuc_close returned %d\n", OSIF_FUNCTION, result)); CAN_DBG((ESDCAN_ZONE, "%s: waiting on wqCloseDelay...\n", OSIF_FUNCTION)); OSIF_MUTEX_UNLOCK(&ocb->node->lock); #if 1 wait_event(ocb->wqCloseDelay, (ocb->close_state & CLOSE_STATE_CLOSE_DONE) && (!(ocb->tx.state & TX_STATE_CLOSING)) && (!(ocb->rx.state & RX_STATE_CLOSING))); #else /* use this code to debug "hanging" close conditions */ for(;;) { if (wait_event_timeout(ocb->wqCloseDelay, (ocb->close_state & CLOSE_STATE_CLOSE_DONE) && (!(ocb->tx.state & TX_STATE_CLOSING)) && (!(ocb->rx.state & RX_STATE_CLOSING)),1000)==0) { UINT32 txcnt; static UINT32 errcnt; nuc_tx_messages(ocb,&txcnt); OSIF_PRINT(("%s: wait_event_timeout!!! close_state=0x%x rx.state=0x%x tx.state=0x%x txcnt=%u\n", OSIF_FUNCTION, (unsigned int)ocb->close_state, (unsigned int)ocb->rx.state, (unsigned int)ocb->tx.state, (unsigned int)txcnt )); errcnt++; if ((errcnt>=10)&&(txcnt==0)) { errcnt=0; OSIF_PRINT(("%s: dirty: exiting wait_event_timeout loop!!!\n",OSIF_FUNCTION)); break; } } else { break; } } #endif OSIF_MUTEX_LOCK(&ocb->node->lock); CAN_DBG((ESDCAN_ZONE, "%s: close conditions fulfilled, close continues\n", OSIF_FUNCTION)); #else CAN_DBG((ESDCAN_ZONE, "%s: calling nuc_close\n", OSIF_FUNCTION)); result = nuc_close(ocb); CAN_DBG((ESDCAN_ZONE, "%s: nuc_close returned %d\n", OSIF_FUNCTION,result)); /* waiting for aborts to finish */ CAN_DBG((ESDCAN_ZONE, "%s: waiting for sema_close...\n", OSIF_FUNCTION)); OSIF_MUTEX_UNLOCK(&ocb->node->lock); down(&ocb->sema_close); OSIF_MUTEX_LOCK(&ocb->node->lock); CAN_DBG((ESDCAN_ZONE, "%s: sema_close signaled\n", OSIF_FUNCTION)); /* While closing the ocb, nucleus might have aborted a RX job * since we have no control, when this reader will exit the driver, * we mark this OCB as ABORTING */ if ( ocb->rx.state ) { /* do not destroy when there is a reader */ ocb->rx.state |= RX_STATE_CLOSING; } #endif CAN_DBG((ESDCAN_ZONE_FU, "%s:ocb_destroy: leave\n", OSIF_FUNCTION)); return result; } #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION /* returns error codes negative and received messages positive */ int esdcan_read_common( CAN_OCB *ocb, void *buf, UINT32 cm_count, UINT32 objSize ) { INT32 result; INT32 ret; INT32 flagInterruptedBySignal = 0; INT32 flagOcbClosing = 0; CAN_DBG((ESDCAN_ZONE_FU, "%s: enter, ocb=%p, cm_count=%d\n", OSIF_FUNCTION, ocb, cm_count)); CAN_ACTION_CHECK(ocb, result, return -result); /* return if any read or take is pending */ if (ocb->rx.state) { return -OSIF_PENDING_READ; } /* no other process is allowed to enter read from now on */ ocb->rx.state = RX_STATE_PENDING_READ; ocb->rx.result = 0; /* reset rx buffer pointer */ ocb->rx.user_buf = buf; CAN_DBG((ESDCAN_ZONE, "%s: rx_user_buf=%p\n", OSIF_FUNCTION, buf)); ocb->rx.cm_size = objSize; ocb->rx.cmbuf_in = ocb->rx.cmbuf; ocb->rx.cm_count = 0; /* trigger rx for cm_count cm */ ret = nuc_rx(ocb, ocb->rx.tout, &cm_count); if (ret != OSIF_SUCCESS) { ocb->rx.state = 0; return -ret; } /* wait for rx finished (interruptible) */ OSIF_MUTEX_UNLOCK(&ocb->node->lock); if ( wait_event_interruptible( ocb->wqRx, ( (ocb->rx.cm_count > 0) || /* Successfull end of canRead() */ (ocb->rx.state & RX_STATE_ABORT) || /* Set by esdcan_rx_done, e.g. on timeout */ (ocb->rx.state & RX_STATE_CLOSING) ) ) ) { /* Interrupted by signal, we might abort here */ OSIF_MUTEX_LOCK(&ocb->node->lock); if ( (ocb->rx.cm_count == 0) && (!(ocb->rx.state & RX_STATE_ABORT)) && (!(ocb->rx.state & RX_STATE_CLOSING)) ) { flagInterruptedBySignal = 1; ocb->rx.state |= RX_STATE_SIGNAL_INTERRUPT; /* Set only in this branch, nuc_rx_abort guarantees one more call of esdcan_rx_done */ nuc_rx_abort(ocb, OSIF_OPERATION_ABORTED); /* call of esdcan_rx_done() is guaranteed */ OSIF_MUTEX_UNLOCK(&ocb->node->lock); wait_event(ocb->wqRx, (!(ocb->rx.state & RX_STATE_SIGNAL_INTERRUPT))); } else { OSIF_MUTEX_UNLOCK(&ocb->node->lock); } } OSIF_MUTEX_LOCK(&ocb->node->lock); ret = ocb->rx.cm_count; ocb->rx.cm_count = 0; if (ocb->rx.state & RX_STATE_CLOSING) { flagOcbClosing = 1; } ocb->rx.state = 0; if (0 == ret) { /* return if rx failed */ CAN_DBG((ESDCAN_ZONE, "%s: rx failed (%d)\n", OSIF_FUNCTION, -(INT32)ocb->rx.result)); if (flagOcbClosing) { /* Delayed close needs to be woken */ /* The ocb is in process of closing and is (amongst others) waiting * for this job to leave the driver */ wake_up(&ocb->wqCloseDelay); CAN_DBG((ESDCAN_ZONE, "%s: RX delayed cleanup\n", OSIF_FUNCTION)); return -EINTR; } if (flagInterruptedBySignal) { /* Interrupted by signal, system will reenter this read */ return -ERESTARTSYS; } else { /* No messages, return rx.result stored by "interruptor", * in most cases RX timeout */ return -(INT32)ocb->rx.result; } } if (flagOcbClosing) { wake_up(&ocb->wqCloseDelay); } /* If we are here, canRead finishes successfully with RX messages */ { UINT8 *dest = buf; #ifdef BOARD_CAN_FD CAN_MSG_X *src; #else CAN_MSG_T *src; #endif INT32 i; src = ocb->rx.cmbuf; for (i = 0; i < ret; i++) { #ifdef BOARD_CAN_FD /* FD-enabled driver, src is CAN_MSG_X */ if ((ocb->rx.cm_size==sizeof(CAN_MSG))||(ocb->rx.cm_size==sizeof(CAN_MSG_X))) { if (copy_to_user(dest, src, ocb->rx.cm_size)) { return -OSIF_EFAULT; } } else { /* need to copy CAN_MSG_X data from cmbuf to user-supplied CAN_MSG_T buffer */ #if 1 /* make local copy, then call copy_to_user ONCE */ CAN_MSG_T tmp; memcpy(&tmp,src,sizeof(CAN_MSG)); tmp.timestamp.tick=src->timestamp.tick; if (copy_to_user(dest, &tmp, sizeof(CAN_MSG_T))) { return -OSIF_EFAULT; } #else if (copy_to_user(dest, src, sizeof(CAN_MSG))) { return -OSIF_EFAULT; } if (copy_to_user(&((CAN_MSG_T*)dest)->timestamp, &src->timestamp, sizeof(src->timestamp))) { return -OSIF_EFAULT; } #endif } #else /* non-FD driver, src is CAN_MSG_T */ if (ocb->rx.cm_size==sizeof(CAN_MSG_X)) { CAN_MSG_X tmp; memcpy(&tmp,src,sizeof(CAN_MSG)); memset(&tmp.buf.c[8],0,64-8); /* don't give away kernel stack data to user */ tmp.timestamp.tick=src->timestamp.tick; if (copy_to_user(dest, &tmp, sizeof(CAN_MSG_X))) { return -OSIF_EFAULT; } } else { if (copy_to_user(dest, src, ocb->rx.cm_size)) { return -OSIF_EFAULT; } } #endif CAN_DBG((ESDCAN_ZONE, "%s: ts=%lx.%lx\n", OSIF_FUNCTION, src->timestamp.h.HighPart, src->timestamp.h.LowPart)); src++; dest += ocb->rx.cm_size; } } CAN_DBG((ESDCAN_ZONE_FU, "%s:IOCTL_read: leave, copied %d CM(SG)s\n", OSIF_FUNCTION, ret)); return (int)ret; /* return count and not count*size */ } #else /* returns error codes negative and received messages positive */ int esdcan_read_common( CAN_OCB *ocb, void *buf, UINT32 cm_count, UINT32 objSize ) { INT32 result; INT32 ret; INT32 flagAbort = 0; CAN_DBG((ESDCAN_ZONE_FU, "%s: enter, ocb=%p, cm_count=%d\n", OSIF_FUNCTION, ocb, cm_count)); CAN_ACTION_CHECK(ocb, result, return -result); /* return if any read or take is pending */ if (ocb->rx.state) { return -OSIF_PENDING_READ; } /* no other process is allowed to enter read from now on */ ocb->rx.state = RX_STATE_PENDING_READ; ocb->rx.result = 0; /* reset rx buffer pointer */ ocb->rx.user_buf = buf; CAN_DBG((ESDCAN_ZONE, "%s: rx_user_buf=%p\n", OSIF_FUNCTION, buf)); ocb->rx.cm_size = objSize; ocb->rx.cmbuf_in = ocb->rx.cmbuf; ocb->rx.cm_count = 0; sema_init(&ocb->sema_rx, 0); /* trigger rx for cm_count cm */ ret = nuc_rx(ocb, ocb->rx.tout, &cm_count); if (ret != OSIF_SUCCESS) { ocb->rx.state = 0; return -ret; } /* wait for rx finished (interruptible) */ OSIF_MUTEX_UNLOCK(&ocb->node->lock); ret = down_interruptible(&ocb->sema_rx); OSIF_MUTEX_LOCK(&ocb->node->lock); if (ret != OSIF_SUCCESS) { if (ocb->rx.state & RX_STATE_CLOSING) { /* The ocb got closed already, freeing of OCB ressources is done in final close() */ CAN_DBG((ESDCAN_ZONE, "%s: RX delayed cleanup\n", OSIF_FUNCTION)); return -EINTR; /* system error code, never reaches user, thus no OSIF_ */ } else if (ocb->rx.cm_count == 0) { /* Interrupted by signal, we'll abort here */ ocb->rx.state |= RX_STATE_ABORTING; flagAbort = 1; nuc_rx_abort(ocb, OSIF_OPERATION_ABORTED); /* call of esdcan_rx_done() is guaranteed */ OSIF_MUTEX_UNLOCK(&ocb->node->lock); down(&ocb->sema_rx); OSIF_MUTEX_LOCK(&ocb->node->lock); } } /* return when rx failed */ ret = ocb->rx.cm_count; if (ret == 0) { CAN_DBG((ESDCAN_ZONE, "%s: rx failed (%d)\n", OSIF_FUNCTION, -(INT32)ocb->rx.result)); ocb->rx.state = 0; if (flagAbort) { return -ERESTARTSYS; } else { return -(INT32)ocb->rx.result; } } { /* read with(out) timestamps */ UINT8 *dest = buf; #ifdef BOARD_CAN_FD CAN_MSG_X *src; #else CAN_MSG_T *src; #endif INT32 i; src = ocb->rx.cmbuf; for (i = 0; i < ret; i++) { #ifdef BOARD_CAN_FD /* FD-enabled driver, src is CAN_MSG_X */ if ((ocb->rx.cm_size==sizeof(CAN_MSG))||(ocb->rx.cm_size==sizeof(CAN_MSG_X))) { if (copy_to_user(dest, src, ocb->rx.cm_size)) { return -OSIF_EFAULT; } } else { /* need to copy CAN_MSG_X data from cmbuf to user-supplied CAN_MSG_T buffer */ #if 1 /* make local copy, then call copy_to_user ONCE */ CAN_MSG_T tmp; memcpy(&tmp,src,sizeof(CAN_MSG)); tmp.timestamp.tick=src->timestamp.tick; if (copy_to_user(dest, &tmp, sizeof(CAN_MSG_T))) { return -OSIF_EFAULT; } #else if (copy_to_user(dest, src, sizeof(CAN_MSG))) { return -OSIF_EFAULT; } if (copy_to_user(&((CAN_MSG_T*)dest)->timestamp, &src->timestamp, sizeof(src->timestamp))) { return -OSIF_EFAULT; } #endif } #else /* non-FD driver, src is CAN_MSG_T */ if (ocb->rx.cm_size==sizeof(CAN_MSG_X)) { CAN_MSG_X tmp; memcpy(&tmp,src,sizeof(CAN_MSG)); memset(&tmp.buf.c[8],0,64-8); /* don't give away kernel stack data to user */ tmp.timestamp.tick=src->timestamp.tick; if (copy_to_user(dest, &tmp, sizeof(CAN_MSG_X))) { return -OSIF_EFAULT; } } else { if (copy_to_user(dest, src, ocb->rx.cm_size)) { return -OSIF_EFAULT; } } #endif CAN_DBG((ESDCAN_ZONE, "%s: ts=%lx.%lx\n", OSIF_FUNCTION, src->timestamp.h.HighPart, src->timestamp.h.LowPart)); src++; dest += ocb->rx.cm_size; } ocb->rx.cm_count = 0; } ocb->rx.state = 0; CAN_DBG((ESDCAN_ZONE_FU, "%s:IOCTL_read: leave, copied %d CM(SG)s\n", OSIF_FUNCTION, ocb->rx.cm_count )); return (int)ret; /* return count and not count*size */ } #endif #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION /* Returns error codes negative and transmitted messages positive */ int esdcan_write_common( CAN_OCB *ocb, void *buf, UINT32 cm_count, UINT32 objSize ) { INT32 result; INT32 old_job_tx_pending = 0; INT32 tx_len; INT32 flagInterruptedBySignal = 0; INT32 flagOcbClosing = 0; INT32 old_state; CAN_DBG((ESDCAN_ZONE_FU, "%s: enter cm_count=%d\n", OSIF_FUNCTION, cm_count)); if (0 == cm_count) { CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (OSIF_INVALID_PARAMETER)\n", OSIF_FUNCTION)); return -OSIF_INVALID_PARAMETER; /* BL TODO: change error-code??? */ } /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, return -result); if (ocb->tx.state & (TX_STATE_PENDING_WRITE | TX_STATE_ABORT)) { CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (PENDING_WRITE)\n", OSIF_FUNCTION)); return -OSIF_PENDING_WRITE; } else if (ocb->tx.state & TX_STATE_PENDING_SEND) { UINT32 dtx; if (nuc_deferred_tx_messages(ocb, &dtx) != OSIF_SUCCESS) { /* nuc_deferred_tx_messages should never fail, but anyway, you may try again */ return -ERESTARTSYS; /* system error code, never reaches user, thus no OSIF_ */ } if (dtx) { return -OSIF_PENDING_WRITE; } if (nuc_tx_messages(ocb, (UINT32*)&old_job_tx_pending) != OSIF_SUCCESS) { /* nuc_tx_messages should never fail, but anyway, you may try again */ return -ERESTARTSYS; /* system error code, never reaches user, thus no OSIF_ */ } } ocb->tx.user_buf = buf; ocb->tx.cm_size = objSize; /* need to save old state in case it is TX_STATE_PENDING_SEND, because if nuc_tx fails, we must not clear the old TX_STATE_PENDING_SEND but leave it as is. */ old_state = ocb->tx.state; /* need to set tx.state before nuc_tx call because nuc_tx might call esdcan_tx_done synchronously */ ocb->tx.state = TX_STATE_PENDING_WRITE; /* trigger tx job, copy_from_user is done in our context from nuc_tx() */ result = nuc_tx(ocb, ocb->tx.tout, &cm_count); if ( (result != OSIF_SUCCESS) && (cm_count == 0) ) { ocb->tx.state = old_state; /* restore old tx.state */ CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (nuc_tx, err = %d, cm_count = %d)\n", OSIF_FUNCTION, result, cm_count)); return -result; } /* wait until job is finished or error occured */ OSIF_MUTEX_UNLOCK(&ocb->node->lock); if (wait_event_interruptible(ocb->wqTx, ( (0 < (ocb->tx.cm_count - old_job_tx_pending)) || (ocb->tx.state & TX_STATE_ABORT) || (ocb->tx.state & TX_STATE_CLOSING) ) ) ) { OSIF_MUTEX_LOCK(&ocb->node->lock); if ( (0 == (ocb->tx.cm_count - old_job_tx_pending)) && (!(ocb->tx.state & TX_STATE_ABORT)) && (!(ocb->tx.state & TX_STATE_CLOSING)) ) { flagInterruptedBySignal = 1; ocb->tx.state |= TX_STATE_SIGNAL_INTERRUPT; nuc_tx_abort(ocb, OSIF_OPERATION_ABORTED, 0); OSIF_MUTEX_UNLOCK(&ocb->node->lock); wait_event(ocb->wqTx, (!(ocb->tx.state & TX_STATE_SIGNAL_INTERRUPT))); /* wait for esdcan_tx_done */ } else { OSIF_MUTEX_UNLOCK(&ocb->node->lock); } } OSIF_MUTEX_LOCK(&ocb->node->lock); tx_len = ocb->tx.cm_count - old_job_tx_pending; ocb->tx.cm_count = 0; if (ocb->tx.state & TX_STATE_CLOSING) { flagOcbClosing = 1; } ocb->tx.state = 0; /* check errors */ if (0 >= tx_len) { if (flagOcbClosing) { /* Delayed close needs to be woken */ /* The ocb is in process of closing and is (amongst others) waiting * for this job to leave the driver */ wake_up(&ocb->wqCloseDelay); CAN_DBG((ESDCAN_ZONE, "%s: TX delayed cleanup\n", OSIF_FUNCTION)); return -EINTR; } if (flagInterruptedBySignal) { CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (ERESTARTSYS, tx.cm_count = %d, old_job_tx_pending = %d)\n", OSIF_FUNCTION, (int)ocb->tx.cm_count, (int)old_job_tx_pending)); return -ERESTARTSYS; } else { CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (result: %ld, tx.cm_count = %d, old_job_tx_pending = %d)\n", OSIF_FUNCTION, -(ocb->tx.result), (int)ocb->tx.cm_count, (int)old_job_tx_pending)); return -(ocb->tx.result); } } if (flagOcbClosing) { wake_up(&ocb->wqCloseDelay); } CAN_DBG((ESDCAN_ZONE, "%s: copied %d bytes\n", OSIF_FUNCTION, ocb->tx.cm_count * sizeof(CAN_MSG))); CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (success, tx.cm_count = %d, tx_len = %d)\n", OSIF_FUNCTION, (int)ocb->tx.cm_count, (int)tx_len)); return (int)tx_len; /* return count and not count*size */ } #else /* Returns error codes negative and transmitted messages positive */ int esdcan_write_common( CAN_OCB *ocb, void *buf, UINT32 cm_count, UINT32 objSize ) { INT32 result, ret; INT32 old_job_tx_pending = 0; INT32 tx_len; INT32 flagAbort = 0; INT32 old_state; CAN_DBG((ESDCAN_ZONE_FU, "%s: enter cm_count=%d\n", OSIF_FUNCTION, cm_count)); if ( cm_count == 0 ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (OSIF_INVALID_PARAMETER)\n", OSIF_FUNCTION)); return -OSIF_INVALID_PARAMETER; /* AB TODO: change error-code??? */ } /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, return -result); if ( ocb->tx.state & (TX_STATE_PENDING_WRITE | TX_STATE_ABORTING) ) { CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (PENDING_WRITE)\n", OSIF_FUNCTION)); return -OSIF_PENDING_WRITE; } else if ( ocb->tx.state & TX_STATE_PENDING_SEND ) { UINT32 dtx; if (nuc_deferred_tx_messages(ocb, &dtx) != OSIF_SUCCESS) { /* nuc_deferred_tx_messages should never fail, but anyway, you may try again */ return -ERESTARTSYS; /* system error code, never reaches user, thus no OSIF_ */ } if (dtx) { return -OSIF_PENDING_WRITE; } if (nuc_tx_messages(ocb, (UINT32*)&old_job_tx_pending) != OSIF_SUCCESS) { /* nuc_tx_messages should never fail, but anyway, you may try again */ return -ERESTARTSYS; /* system error code, never reaches user, thus no OSIF_ */ } } ocb->tx.user_buf = buf; ocb->tx.cm_size = objSize; sema_init(&ocb->sema_tx, 0); /* need to save old state in case it is TX_STATE_PENDING_SEND, because if nuc_tx fails, we must not clear the old TX_STATE_PENDING_SEND but leave it as is. */ old_state = ocb->tx.state; /* need to set tx.state before nuc_tx call because nuc_tx might call esdcan_tx_done synchronously */ ocb->tx.state = TX_STATE_PENDING_WRITE; /* trigger tx job, copy_from_user is done in our context from nuc_tx() */ result = nuc_tx(ocb, ocb->tx.tout, &cm_count); if ( (result != OSIF_SUCCESS) && (cm_count == 0) ) { ocb->tx.state = old_state; /* restore old tx.state */ CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (nuc_tx, err = %d, cm_count = %d)\n", OSIF_FUNCTION, result, cm_count)); return -result; } /* wait until job is finished or error occured */ OSIF_MUTEX_UNLOCK(&ocb->node->lock); ret = down_interruptible(&ocb->sema_tx); OSIF_MUTEX_LOCK(&ocb->node->lock); /* Check, if the job was finished between wakeup and mutex lock */ tx_len = ocb->tx.cm_count; tx_len -= old_job_tx_pending; if ( (ret != OSIF_SUCCESS) && (tx_len <= 0) ) { ocb->tx.state |= TX_STATE_ABORTING; flagAbort = 1; nuc_tx_abort(ocb, OSIF_OPERATION_ABORTED, 0); OSIF_MUTEX_UNLOCK(&ocb->node->lock); down(&ocb->sema_tx_abort); /* wait for esdcan_tx_done */ OSIF_MUTEX_LOCK(&ocb->node->lock); } tx_len = ocb->tx.cm_count; tx_len -= old_job_tx_pending; ocb->tx.cm_count = 0; ocb->tx.state = 0; /* check errors */ if (tx_len <= 0) { if (flagAbort) { CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (ERESTARTSYS, tx.cm_count = %d, old_job_tx_pending = %d)\n", OSIF_FUNCTION, (int)ocb->tx.cm_count, (int)old_job_tx_pending)); return -ERESTARTSYS; } else { CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (result: %ld, tx.cm_count = %d, old_job_tx_pending = %d)\n", OSIF_FUNCTION, -(ocb->tx.result), (int)ocb->tx.cm_count, (int)old_job_tx_pending)); return -(ocb->tx.result); } } CAN_DBG((ESDCAN_ZONE, "%s: copied %d bytes\n", OSIF_FUNCTION, ocb->tx.cm_count * sizeof(CAN_MSG))); CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (success, tx.cm_count = %d, tx_len = %d)\n", OSIF_FUNCTION, (int)ocb->tx.cm_count, (int)tx_len)); return (int)tx_len; /* return count and not count*size */ } #endif #ifdef OSIF_OS_LINUX /* AB: This won't work on IRIX */ static int my_nuc_ioctl( CAN_OCB *ocb, UINT32 cmd, VOID *buf_in, UINT32 len_in, VOID *buf_out, UINT32 *len_out ) { INT32 status; IOCTL_WAIT_CONTEXT wait; #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) DEFINE_WAIT(waitQ); #endif CAN_DBG((ESDCAN_ZONE_FU, "%s: enter cmd=%08lx\n", OSIF_FUNCTION, cmd)); init_waitqueue_head(&wait.wq); status = nuc_ioctl(ocb, &wait, cmd, buf_in, len_in, buf_out, len_out); if (OSIF_EBUSY == status) { CAN_NODE *node = ocb->node; /* Must wait here */ OSIF_MUTEX_UNLOCK(&node->lock); #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) /* BL: sleep_on is deprecated since 2.6.10 */ prepare_to_wait(&wait.wq, &waitQ, TASK_UNINTERRUPTIBLE); schedule(); finish_wait(&wait.wq, &waitQ); #else sleep_on(&wait.wq); #endif OSIF_MUTEX_LOCK(&node->lock); status = wait.status; } CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (status=%d)\n", OSIF_FUNCTION, status)); return status; } #endif static int esdcan_ioctl_internal(struct inode *inode, struct file *file, unsigned int cmd, IOCTL_ARG *ioArg, CAN_OCB *ocb ) { INT32 result = OSIF_SUCCESS; CAN_NODE *node; UINT32 objSize; /* if private_data == 0 -> only allow CAN_CREATE */ if (!ocb) { CAN_DBG((ESDCAN_ZONE_FU, "%s: create path: cmd: 0x%X, IOCTL_ESDCAN_CREATE: 0x%0X\n", OSIF_FUNCTION, cmd, IOCTL_ESDCAN_CREATE)); if (cmd == IOCTL_ESDCAN_CREATE) { CAN_INIT_ARG can_init; #ifdef OSIF_OS_LINUX INT32 net_no = INODE2CANNODE(inode); #endif /* OSIF_OS_LINUX */ #ifdef OSIF_OS_IRIX INT32 net_no = file->node->net_no; ocb = file->ocb; /* set ocb (on irix ocb_create already called) */ #endif /* OSIF_OS_IRIX */ CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_CREATE, net_no=%d\n", OSIF_FUNCTION, net_no)); if (copy_from_user(&can_init, (VOID*)ioArg->buffer, sizeof(CAN_INIT_ARG))) { HOTPLUG_GLOBAL_UNLOCK; return OSIF_EFAULT; } #ifdef OSIF_OS_LINUX result = ocb_create(net_no, &ocb); if (result != OSIF_SUCCESS) { HOTPLUG_GLOBAL_UNLOCK; return (int)result; } #endif /* OSIF_OS_LINUX */ result = ocb_create2(ocb, net_no, &can_init); if (result != OSIF_SUCCESS) { HOTPLUG_GLOBAL_UNLOCK; return (int)result; } file->private_data = ocb; /* mark as ready */ #ifdef OSIF_OS_LINUX /* * BL: storing pointer to file-struct in ocb, in order * to be able to clear file->private_data on * USB-surprise-removal */ ocb->file = file; #endif /* OSIF_OS_LINUX */ nuc_check_links(ocb); HOTPLUG_GLOBAL_UNLOCK; return OSIF_SUCCESS; } else { CAN_DBG((ESDCAN_ZONE_FU, "%s: determine lib path: cmd: 0x%X, IOCTL_CAN_SET_QUEUESIZE: 0x%0X\n", OSIF_FUNCTION, cmd, IOCTL_CAN_SET_QUEUESIZE)); HOTPLUG_GLOBAL_UNLOCK; /* * Normally we've discovered, that an old "candev"-ntcan-library (major 1) * is trying to access the new driver. Unfortunately this case does happen * with "surprise"-removed USB-modules, too (although ntcan-library has a * correct version). Since there're no modules out there, which use the old * candev-driver and thus all USB-modules should be delivered with a new * library, we deliver another error-code depending on the IOCTL-command * in case of the USB-module. */ #if defined (BOARD_USB) if (cmd == IOCTL_CAN_SET_QUEUESIZE) { return OSIF_INVALID_DRIVER; } else { return OSIF_WRONG_DEVICE_STATE; } #else return OSIF_INVALID_DRIVER; #endif } } HOTPLUG_GLOBAL_UNLOCK; node = ocb->node; if (-1 == HOTPLUG_BOLT_USER_ENTRY(((CAN_CARD*)node->crd)->p_mod)) { CAN_DBG((ESDCAN_ZONE, "%s: bolt_user_entry returned -1\n", OSIF_FUNCTION)); return OSIF_EIO; } OSIF_MUTEX_LOCK(&node->lock); if (ocb->close_state & CLOSE_STATE_HANDLE_CLOSED) { ioArg->size = 0; OSIF_MUTEX_UNLOCK(&node->lock); return OSIF_INVALID_HANDLE; } switch(cmd) { case IOCTL_ESDCAN_DESTROY: case IOCTL_ESDCAN_DESTROY_DEPRECATED: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_DESTROY, minor=%d\n", OSIF_FUNCTION, ocb->minor)); #if defined (OSIF_OS_IRIX) file->private_data = 0; /* mark ocb as no more valid! */ #endif /* defined (OSIF_OS_IRIX) */ result = ocb_destroy(ocb); break; case IOCTL_ESDCAN_SEND_T: CAN_DBG((ESDCAN_ZONE, "%s:IOCTL_ESDCAN_SEND_T: cm_count=%d\n", OSIF_FUNCTION, ioArg->size)); objSize = sizeof(CAN_MSG_T); goto IOCTL_ESDCAN_SEND_00; case IOCTL_ESDCAN_SEND_X: CAN_DBG((ESDCAN_ZONE, "%s:IOCTL_ESDCAN_SEND_X: cm_count=%d\n", OSIF_FUNCTION, ioArg->size)); objSize = sizeof(CAN_MSG_X); goto IOCTL_ESDCAN_SEND_00; case IOCTL_ESDCAN_SEND: CAN_DBG((ESDCAN_ZONE, "%s:IOCTL_ESDCAN_SEND: cm_count=%d\n", OSIF_FUNCTION, ioArg->size)); objSize = sizeof(CAN_MSG); IOCTL_ESDCAN_SEND_00: { UINT32 cm_count; INT32 old_state; /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); /* entering not allowed when a write is pending */ if (ocb->tx.state & TX_STATE_PENDING_WRITE) { result = OSIF_PENDING_WRITE; break; } ocb->tx.user_buf = (VOID*)ioArg->buffer; ocb->tx.cm_size = objSize; cm_count = ioArg->size; CAN_DBG((ESDCAN_ZONE, "%s: cm_count=%d\n", OSIF_FUNCTION, cm_count)); /* need to save old state in case it is TX_STATE_PENDING_SEND, because if nuc_tx fails, we must not clear the old TX_STATE_PENDING_SEND but leave it as is. */ old_state = ocb->tx.state; /* need to set tx.state before nuc_tx call because nuc_tx might call esdcan_tx_done synchronously */ ocb->tx.state = TX_STATE_PENDING_SEND; /* trigger tx job, copy_from_user is done in our context from nuc_tx() */ result = nuc_tx(ocb, 0, &cm_count); /* check errors */ if ( (result != OSIF_SUCCESS) && (cm_count == 0) ) { ocb->tx.state = old_state; /* restore old tx.state */ break; } CAN_DBG((ESDCAN_ZONE, "%s: copied %d bytes\n", OSIF_FUNCTION, cm_count * sizeof(CAN_MSG))); result = OSIF_SUCCESS; ioArg->size = cm_count; /* return count and not count*size */ break; } case IOCTL_ESDCAN_TAKE_T: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_TAKE_T\n", OSIF_FUNCTION)); objSize = sizeof(CAN_MSG_T); goto IOCTL_ESDCAN_TAKE_00; case IOCTL_ESDCAN_TAKE_X: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_TAKE_X\n", OSIF_FUNCTION)); objSize = sizeof(CAN_MSG_X); goto IOCTL_ESDCAN_TAKE_00; case IOCTL_ESDCAN_TAKE: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_TAKE\n", OSIF_FUNCTION)); objSize = sizeof(CAN_MSG); IOCTL_ESDCAN_TAKE_00: { INT32 cm_count; /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); /* only one process may take/read at a time */ if (ocb->rx.state) { result = OSIF_PENDING_READ; break; } ocb->rx.state = RX_STATE_PENDING_TAKE; /* reset rx buffer pointer */ ocb->rx.user_buf = (VOID*)ioArg->buffer; ocb->rx.cm_size = objSize; ocb->rx.cmbuf_in = ocb->rx.cmbuf; ocb->rx.cm_count = 0; cm_count = (UINT32)(ioArg->size & (CANIO_MAX_RX_QUEUESIZE-1)); ioArg->size = 0; CAN_DBG((ESDCAN_ZONE, "%s: cm_count=%d\n", OSIF_FUNCTION, cm_count)); if (ocb->mode & CANIO_MODE_OBJECT) { UINT32 id; if (get_user(id, &((CAN_MSG*)ocb->rx.user_buf)->id)) { ocb->rx.state = 0; result = OSIF_EFAULT; break; } /* TODO: Michael: RX object mode also needs a ## !!! */ result = nuc_rx_obj(ocb, (UINT32*)&cm_count, id); if (result != OSIF_SUCCESS) { ocb->rx.state = 0; break; } ocb->rx.cm_count = cm_count; /* non object mode does this in rx_done */ } else { /* trigger rx for cm_count cm */ result = nuc_rx(ocb, 0, (UINT32*)&cm_count); if (result != OSIF_SUCCESS) { ocb->rx.state = 0; break; } } /* return if rx failed */ if (0 == ocb->rx.cm_count) { nuc_rx_abort(ocb, OSIF_SUCCESS); /* return OSIF_SUCCESS and _not_ OSIF_EIO! */ if (0 == ocb->rx.cm_count) { ocb->rx.state = 0; result = (int)ocb->rx.result; break; } } { /* read with(out) timestamps */ UINT8 *dest = (UINT8*)ioArg->buffer; #ifdef BOARD_CAN_FD CAN_MSG_X *src; #else CAN_MSG_T *src; #endif INT32 i; src = ocb->rx.cmbuf; for (i = 0; i < ocb->rx.cm_count; i++) { #ifdef BOARD_CAN_FD if ((ocb->rx.cm_size==sizeof(CAN_MSG))||(ocb->rx.cm_size==sizeof(CAN_MSG_X))) { if (copy_to_user(dest, src, ocb->rx.cm_size)) { return -OSIF_EFAULT; } } else { /* need to copy CAN_MSG_X data from cmbuf to user-supplied CAN_MSG_T buffer */ if (copy_to_user(dest, src, sizeof(CAN_MSG))) { return -OSIF_EFAULT; } if (copy_to_user(&((CAN_MSG_T*)dest)->timestamp, &src->timestamp, sizeof(src->timestamp))) { return -OSIF_EFAULT; } } #else if (copy_to_user(dest, src, ocb->rx.cm_size)) { result = OSIF_EFAULT; break; } #endif src++; dest += ocb->rx.cm_size; } } ocb->rx.state = 0; CAN_DBG((ESDCAN_ZONE, "%s: leave, copied %d CM(SG)s\n", OSIF_FUNCTION, ocb->rx.cm_count)); ioArg->size = ocb->rx.cm_count; /* return count and not count*size */ ocb->rx.cm_count = 0; /* important to clear, for next read call */ break; } case IOCTL_ESDCAN_WRITE_T: CAN_DBG((ESDCAN_ZONE, "%s:IOCTL_ESDCAN_WRITE_T: cm_count=%d\n", OSIF_FUNCTION, ioArg->size)); objSize = sizeof(CAN_MSG_T); goto IOCTL_ESDCAN_WRITE_00; case IOCTL_ESDCAN_WRITE_X: CAN_DBG((ESDCAN_ZONE, "%s:IOCTL_ESDCAN_WRITE_X: cm_count=%d\n", OSIF_FUNCTION, ioArg->size)); objSize = sizeof(CAN_MSG_X); goto IOCTL_ESDCAN_WRITE_00; case IOCTL_ESDCAN_WRITE: CAN_DBG((ESDCAN_ZONE, "%s:IOCTL_ESDCAN_WRITE: cm_count=%d\n", OSIF_FUNCTION, ioArg->size)); objSize = sizeof(CAN_MSG); IOCTL_ESDCAN_WRITE_00: result = esdcan_write_common(ocb, (VOID*)ioArg->buffer, ioArg->size, objSize); if (0 > result) { result = -result; } else { ioArg->size = result; result = OSIF_SUCCESS; } break; case IOCTL_ESDCAN_READ_T: CAN_DBG((ESDCAN_ZONE, "%s:IOCTL_ESDCAN_READ_T: cm_count=%d\n", OSIF_FUNCTION, ioArg->size)); objSize = sizeof(CAN_MSG_T); goto IOCTL_ESDCAN_READ_00; case IOCTL_ESDCAN_READ_X: CAN_DBG((ESDCAN_ZONE, "%s:IOCTL_ESDCAN_READ_X: cm_count=%d\n", OSIF_FUNCTION, ioArg->size)); objSize = sizeof(CAN_MSG_X); goto IOCTL_ESDCAN_READ_00; case IOCTL_ESDCAN_READ: CAN_DBG((ESDCAN_ZONE, "%s:IOCTL_ESDCAN_READ: cm_count=%d\n", OSIF_FUNCTION, ioArg->size)); objSize = sizeof(CAN_MSG); IOCTL_ESDCAN_READ_00: result = esdcan_read_common(ocb, (VOID*)ioArg->buffer, ioArg->size, objSize); if (0 > result) { result = -result; } else { ioArg->size = result; result = OSIF_SUCCESS; } break; case IOCTL_ESDCAN_PURGE_TX_FIFO: case IOCTL_ESDCAN_PURGE_TX_FIFO_DEPRECATED: case IOCTL_ESDCAN_TX_ABORT: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_TX_ABORT\n", OSIF_FUNCTION)); result = nuc_tx_abort(ocb, OSIF_OPERATION_ABORTED, 0); break; case IOCTL_ESDCAN_FLUSH_RX_FIFO: case IOCTL_ESDCAN_FLUSH_RX_FIFO_DEPRECATED: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_PURGE_RX_FIFO\n", OSIF_FUNCTION)); result = nuc_rx_purge(ocb); break; case IOCTL_ESDCAN_RX_ABORT: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_RX_ABORT\n", OSIF_FUNCTION)); result = nuc_rx_abort(ocb, OSIF_OPERATION_ABORTED); break; case IOCTL_ESDCAN_RX_OBJ: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_RX_OBJ: TODO !!!!\n", OSIF_FUNCTION)); /* TODO */ result = OSIF_NOT_IMPLEMENTED; break; case IOCTL_ESDCAN_TX_OBJ_CREATE: cmd = NUC_TX_OBJ_CREATE; goto IOCTL_ESDCAN_TX_OBJ; case IOCTL_ESDCAN_TX_OBJ_UPDATE: cmd = NUC_TX_OBJ_UPDATE; goto IOCTL_ESDCAN_TX_OBJ; case IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON: cmd = NUC_TX_OBJ_AUTOANSWER_ON; goto IOCTL_ESDCAN_TX_OBJ; case IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF: cmd = NUC_TX_OBJ_AUTOANSWER_OFF; goto IOCTL_ESDCAN_TX_OBJ; case IOCTL_ESDCAN_TX_OBJ_DESTROY: cmd = NUC_TX_OBJ_DESTROY; goto IOCTL_ESDCAN_TX_OBJ; case IOCTL_ESDCAN_TX_OBJ_SCHEDULE: cmd = NUC_TX_OBJ_SCHEDULE; goto IOCTL_ESDCAN_TX_OBJ; case IOCTL_ESDCAN_TX_OBJ_SCHEDULE_START: cmd = NUC_TX_OBJ_SCHEDULE_START; goto IOCTL_ESDCAN_TX_OBJ; case IOCTL_ESDCAN_TX_OBJ_SCHEDULE_STOP: cmd = NUC_TX_OBJ_SCHEDULE_STOP; IOCTL_ESDCAN_TX_OBJ: { UINT32 cm_count; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_TX_OBJ_xxx\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); ocb->tx.user_buf = (VOID*)ioArg->buffer; ocb->tx.cm_size = sizeof(CAN_MSG); cm_count = 1; CAN_DBG((ESDCAN_ZONE, "%s: cm_count=%d\n", OSIF_FUNCTION, cm_count)); result = nuc_tx_obj(ocb, cmd, &cm_count); break; } case IOCTL_ESDCAN_ID_RANGE_ADD: { CAN_ID_RANGE_ARG id_range; UINT32 count; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_ID_RANGE_ADD\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if ( copy_from_user(&id_range, (VOID*)ioArg->buffer, sizeof(CAN_ID_RANGE_ARG)) ) { result = OSIF_EFAULT; break; } count = id_range.id_stop - id_range.id_start + 1; result = id_filter(ocb, node, FILTER_ON | ocb->filter_cmd, id_range.id_start, &count); if (result != OSIF_SUCCESS) { id_filter(ocb, node, FILTER_OFF | ocb->filter_cmd, id_range.id_start, &count); } break; } case IOCTL_ESDCAN_ID_RANGE_DEL: { CAN_ID_RANGE_ARG id_range; UINT32 count; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_ID_RANGE_DEL\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (copy_from_user(&id_range, (VOID*)ioArg->buffer, sizeof(CAN_ID_RANGE_ARG))) { result = OSIF_EFAULT; break; } count = id_range.id_stop - id_range.id_start + 1; result = id_filter(ocb, node, FILTER_OFF | ocb->filter_cmd, id_range.id_start, &count); break; } case IOCTL_ESDCAN_ID_REGION_ADD: { CAN_ID_REGION_ARG id_region; CAN_ACTION_CHECK(ocb, result, break); if (copy_from_user(&id_region, (VOID*)ioArg->buffer, sizeof(CAN_ID_REGION_ARG))) { result = OSIF_EFAULT; break; } CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_ID_REGION_ADD\n", OSIF_FUNCTION)); result = nuc_id_filter(ocb, (FILTER_ON | ocb->filter_cmd), id_region.id1st, &id_region.cnt); if (id_region.cnt) { result = OSIF_SUCCESS; } if (copy_to_user((VOID*)ioArg->buffer, &id_region, sizeof(CAN_ID_REGION_ARG))) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_ID_REGION_DEL: { CAN_ID_REGION_ARG id_region; CAN_ACTION_CHECK(ocb, result, break); if (copy_from_user(&id_region, (VOID*)ioArg->buffer, sizeof(CAN_ID_REGION_ARG))) { result = OSIF_EFAULT; break; } CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_ID_REGION_DEL\n", OSIF_FUNCTION)); result = nuc_id_filter(ocb, (FILTER_OFF | ocb->filter_cmd), id_region.id1st, &id_region.cnt); if (id_region.cnt) { result = OSIF_SUCCESS; } if (copy_to_user((VOID*)ioArg->buffer, &id_region, sizeof(CAN_ID_REGION_ARG))) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_SET_BAUD: cmd = ESDCAN_CTL_BAUDRATE_SET; goto IOCTL_32_W; case IOCTL_ESDCAN_GET_BAUD: cmd = ESDCAN_CTL_BAUDRATE_GET; goto IOCTL_32_R; case IOCTL_ESDCAN_SET_TIMEOUT: { CAN_TIMEOUT_ARG timeout; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_SET_TIMEOUT\n", OSIF_FUNCTION)); /* Do NOT block attempts to access cards with wrong firmware, because * we need canOpen() for the updater to work which calls this IOCTL * implicitely. */ if (copy_from_user(&timeout, (VOID*)ioArg->buffer, sizeof(CAN_TIMEOUT_ARG))) { result = OSIF_EFAULT; break; } if ( (timeout.rxtout > CANIO_MAX_RX_TIMEOUT) || (timeout.txtout > CANIO_MAX_TX_TIMEOUT) ) { result = OSIF_INVALID_PARAMETER; break; } ocb->rx.tout = timeout.rxtout; ocb->tx.tout = timeout.txtout; break; } case IOCTL_ESDCAN_GET_RX_MESSAGES: { UINT32 msgs = 0; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_RX_MESSAGES\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); CAN_DBG((ESDCAN_ZONE, "%s: calling nuc_rx_messages\n", OSIF_FUNCTION)); result = nuc_rx_messages( ocb, &msgs ); if (put_user(msgs, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; break; } CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_RX_MESSAGES (rx_msgs = %d)\n", OSIF_FUNCTION, msgs)); break; } case IOCTL_ESDCAN_GET_RX_TIMEOUT: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_RX_TIMEOUT\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (put_user(ocb->rx.tout, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; break; } CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_RX_TIMEOUT (rx.tout = %d)\n", OSIF_FUNCTION, ocb->rx.tout)); break; case IOCTL_ESDCAN_GET_TX_TIMEOUT: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_TX_TIMEOUT\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (put_user(ocb->tx.tout, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; break; } CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_TX_TIMEOUT (tx.tout = %d)\n", OSIF_FUNCTION, ocb->tx.tout)); break; case IOCTL_ESDCAN_GET_TIMESTAMP_FREQ: case IOCTL_ESDCAN_GET_TIMESTAMP: { OSIF_TS ts; INT32 outbuflen = sizeof(OSIF_TS); CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_TIMESTAMP_...\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); result = my_nuc_ioctl(ocb, (cmd == IOCTL_ESDCAN_GET_TIMESTAMP_FREQ) ? ESDCAN_CTL_TIMEST_FREQ_GET : ESDCAN_CTL_TIMESTAMP_GET, NULL, 0, &ts, &outbuflen); CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_TIMESTAMP_... result=%d, ts=0x%llX\n", OSIF_FUNCTION, result, ts.tick)); if (result != OSIF_SUCCESS) { break; } if (copy_to_user((VOID*)ioArg->buffer, &ts, sizeof(OSIF_TS))) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_DEBUG: { CAN_DEBUG_ARG can_debug; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_DEBUG\n", OSIF_FUNCTION)); if ( copy_from_user( &can_debug, (VOID*)ioArg->buffer, sizeof(can_debug) ) ) { result = OSIF_EFAULT; break; } switch (can_debug.cmd) { case CAN_DEBUG_VER: { CAN_CARD *crd = (CAN_CARD*)node->crd; can_debug.p.ver.drv_ver = MAKE_VERSION(LEVEL, REVI, BUILD); can_debug.p.ver.firm_ver = MAKE_VERSION(crd->version_firmware.level, crd->version_firmware.revision, crd->version_firmware.build); can_debug.p.ver.hard_ver = MAKE_VERSION(crd->version_hardware.level, crd->version_hardware.revision, crd->version_hardware.build); can_debug.p.ver.board_stat = crd->board_status; /* Will provide real FW/HW status from all supporting boards. */ OSIF_SNPRINTF(((CHAR8*)can_debug.p.ver.firm_info, sizeof(can_debug.p.ver.firm_info), "%s", crd->pCardIdent->all.name)); can_debug.p.ver.features = (UINT16)(ocb->node->features & FEATURE_MASK_DOCUMENTED); can_debug.p.ver.ctrl_type = node->ctrl_type; OSIF_MEMSET(can_debug.p.ver.reserved, 0, sizeof(can_debug.p.ver.reserved)); break; } default: { INT32 outbuflen = sizeof(can_debug); result = my_nuc_ioctl(ocb, ESDCAN_CTL_DEBUG, &can_debug, sizeof(can_debug), &can_debug, &outbuflen); } } if (copy_to_user((VOID*)ioArg->buffer, &can_debug, sizeof(can_debug))) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_GET_INFO: { CAN_INFO info; INT32 outbuflen = sizeof(info); CAN_CARD *crd = (CAN_CARD*)node->crd; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_INFO\n", OSIF_FUNCTION)); /* Do NOT block attempts to access cards with wrong firmware. The * information should always be readable. */ if ( copy_from_user( &info, (VOID*)ioArg->buffer, sizeof(info) ) ) { result = OSIF_EFAULT; break; } result = my_nuc_ioctl(ocb, ESDCAN_CTL_CAN_INFO, &info, sizeof(info), &info, &outbuflen); /* info.base_net = ; the driver doesn't know this! Keep previous data. */ info.ports = crd->num_nodes; info.boardstatus= crd->board_status; info.driver = MAKE_VERSION(LEVEL, REVI, BUILD); info.firmware = MAKE_VERSION(crd->version_firmware.level, crd->version_firmware.revision, crd->version_firmware.build); info.firmware2 = MAKE_VERSION(crd->version_firmware2.level, crd->version_firmware2.revision, crd->version_firmware2.build); info.hardware = MAKE_VERSION(crd->version_hardware.level, crd->version_hardware.revision, crd->version_hardware.build); /* The board layer should have set the serial number. */ info.serial = crd->serial; /* If the board layer didn't set the <serial_string> then use the * default decode algorithm for the <serial> number. */ if ('\0' == info.serial_string[0]) { if (0 != info.serial) { OSIF_SNPRINTF((info.serial_string, sizeof(info.serial_string), "%c%c%06ld", 'A' + ((info.serial >> 28) & 0x0F), 'A' + ((info.serial >> 24) & 0x0F), info.serial & 0x00FFFFFF)); } else { /* This means no valid serial number => "N/A" */ OSIF_SNPRINTF((info.serial_string, sizeof(info.serial_string), "N/A")); } } OSIF_SNPRINTF((info.boardid, sizeof(info.boardid), "%s", crd->pCardIdent->all.name)); if (copy_to_user((VOID*)ioArg->buffer, &info, sizeof(info))) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_SET_20B_HND_FILTER: { UINT32 amr; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_CAN_SET_20B_FILTER\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (get_user(amr, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; break; } result = nuc_id_filter_mask(ocb, ocb->filter20b.acr, amr, CANIO_IDS_REGION_20B); if (OSIF_SUCCESS == result) { ocb->filter20b.amr = amr; } break; } case IOCTL_ESDCAN_SET_HND_FILTER: { CAN_FILTER_MASK filterMask; UINT32 buflen = sizeof(filterMask); CAN_DBG((OSIF_ZONE_ESDCAN, "%s: IOCTL_CAN_SET_FILTER\n", OSIF_FUNCTION)); CAN_ACTION_CHECK(ocb, result, break); if (copy_from_user(&filterMask, (VOID*)ioArg->buffer, buflen)) { result = OSIF_EFAULT; break; } result = nuc_id_filter_mask( ocb, filterMask.acr, filterMask.amr, filterMask.idArea ); break; } case IOCTL_ESDCAN_SET_RX_TIMEOUT: case IOCTL_ESDCAN_SET_TX_TIMEOUT: { UINT32 tout; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_SET_RX/TX_TIMEOUT\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (get_user(tout, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; break; } if (IOCTL_ESDCAN_SET_TX_TIMEOUT == cmd) { ocb->tx.tout = tout; } else { ocb->rx.tout = tout; } break; } case IOCTL_ESDCAN_GET_SERIAL: { CAN_CARD *crd = (CAN_CARD*)node->crd; CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_SERIAL\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (put_user(crd->serial, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_GET_FEATURES: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_FEATURES\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (put_user(node->features, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; } break; case IOCTL_ESDCAN_UPDATE: /* candev legacy ioctl, not needed anymore, replaced by IOCTL_ESDCAN_TX_OBJ_UPDATE */ case IOCTL_ESDCAN_SET_MODE: /* candev legacy ioctl, not needed for esdcan */ case IOCTL_ESDCAN_GET_TICKS_FREQ: /* legacy ioctl, not needed anymore */ case IOCTL_ESDCAN_GET_TICKS: /* legacy ioctl, not needed anymore */ case IOCTL_ESDCAN_SET_ALT_RTR_ID: /* deprecated customer specific extension */ result = OSIF_NOT_IMPLEMENTED; /* ...and never will be */ break; case IOCTL_ESDCAN_SET_BUSLOAD_INTERVAL: cmd = ESDCAN_CTL_BUSLOAD_INTERVAL_SET; goto IOCTL_32_W; case IOCTL_ESDCAN_GET_BUSLOAD_INTERVAL: cmd = ESDCAN_CTL_BUSLOAD_INTERVAL_GET; goto IOCTL_32_R; case IOCTL_ESDCAN_GET_BUS_STATISTIC: { CAN_BUS_STAT stat; UINT32 outbuflen = sizeof(CAN_BUS_STAT); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); result = my_nuc_ioctl(ocb, ESDCAN_CTL_BUS_STATISTIC_GET, NULL, 0, &stat, &outbuflen); CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_GET_BUS_STATISTIC result=%d\n", OSIF_FUNCTION, result)); if (result != OSIF_SUCCESS) { break; } if (copy_to_user((VOID*)ioArg->buffer, &stat, sizeof(CAN_BUS_STAT) )) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_RESET_BUS_STATISTIC: cmd = ESDCAN_CTL_BUS_STATISTIC_RESET; goto IOCTL_CMD; case IOCTL_ESDCAN_GET_ERROR_COUNTER: cmd = ESDCAN_CTL_ERROR_COUNTER_GET; goto IOCTL_32_R; case IOCTL_ESDCAN_GET_BITRATE_DETAILS: { CAN_BITRATE btrInfo; UINT32 outbuflen = sizeof(btrInfo); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); result = my_nuc_ioctl(ocb, ESDCAN_CTL_BITRATE_DETAILS_GET, NULL, 0, &btrInfo, &outbuflen); CAN_DBG((ESDCAN_ZONE, "%s: ESDCAN_CTL_BITRATE_DETAILS_GET result=%d, errCnt=0x%08X\n", OSIF_FUNCTION, result)); if (result != OSIF_SUCCESS) { break; } if (copy_to_user((VOID*)ioArg->buffer, &btrInfo, sizeof(btrInfo))) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_SER_REG_READ: cmd = ESDCAN_CTL_SER_REG_READ; goto IOCTL_ESDCAN_SER_REG_COMMON; case IOCTL_ESDCAN_SER_REG_WRITE: cmd = ESDCAN_CTL_SER_REG_WRITE; IOCTL_ESDCAN_SER_REG_COMMON: { SERIAL_ARG uartTuple; UINT32 buflen = sizeof(uartTuple); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (copy_from_user(&uartTuple, (VOID*)ioArg->buffer, buflen)) { result = OSIF_EFAULT; break; } result = my_nuc_ioctl(ocb, cmd, &uartTuple, buflen, &uartTuple, &buflen); CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_SER_REG_COMMON cmd=%d result=%d\n", OSIF_FUNCTION, cmd, result)); if (result != OSIF_SUCCESS) { break; } if (copy_to_user((VOID*)ioArg->buffer, &uartTuple, buflen)) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_RESET_CAN_ERROR_CNT: cmd = ESDCAN_CTL_RESET_CAN_ERROR_CNT; goto IOCTL_CMD; case IOCTL_ESDCAN_EEI_CREATE: { UINT32 eeihandle; INT32 outbuflen = sizeof(UINT32); CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_ESDCAN_EEI_CREATE...\n", OSIF_FUNCTION)); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); result = my_nuc_ioctl(ocb, ESDCAN_CTL_EEI_CREATE, NULL, 0, &eeihandle, &outbuflen); if (result != OSIF_SUCCESS) { break; } if (copy_to_user((VOID*)ioArg->buffer, &eeihandle, sizeof(UINT32))) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_EEI_DESTROY: cmd = ESDCAN_CTL_EEI_DESTROY; goto IOCTL_32_W; case IOCTL_ESDCAN_EEI_STATUS: { EEI_STATUS eeistatus; INT32 outbuflen = sizeof(EEI_STATUS); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (copy_from_user(&eeistatus, (VOID*)ioArg->buffer, sizeof(EEI_STATUS))) { result = OSIF_EFAULT; break; } result = my_nuc_ioctl(ocb, ESDCAN_CTL_EEI_STATUS, &eeistatus, sizeof(EEI_STATUS), &eeistatus, &outbuflen); if (result != OSIF_SUCCESS) { break; } if (copy_to_user((VOID*)ioArg->buffer, &eeistatus, sizeof(EEI_STATUS))) { result = OSIF_EFAULT; } break; } case IOCTL_ESDCAN_EEI_CONFIGURE: { EEI_UNIT eeiunit; /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (copy_from_user(&eeiunit, (VOID*)ioArg->buffer, sizeof(EEI_UNIT))) { result = OSIF_EFAULT; break; } result = my_nuc_ioctl(ocb, ESDCAN_CTL_EEI_CONFIGURE, &eeiunit, sizeof(EEI_UNIT), NULL, NULL); break; } case IOCTL_ESDCAN_EEI_START: cmd = ESDCAN_CTL_EEI_START; goto IOCTL_32_W; case IOCTL_ESDCAN_EEI_STOP: cmd = ESDCAN_CTL_EEI_STOP; goto IOCTL_32_W; case IOCTL_ESDCAN_EEI_TRIGGER_NOW: cmd = ESDCAN_CTL_EEI_TRIGGER_NOW; goto IOCTL_32_W; case IOCTL_ESDCAN_SET_TX_TS_WIN: cmd = ESDCAN_CTL_TX_TS_WIN_SET; goto IOCTL_32_W; case IOCTL_ESDCAN_GET_TX_TS_WIN: cmd = ESDCAN_CTL_TX_TS_WIN_GET; goto IOCTL_32_R; case IOCTL_ESDCAN_SET_TX_TS_TIMEOUT: cmd = ESDCAN_CTL_TX_TS_TIMEOUT_SET; goto IOCTL_32_W; case IOCTL_ESDCAN_GET_TX_TS_TIMEOUT: cmd = ESDCAN_CTL_TX_TS_TIMEOUT_GET; goto IOCTL_32_R; IOCTL_CMD: { /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); result = my_nuc_ioctl(ocb, cmd, NULL, 0, NULL, NULL); CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_CMD ocb=0x%08X, node=0x%08X, cmd=%d result=%d\n", OSIF_FUNCTION, ocb, node, cmd, result)); break; } IOCTL_32_R: { UINT32 value; UINT32 buflen = sizeof(value); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); result = my_nuc_ioctl(ocb, cmd, NULL, 0, &value, &buflen); CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_32_R ocb=0x%08X, node=0x%08X, cmd=%d result=%d\n", OSIF_FUNCTION, ocb, node, cmd, result)); if ( (result != OSIF_SUCCESS) || (buflen != sizeof(value)) ) { break; } if (put_user(value, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; } break; } IOCTL_32_W: { UINT32 value; /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (get_user(value, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; break; } result = my_nuc_ioctl(ocb, cmd, &value, sizeof(value), NULL, NULL); CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_32_W ocb=0x%08X, node=0x%08X, cmd=%d result=%d\n", OSIF_FUNCTION, ocb, node, cmd, result)); break; } #if 0 /* currently not used */ IOCTL_32_RW: { UINT32 value; UINT32 buflen = sizeof(value); /* block attempts to access cards with wrong firmware */ CAN_ACTION_CHECK(ocb, result, break); if (get_user(value, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; break; } result = my_nuc_ioctl(ocb, cmd, &value, buflen, &value, &buflen); CAN_DBG((ESDCAN_ZONE, "%s: IOCTL_32_RW ocb=0x%08X, node=0x%08X, cmd=%d result=%d\n", OSIF_FUNCTION, ocb, node, cmd, result)); if ( (result != OSIF_SUCCESS) || (buflen != sizeof(value)) ) { break; } if (put_user(value, (UINT32*)ioArg->buffer)) { result = OSIF_EFAULT; } break; } #endif default: CAN_DBG((ESDCAN_ZONE, "%s: IOCTL(%08x) not supported\n", OSIF_FUNCTION, cmd)); result = OSIF_NOT_SUPPORTED; } /* switch */ nuc_check_links(ocb); OSIF_MUTEX_UNLOCK(&node->lock); HOTPLUG_BOLT_USER_EXIT(((CAN_CARD*)node->crd)->p_mod); return result; } #if PLATFORM_64BIT # if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,10) static int esdcan_ioctl_32(unsigned int fd, unsigned int cmd, unsigned long arg, struct file *file) { struct inode *inode; INT32 result = OSIF_SUCCESS; IOCTL_ARG ioArg; IOCTL_ARG_32 ioArg32; CAN_OCB *ocb; CAN_DBG((ESDCAN_ZONE_FU, "%s: enter\n", OSIF_FUNCTION)); /* Patch ioctl-cmd to ioctl-command in 64-Bit driver * This function is called for IOCTLs with parameters, only. */ cmd = ((cmd & (~0x00040000)) | 0x00080000); inode = file->f_dentry->d_inode; HOTPLUG_GLOBAL_LOCK; ocb = (CAN_OCB*)file->private_data; CAN_DBG((ESDCAN_ZONE, "%s: params: ioctl=%x, ocb=%p, arg=%p\n", OSIF_FUNCTION, cmd, ocb, arg)); if (NULL != (IOCTL_ARG_32*)arg) { if (copy_from_user(&ioArg32, (IOCTL_ARG_32*)arg, sizeof(ioArg32))) { HOTPLUG_GLOBAL_UNLOCK; CAN_DBG((ESDCAN_ZONE, "%s: leave (cfu failed)\n", OSIF_FUNCTION)); RETURN_TO_USER(OSIF_EFAULT); } ioArg.buffer = (void*)((unsigned long)ioArg32.buffer); ioArg.size = ioArg32.size; } result = esdcan_ioctl_internal(inode, file, cmd, &ioArg, ocb); if ( ( IOCTL_ESDCAN_CREATE != cmd ) && ( NULL != ocb ) ) { if (result == OSIF_SUCCESS) { ioArg32.buffer = (uint32_t)((unsigned long)ioArg.buffer); ioArg32.size = ioArg.size; if (NULL != (IOCTL_ARG_32*)arg) { /* result of esdcan_ioctl_internal is aliased! */ if (copy_to_user((IOCTL_ARG_32*)arg, &ioArg32, sizeof(ioArg32))) { result = OSIF_EFAULT; } } } } CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (result=%d)\n", OSIF_FUNCTION, result)); RETURN_TO_USER(result); } # else static long esdcan_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct inode *inode; INT32 result = OSIF_SUCCESS; IOCTL_ARG ioArg; IOCTL_ARG_32 ioArg32; CAN_OCB *ocb; CAN_DBG((ESDCAN_ZONE_FU, "%s: enter (cmd=0x%X, arg=%p)\n", OSIF_FUNCTION, cmd, arg)); inode = file_inode(file); HOTPLUG_GLOBAL_LOCK; /* Patch ioctl-cmd to ioctl-command in 64-Bit driver */ if (IOCTL_CAN_SET_QUEUESIZE != cmd) { /* Don't change IOCTL from old library (needed for differentiation) */ if ( (cmd & IOCSIZE_MASK) == 0x00040000 ) { /* Don't change IOCTL's without parameter */ cmd = ((cmd & (~0x00040000)) | 0x00080000); } } ocb = (CAN_OCB*)file->private_data; CAN_DBG((ESDCAN_ZONE, "%s: params (ioctl=%x, ocb=%p, arg=%p)\n", OSIF_FUNCTION, cmd, ocb, arg)); if (NULL != (IOCTL_ARG_32*)arg) { if (copy_from_user(&ioArg32, (IOCTL_ARG_32*)arg, sizeof(ioArg32))) { HOTPLUG_GLOBAL_UNLOCK; CAN_DBG((ESDCAN_ZONE, "%s: leave (cfu failed)\n", OSIF_FUNCTION)); RETURN_TO_USER(OSIF_EFAULT); } ioArg.buffer = (void*)((unsigned long)ioArg32.buffer); ioArg.size = ioArg32.size; } result = esdcan_ioctl_internal(inode, file, cmd, &ioArg, ocb); if ( ( IOCTL_ESDCAN_CREATE != cmd ) && ( NULL != ocb ) ) { if (result == OSIF_SUCCESS) { ioArg32.buffer = (uint32_t)((unsigned long)ioArg.buffer); ioArg32.size = ioArg.size; if (NULL != (IOCTL_ARG_32*)arg) { /* result of esdcan_ioctl_internal is aliased! */ if (copy_to_user((IOCTL_ARG_32*)arg, &ioArg32, sizeof(ioArg32))) { result = OSIF_EFAULT; } } } } CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (result=%d)\n", OSIF_FUNCTION, result)); RETURN_TO_USER(result); } # endif #endif #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,10) static long esdcan_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct inode *inode; long result = OSIF_SUCCESS; CAN_DBG((ESDCAN_ZONE_FU, "%s: enter (cmd=0x%X, arg=%p)\n", OSIF_FUNCTION, cmd, arg)); inode = file_inode(file); result = esdcan_ioctl(inode, file, cmd, arg); CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (result=%d)\n", OSIF_FUNCTION, result)); return result; /* returns to user, but result is already inverted in esdcan_ioctl() */ } #endif /*! \fn static int esdcan_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg); * \brief ioctl entry for driver * \param inode pointer to inode structure * \param file pointer to file structure (contains private_data pointer) * \param cmd ioctl command (see esdcanio.h for IOCTL_x defines) * \param ioctl argument (this is usually a user space pointer) * \return Linux or CAN error code */ ESDCAN_IOCTL_PROTO { IOCTL_ARG ioArg; INT32 result = OSIF_SUCCESS; CAN_OCB *ocb; #ifdef OSIF_OS_IRIX vertex_hdl_t vhdl_dev, vhdl; void *drvarg; CAN_HANDLE_INFO *file; /* call this variable "file" because of linux */ #endif /* OSIF_OS_IRIX */ CAN_DBG((ESDCAN_ZONE_FU, "%s: enter\n", OSIF_FUNCTION)); HOTPLUG_GLOBAL_LOCK; #ifdef OSIF_OS_IRIX /* Get the vertex handle and pointer to dev-structure */ vhdl_dev = dev_to_vhdl(devp); if (vhdl_dev == NULL) { CAN_PRINT((":CAN: dev_to_vhdl returns NULL")); HOTPLUG_GLOBAL_UNLOCK; RETURN_TO_USER(OSIF_EIO); } CAN_DBG((ESDCAN_ZONE, "%s:CAN: vhdl_dev=%x", OSIF_FUNCTION, vhdl_dev)); file = (CAN_HANDLE_INFO*)device_info_get(vhdl_dev); #endif /* OSIF_OS_IRIX */ ocb = (CAN_OCB*)file->private_data; CAN_DBG((ESDCAN_ZONE, "%s: enter (ioctl=%x, ocb=%p, arg=%p)\n", OSIF_FUNCTION, cmd, ocb, arg)); if (NULL != (IOCTL_ARG*)arg) { if (copy_from_user(&ioArg, (IOCTL_ARG*)arg, sizeof(ioArg))) { HOTPLUG_GLOBAL_UNLOCK; CAN_DBG((ESDCAN_ZONE, "%s: leave (cfu failed)\n", OSIF_FUNCTION)); RETURN_TO_USER(OSIF_EFAULT); } } result = esdcan_ioctl_internal(inode, file, cmd, &ioArg, ocb); if ( ( IOCTL_ESDCAN_CREATE != cmd ) && ( NULL != ocb ) ) { if (result == OSIF_SUCCESS) { #ifdef OSIF_OS_IRIX *rvalp = 0; #endif if (NULL != (IOCTL_ARG*)arg) { /* result of esdcan_ioctl_internal is aliased! */ if (copy_to_user((IOCTL_ARG*)arg, &ioArg, sizeof(ioArg))) { result = OSIF_EFAULT; } } } } CAN_DBG((ESDCAN_ZONE_FU, "%s: leave (result=%d)\n", OSIF_FUNCTION, result)); RETURN_TO_USER(result); } static unsigned int esdcan_poll(struct file *pFile, struct poll_table_struct *pPollTable) { CAN_OCB *ocb; CAN_NODE *node; unsigned int mask = 0; UINT32 num; ocb = (CAN_OCB*)pFile->private_data; node = ocb->node; OSIF_MUTEX_LOCK(&node->lock); if (ocb->close_state & CLOSE_STATE_HANDLE_CLOSED) { OSIF_MUTEX_UNLOCK(&node->lock); return OSIF_INVALID_HANDLE; } poll_wait(pFile, &node->wqRxNotify, pPollTable); nuc_rx_messages(ocb, &num); if (num) { mask |= POLLIN | POLLRDNORM; } OSIF_MUTEX_UNLOCK(&node->lock); return mask; }
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/osif_spi.h
/* -*- linux-c -*- * FILE NAME osif_spi.h * * BRIEF MODULE DESCRIPTION * OSIF specials only needed with SPI CAN controllers * * Also included in GPL'ed files * escan-of-spi-connector.c and esd-omap2-mcspi.c * * history: * $Log$ * */ /************************************************************************************************** * * Copyright (c) 1996 - 2013 by esd electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd.eu * Germany sales@esd.eu * *************************************************************************/ #ifndef __OSIF_SPI_H__ #define __OSIF_SPI_H__ #include "sys_osiftypes.h" #define MAX_DIRECTSPI_DEV 4 #define DIRECTSPIDEV_VERSION 1 #define MAX_SPI_CANDDEV 16 #define SPI_CANDEV_VERSION 1 #define SPI_CAN_CTRL_TYPE_UNKOWN 0 #define SPI_CAN_CTRL_TYPE_MCP2515 1 #define SPI_MASTER_CTRL_TYPE_UNKNOWN 0 #define SPI_MASTER_CTRL_TYPE_OMAP_2_4 1 #define OSIF_SPI_BUFFER 32 typedef struct { uint8_t io[OSIF_SPI_BUFFER]; /* Data buffer */ int nBytes; /* # of bytes (Tx/Rx) */ } OSIF_SPIMSG; struct spi_candev; struct directspidev { u32 directspi_dev_version; u32 master_id; u32 master_type; /* SPI_MASTER_CTRL_TYPE_xxx */ struct platform_device *master_dev; void __iomem *master_base; /* was mcspi->base */ unsigned long master_phys; // todo FJ use a sub-structure for func ptrs!? int (*init)(struct spi_candev *pscd, VOID *vp); int (*sync_xfer)(struct spi_candev *pscd, OSIF_SPIMSG *pMsg); u32 reserved[32]; }; struct spi_candev { u32 spi_candev_version; u32 spi_id; int spi_irq; int spi_gpio_irq; char compatible[64]; u32 spi_type; /* SPI_CAN_CTRL_TYPE_xxx */ u32 spi_cs; /* cs (0,1,2 ...) */ u32 spi_clock; u32 spi_flags; u32 spi_max_frequency; u32 spi_mode; u32 spi_word_len; struct directspidev *pdsd; void __iomem *spi_cs_base; /* was mcspi_cs->base */ unsigned long spi_cs_phys; u32 spi_chconf0; void *driverdata; /* typically *CAN_CARD */ // todo FJ use a sub-structure for func ptrs!? int (*spi_check_no_irq_pending)(struct spi_candev *pscd); /* check that there is no pending IRQ from CAN controller */ u32 reserved[32]; }; #endif /* __OSIF_SPI_H__ */ /*---------------------------------------------------------------------------*/ /* EOF */ /*---------------------------------------------------------------------------*/ /* Some customisation for (X)-emacs */ /* * Local variables: * mode: c * indent-tabs-mode: nil * c-indent-level: 4 * c-basic-offset: 4 * tab-width: 4 * End: */
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/canio.h
/* canio.h ** ** Copyright (c) 2001-2015 by electronic system design gmbh ** ** This software is copyrighted by and is the sole property of ** esd gmbh. All rights, title, ownership, or other interests ** in the software remain the property of esd gmbh. This ** software may only be used in accordance with the corresponding ** license agreement. Any unauthorized use, duplication, transmission, ** distribution, or disclosure of this software is expressly forbidden. ** ** This Copyright notice may not be removed or modified without prior ** written consent of esd gmbh. ** ** esd gmbh, reserves the right to modify this software without notice. ** ** electronic system design gmbh Tel. +49-511-37298-0 ** Vahrenwalder Str 205 Fax. +49-511-37298-68 ** 30165 Hannover http://www.esd.eu ** Germany support@esd.eu ** ** ** user-header for io-control for esd-can-driver linux ** */ #ifndef __CANIO_H__ #define __CANIO_H__ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include <linux/ioctl.h> /* Following define is used to en-/disable code on non-64-Bit platforms */ #define PLATFORM_64BIT defined(__ppc64__) || defined(__x86_64__) #ifdef __KERNEL__ # define CANIO_UINT8 u8 # define CANIO_INT8 s8 # define CANIO_UINT16 u16 # define CANIO_INT16 s16 # define CANIO_UINT32 u32 # define CANIO_INT32 s32 # define CANIO_UINT64 u64 # define CANIO_INT64 s64 #else # include <stdint.h> # define CANIO_UINT8 uint8_t # define CANIO_INT8 int8_t # define CANIO_UINT16 uint16_t # define CANIO_INT16 int16_t # define CANIO_UINT32 uint32_t # define CANIO_INT32 int32_t # define CANIO_UINT64 uint64_t # define CANIO_INT64 int64_t #endif /* CAN-id-regions */ #define CANIO_IDS_REGION_20A 0 #define CANIO_IDS_REGION_20B 1 #define CANIO_IDS_REGION_EV 2 /* FJ: 2013-04-11 * EtherCAN server still needs this ... */ typedef struct { int32_t id1st; int32_t idlst; } CAN_IDSET; #define CANIO_20B_BASE 0x20000000 /* CAN-id-values (11-Bit/20a) */ #define CANIO_IDS 0x800 /* range of 20a-IDs */ #define CANIO_ID_BASE 0x00000000 #define CANIO_ID_LAST (CANIO_ID_BASE+CANIO_IDS-1) /* CAN-id-values (29-Bit/20b) */ #define CANIO_IDS_20B 0x20000000 /* range of 20b-IDs */ #define CANIO_ID_20B_BASE 0x20000000 #define CANIO_ID_20B_LAST (CANIO_ID_20B_BASE+CANIO_IDS_20B-1) #define CANIO_ID_INVALID 0xFFFFFFFF /* CAN-event-id-values */ #define CANIO_EVS 0x100 /* range of events */ #define CANIO_EV_BASE 0x40000000 #define CANIO_EV_CAN_ERROR CANIO_EV_BASE #define CANIO_EV_BAUD_CHANGE (CANIO_EV_BASE + 0x01) #define CANIO_EV_CAN_ERROR_EXT (CANIO_EV_BASE + 0x02) #define CANIO_EV_BUSLOAD (CANIO_EV_BASE + 0x03) #define CANIO_EV_CAN_DEFERRED_TX (CANIO_EV_BASE + 0x30) #define CANIO_EV_ECHO(NR) (CANIO_EV_BASE + 0x40 + ((NR) & 0x1F)) #define CANIO_EV_ECHO_FIRST (CANIO_EV_BASE + 0x40) #define CANIO_EV_ECHO_LAST (CANIO_EV_BASE + 0x5F) #define CANIO_EV_DNET_EVPOLL (CANIO_EV_BASE + 0x7C) #define CANIO_EV_DNET_EVEXPL (CANIO_EV_BASE + 0x7D) #define CANIO_EV_DNET_EV (CANIO_EV_BASE + 0x7E) #define CANIO_EV_DNET_CALL (CANIO_EV_BASE + 0x7F) #define CANIO_EV_USER (CANIO_EV_BASE + 0x80) #define CANIO_EV_TEMP (CANIO_EV_USER + 0x01) /* D31 events */ #define CANIO_EV_WATCHDOG (CANIO_EV_USER + 0x05) /* D31 events */ #define CANIO_EV_STOP_RELAIS (CANIO_EV_USER + 0x08) #define CANIO_EV_TEMP_SENSOR (CANIO_EV_USER + 0x0A) /* D31 events */ #define CANIO_EV_ARINC_TIMER (CANIO_EV_USER + 0x20) /* Events used on CAN-xxx/400 */ #define CANIO_EV_ARINC_TIME_SET (CANIO_EV_USER + 0x21) /* Events used on CAN-xxx/400 */ #define CANIO_EV_ARINC_INTERVAL_SET (CANIO_EV_USER + 0x22) /* Events used on CAN-xxx/400 */ #define CANIO_EV_ARINC_INTERVAL_GET (CANIO_EV_USER + 0x23) /* Events used on CAN-xxx/400 */ #define CANIO_EV_ARINC_START_SET (CANIO_EV_USER + 0x24) /* Events used on CAN-xxx/400 */ #define CANIO_EV_ARINC_START_GET (CANIO_EV_USER + 0x25) /* Events used on CAN-xxx/400 */ #define CANIO_EV_ARINC_START (CANIO_EV_USER + 0x26) /* Events used on CAN-xxx/400 */ #define CANIO_EV_ARINC_STOP (CANIO_EV_USER + 0x27) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_STATUS (CANIO_EV_USER + 0x28) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_CONFIG (CANIO_EV_USER + 0x29) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_SCRATCH (CANIO_EV_USER + 0x2A) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_FRAME_LOW (CANIO_EV_USER + 0x2B) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_FRAME_HIGH (CANIO_EV_USER + 0x2C) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_FWINFO_1 (CANIO_EV_USER + 0x2D) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_FWINFO_2 (CANIO_EV_USER + 0x2E) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_FWINFO_3 (CANIO_EV_USER + 0x2F) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_INFO_1 (CANIO_EV_USER + 0x30) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_INFO_2 (CANIO_EV_USER + 0x31) /* Events used on CAN-xxx/400 */ #define CANIO_EV_IRIGB_1PPS (CANIO_EV_USER + 0x32) /* Events used on CAN-xxx/400 */ /* #define CANIO_EV_ECHO (CANIO_EV_USER + 0x3F)*//* only defined in <win32/canio.h> */ #define CANIO_EV_WATCHDOG_RESET (CANIO_EV_USER + 0x45) /* D31 events */ #define CANIO_EV_TEMP_RANGE (CANIO_EV_USER + 0x46) /* D31 events */ #define CANIO_EV_PXI_CLOCK_SOURCE (CANIO_EV_USER + 0x50) /* Events used on CAN-xxx/400 */ #define CANIO_EV_PXI_STARTRIGGER_CONF (CANIO_EV_USER + 0x51) /* Events used on CAN-xxx/400 */ #define CANIO_EV_LAST (CANIO_EV_BASE + 0xFF) #define CANIO_DN_BASE 0x41000000 #define CANIO_DN_LAST 0x41FFFFFF /* * Flags in CMSG's <len> field */ #define CANIO_RTR 0x10 /* CAN message is RTR */ /* -> NTCAN_FD bit not set */ #define CANIO_ERR_PASSIVE 0x10 /* Sender is error passive */ /* -> NTCAN_FD bit set */ #define CANIO_NO_DATA 0x20 /* No updated data */ /* -> Object mode handle */ #define CANIO_INTERACTION 0x20 /* Interaction data */ /* -> FIFO mode handle */ #define CANIO_MARK_TX_ERROR 0x40 /* TX done with error in */ /* local-echo mode */ #define CANIO_FD 0x80 /* Frame is CAN-FD message */ #define CANIO_AUTO_ANSWER_VALID 0x20 /* Used only in 2.x driver !!! */ #define CANIO_DLC(len) ((len) & 0x0F) #define CANIO_DLC_AND_TYPE(len) ((len) & (0x0F | CANIO_RTR)) #define CANIO_IS_RTR(len) (((len) & (CANIO_FD | CANIO_RTR)) == CANIO_RTR) #define CANIO_IS_INTERACTION(len) ((len) & CANIO_INTERACTION) #define CANIO_IS_FD(len) ((len) & CANIO_FD) #define CANIO_IS_FD_ERR_PASSIVE(len) (((len) & (CANIO_FD | CANIO_ERR_PASSIVE)) == \ (CANIO_FD | CANIO_ERR_PASSIVE)) #define CANIO_LEN_TO_DATASIZE(len) __canLenToDataSize((len)) static __inline__ uint8_t __rotl8(uint8_t value, uint8_t shift) { return (value << shift) | (value >> (8 - shift)); } static __inline__ uint8_t __canLenToDataSize(uint8_t len) { static const uint8_t ucLenCan[] = { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 12, 8, 16, 8, 20, 8, 24, 8, 32, 8, 48, 8, 64, 0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 12, 0, 16, 0, 20, 0, 24, 0, 32, 0, 48, 0, 64 }; return(ucLenCan[__rotl8(len, 1) & 0x3F]); } #define CANIO_MAX_TX_QUEUESIZE 0x4000 #define CANIO_MAX_RX_QUEUESIZE 0x4000 #define CANIO_MAX_TX_TIMEOUT 0xFFFF #define CANIO_MAX_RX_TIMEOUT 0xFFFF /* * Bits for baudrate configuration (must be in sync with ntcan.h) * * The MSB of the baudrate constant is reserved to indicate the * meaning of the lower 24 bits. The two macros CANIO_BAUD_MODE() * and CANIO_BAUD_ARG() can be used to mask either the mode bits * or the argument. * * In addition there is a special constant to indicate an unconfigured * CAN controller. */ #define CANIO_BAUD_NOT_SET 0x7FFFFFFF #define CANIO_USER_BAUD 0x80000000 #define CANIO_LISTEN_ONLY_MODE 0x40000000 #define CANIO_USER_BAUD_NUM 0x20000000 #define CANIO_AUTOBAUD 0x00FFFFFE #define CANIO_AUTOBAUD_OLD 0x7FFFFFFE /* Old autobaud constant used */ /* in drivers prior V3.8.3 */ #define CANIO_NO_IMPLICIT_CLK_DIV 0x00000800 #define CANIO_BAUD_ARG(baud) ((baud) & 0x00FFFFFF) #define CANIO_BAUD_MODE(baud) ((baud) & 0xFF000000) /* Defines to decode CAN controller type, as delivered by canStatus(), etc. */ #define CANIO_CANCTL_SJA1000 0x00 #define CANIO_CANCTL_I82527 0x01 #define CANIO_CANCTL_FUJI 0x02 #define CANIO_CANCTL_LPC2292 0x03 #define CANIO_CANCTL_LPC17XX CANIO_CANCTL_LPC2292 #define CANIO_CANCTL_MSCAN 0x04 #define CANIO_CANCTL_ATSAM 0x05 #define CANIO_CANCTL_ESDACC 0x06 #define CANIO_CANCTL_STM32 0x07 #define CANIO_CANCTL_CC770 0x08 #define CANIO_CANCTL_SPEAR 0x09 #define CANIO_CANCTL_FLEXCAN 0x0A #define CANIO_CANCTL_SITARA 0x0B #define CANIO_CANCTL_MCP2515 0x0C #define CANIO_CANCTL_MCAN 0x0D /* Defines for CAN transceiver types */ #define CANIO_TRX_PCA82C251 0x00 /* NXP PCA82C251 */ #define CANIO_TRX_SN65HVD251 0x01 /* TI SN65HVD251 */ #define CANIO_TRX_SN65HVD265 0x02 /* TI SN65HVD265 */ /********************************************************************* * IO-controls * *********************************************************************/ /* * Define own private IOCTL for "candev"-driver */ #define IOCTL_CAN_SET_ID 1 #define IOCTL_CAN_SET_BAUD 2 #define IOCTL_CAN_SET_MODE 3 #define IOCTL_CAN_SET_TIMEOUT 4 #define IOCTL_CAN_SEND 5 #define IOCTL_CAN_TAKE 7 #define IOCTL_CAN_UPDATE 8 #define IOCTL_CAN_SET_QUEUESIZE 9 /* Also used to distinguish old and new driver */ #define IOCTL_CAN_TX_BUFFER 10 #define IOCTL_CAN_RX_BUFFER 11 #define IOCTL_CAN_DEBUG 12 #define IOCTL_CAN_GET_BAUD 17 #define IOCTL_CAN_SEND_DEVNET 18 #define IOCTL_CAN_FLUSH_RX_FIFO 19 #define IOCTL_CAN_GET_RX_MESSAGES 20 #define IOCTL_CAN_GET_RX_TIMEOUT 21 #define IOCTL_CAN_GET_TX_TIMEOUT 22 #define IOCTL_CAN_ABORT 23 #define IOCTL_CAN_GET_SERIAL 24 #define IOCTL_CAN_RAW 250 /* * Structures used as args for "candev"-ioctls */ /* * IOCTL_CAN_SET_BAUD: * arg = CAN_BAUDSET* * Values for baud-argument: * baud = int 0 = 1000.0 kBit/s * 1 = 666.6 kBit/s * 2 = 500.0 kBit/s * 3 = 333.3 kBit/s * 4 = 250.0 kBit/s * 5 = 166.0 kBit/s * 6 = 125.0 kBit/s * 7 = 100.0 kBit/s * 8 = 66.6 kBit/s * 9 = 50.0 kBit/s * 10 = 33.3 kBit/s * 11 = 20.0 kBit/s * 12 = 12.5 kBit/s * 13 = 10.0 kBit/s * 14 = 800.0 kBit/s * 15 = 1600.0 kBit/s * 16 = 83.3 kBit/s */ typedef struct /* structure for baud setting */ { int32_t net; /* net number */ int32_t baud; /* baudrate */ } CAN_BAUDSET, *PCAN_BAUDSET; typedef union { uint64_t tick; #if ( defined(__BYTE_ORDER) && (__BYTE_ORDER == __BIG_ENDIAN) ) || ( !defined(__BYTE_ORDER) && defined(__BIG_ENDIAN)) struct { uint32_t HighPart; uint32_t LowPart; } h; #endif /* __BIG_ENDIAN */ #if ( defined(__BYTE_ORDER) && (__BYTE_ORDER == __LITTLE_ENDIAN) ) || ( !defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN)) struct { uint32_t LowPart; uint32_t HighPart; } h; #endif /* __LITTLE_ENDIAN */ } CAN_TIMESTAMP, CAN_TIMESTAMP_FREQ; /* * arg = CAN_MSG* */ typedef struct { /* structure for action-routines */ int32_t id; /* id of can-frame or event-id */ uint8_t len; /* count of data-bytes (0...8) */ uint8_t msg_lost; /* message-lost-counter */ uint8_t reserved[2]; /* reserved for future */ union { /* data-buffer */ int8_t c[8]; int16_t s[4]; int32_t l[2]; int64_t ll[1]; } buf; } CAN_MSG, *PCAN_MSG; typedef struct { int32_t id; /* can-id */ uint8_t len; /* length of message: 0-8 */ uint8_t msg_lost; /* count of lost rx-messages */ uint8_t reserved[2]; /* reserved */ union { /* data-buffer */ int8_t c[8]; int16_t s[4]; int32_t l[2]; int64_t ll[1]; } buf; CAN_TIMESTAMP timestamp; /* time stamp of this message */ } CAN_MSG_T, *PCAN_MSG_T; typedef struct { int32_t id; /* can-id */ uint8_t len; /* length of message: 0-8 */ uint8_t msg_lost; /* count of lost rx-messages */ uint8_t reserved[2]; /* reserved */ union { /* data-buffer */ int8_t c[64]; int16_t s[32]; int32_t l[16]; int64_t ll[8]; } buf; CAN_TIMESTAMP timestamp; /* time stamp of this message */ } CAN_MSG_X, *PCAN_MSG_X; typedef struct _CAN_SCHED { int32_t id; int32_t flags; uint64_t time_start; uint64_t time_interval; uint32_t countStart; /* Start value for counting */ uint32_t countStop; /* Stop value for counting. After reaching this value, the counter is loaded with the countStart value. */ } CAN_SCHED; /* * IOCTL_CAN_SET_QUEUESIZE: * arg = CAN_QUEUE* */ typedef struct { int32_t tx_size; /* queuesize for tx-direction */ int32_t rx_size; /* queuesize for rx-direction */ } CAN_QUEUE, *PCAN_QUEUE; #pragma pack(1) typedef struct { /* structure for action-routines */ uint32_t id; /* 0x40/0x01/macid/len of dnet req */ uint16_t x1; /* para2 */ uint16_t x2; /* para2 */ union { /* data-buffer */ int8_t c[8]; int16_t s[4]; int32_t l[2]; int64_t ll[1]; } buf; } DNET_MSG, *PDNET_MSG; #pragma pack() /* * Define own private IOCTL for "esdcan"-driver * AB: To esd developers: * Don't forget to add the "_32-defines" (for 64-platforms) * and additions to esdcan_unregister_ioctl32() and * esdcan_register_ioctl32() in esdcan.c, when adding new IOCTLs. */ #define IOCTL_BASE 'C' #define IOCTL_ESDCAN_CREATE _IOW (IOCTL_BASE, 0, IOCTL_ARG*) #define IOCTL_ESDCAN_ID_RANGE_ADD _IOW (IOCTL_BASE, 1, IOCTL_ARG*) #define IOCTL_ESDCAN_ID_RANGE_DEL _IOW (IOCTL_BASE, 2, IOCTL_ARG*) #define IOCTL_ESDCAN_SET_BAUD _IOW (IOCTL_BASE, 3, IOCTL_ARG*) #define IOCTL_ESDCAN_SET_MODE _IOW (IOCTL_BASE, 4, IOCTL_ARG*) /* AB: DEPRECATED/REMOVED, not needed in esdcan (candev legacy)*/ #define IOCTL_ESDCAN_SET_TIMEOUT _IOW (IOCTL_BASE, 5, IOCTL_ARG*) #define IOCTL_ESDCAN_SEND _IOW (IOCTL_BASE, 6, IOCTL_ARG*) #define IOCTL_ESDCAN_TAKE _IOR (IOCTL_BASE, 7, IOCTL_ARG*) #define IOCTL_ESDCAN_DEBUG _IOWR (IOCTL_BASE, 9, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_BAUD _IOR (IOCTL_BASE, 10, IOCTL_ARG*) #define IOCTL_ESDCAN_DESTROY _IO (IOCTL_BASE, 11) #define IOCTL_ESDCAN_DESTROY_DEPRECATED _IOW (IOCTL_BASE, 11, unsigned long) /* Compatibility to libs <= 3.0.7 */ #define IOCTL_ESDCAN_TX_ABORT _IOW (IOCTL_BASE, 12, IOCTL_ARG*) #define IOCTL_ESDCAN_RX_ABORT _IOW (IOCTL_BASE, 13, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_CREATE _IOW (IOCTL_BASE, 16, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_UPDATE _IOW (IOCTL_BASE, 17, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF _IOW (IOCTL_BASE, 18, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_DESTROY _IOW (IOCTL_BASE, 19, IOCTL_ARG*) #define IOCTL_ESDCAN_RX_OBJ _IOW (IOCTL_BASE, 20, IOCTL_ARG*) #define IOCTL_ESDCAN_READ _IOWR (IOCTL_BASE, 21, IOCTL_ARG*) #define IOCTL_ESDCAN_WRITE _IOWR (IOCTL_BASE, 22, IOCTL_ARG*) #define IOCTL_ESDCAN_UPDATE _IOW (IOCTL_BASE, 23, IOCTL_ARG*) #define IOCTL_ESDCAN_FLUSH_RX_FIFO _IO (IOCTL_BASE, 24) #define IOCTL_ESDCAN_FLUSH_RX_FIFO_DEPRECATED _IOW (IOCTL_BASE, 24, unsigned long) /* Compatibility to libs <= 3.0.7 */ #define IOCTL_ESDCAN_GET_RX_MESSAGES _IOR (IOCTL_BASE, 25, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_RX_TIMEOUT _IOR (IOCTL_BASE, 26, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_TX_TIMEOUT _IOR (IOCTL_BASE, 27, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_TIMESTAMP_FREQ _IOR (IOCTL_BASE, 28, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_TIMESTAMP _IOR (IOCTL_BASE, 29, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_TICKS_FREQ _IOR (IOCTL_BASE, 30, IOCTL_ARG*) /* BL: DEPRECATED/REMOVED, use IOCTL_ESDCAN_GET_TIMESTAMP_FREQ */ #define IOCTL_ESDCAN_GET_TICKS _IOR (IOCTL_BASE, 31, IOCTL_ARG*) /* BL: DEPRECATED/REMOVED, use IOCTL_ESDCAN_GET_TIMESTAMP */ #define IOCTL_ESDCAN_SEND_T _IOW (IOCTL_BASE, 32, IOCTL_ARG*) #define IOCTL_ESDCAN_WRITE_T _IOW (IOCTL_BASE, 33, IOCTL_ARG*) #define IOCTL_ESDCAN_TAKE_T _IOWR (IOCTL_BASE, 34, IOCTL_ARG*) #define IOCTL_ESDCAN_READ_T _IOWR (IOCTL_BASE, 35, IOCTL_ARG*) #define IOCTL_ESDCAN_PURGE_TX_FIFO _IO (IOCTL_BASE, 36) #define IOCTL_ESDCAN_PURGE_TX_FIFO_DEPRECATED _IOW (IOCTL_BASE, 36, unsigned long) /* Compatibility to libs <= 3.0.7 */ #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON _IOW (IOCTL_BASE, 37, IOCTL_ARG*) #define IOCTL_ESDCAN_SET_RX_TIMEOUT _IOW (IOCTL_BASE, 38, IOCTL_ARG*) #define IOCTL_ESDCAN_SET_TX_TIMEOUT _IOW (IOCTL_BASE, 39, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_FEATURES _IOR (IOCTL_BASE, 40, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_SCHEDULE _IOW (IOCTL_BASE, 41, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_SCHEDULE_START _IO (IOCTL_BASE, 42) #define IOCTL_ESDCAN_TX_OBJ_SCHEDULE_STOP _IO (IOCTL_BASE, 43) #define IOCTL_ESDCAN_SET_20B_HND_FILTER _IOW (IOCTL_BASE, 44, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_SERIAL _IOR (IOCTL_BASE, 45, IOCTL_ARG*) #define IOCTL_ESDCAN_SET_ALT_RTR_ID _IO (IOCTL_BASE, 46) #define IOCTL_ESDCAN_SET_BUSLOAD_INTERVAL _IOW (IOCTL_BASE, 47, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_BUSLOAD_INTERVAL _IOR (IOCTL_BASE, 48, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_BITRATE_DETAILS _IOR (IOCTL_BASE, 49, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_BUS_STATISTIC _IOR (IOCTL_BASE, 50, IOCTL_ARG*) #define IOCTL_ESDCAN_RESET_BUS_STATISTIC _IO (IOCTL_BASE, 51) #define IOCTL_ESDCAN_GET_ERROR_COUNTER _IOR (IOCTL_BASE, 52, IOCTL_ARG*) #define IOCTL_ESDCAN_SER_REG_READ _IOWR (IOCTL_BASE, 53, IOCTL_ARG*) /* Special IOCTL, works only on specific hardware, NOT accessible via NTCAN */ #define IOCTL_ESDCAN_SER_REG_WRITE _IOWR (IOCTL_BASE, 54, IOCTL_ARG*) /* Special IOCTL, works only on specific hardware, NOT accessible via NTCAN */ #define IOCTL_ESDCAN_RESET_CAN_ERROR_CNT _IO (IOCTL_BASE, 55) #define IOCTL_ESDCAN_ID_REGION_ADD _IOWR (IOCTL_BASE, 56, IOCTL_ARG*) #define IOCTL_ESDCAN_ID_REGION_DEL _IOWR (IOCTL_BASE, 57, IOCTL_ARG*) #define IOCTL_ESDCAN_SET_TX_TS_WIN _IOW (IOCTL_BASE, 58, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_TX_TS_WIN _IOR (IOCTL_BASE, 59, IOCTL_ARG*) #define IOCTL_ESDCAN_SET_TX_TS_TIMEOUT _IOW (IOCTL_BASE, 60, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_TX_TS_TIMEOUT _IOR (IOCTL_BASE, 61, IOCTL_ARG*) #define IOCTL_ESDCAN_SET_HND_FILTER _IOW (IOCTL_BASE, 62, IOCTL_ARG*) #define IOCTL_ESDCAN_SEND_X _IOWR (IOCTL_BASE, 72, IOCTL_ARG*) #define IOCTL_ESDCAN_WRITE_X _IOWR (IOCTL_BASE, 73, IOCTL_ARG*) #define IOCTL_ESDCAN_TAKE_X _IOWR (IOCTL_BASE, 74, IOCTL_ARG*) #define IOCTL_ESDCAN_READ_X _IOWR (IOCTL_BASE, 75, IOCTL_ARG*) #define IOCTL_ESDCAN_SET_BAUD_X _IOW (IOCTL_BASE, 76, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_BAUD_X _IOWR (IOCTL_BASE, 77, IOCTL_ARG*) #define IOCTL_ESDCAN_EEI_CREATE _IOR (IOCTL_BASE, 81, IOCTL_ARG*) #define IOCTL_ESDCAN_EEI_DESTROY _IOW (IOCTL_BASE, 82, IOCTL_ARG*) #define IOCTL_ESDCAN_EEI_STATUS _IOWR (IOCTL_BASE, 83, IOCTL_ARG*) #define IOCTL_ESDCAN_EEI_CONFIGURE _IOW (IOCTL_BASE, 84, IOCTL_ARG*) #define IOCTL_ESDCAN_EEI_START _IOW (IOCTL_BASE, 85, IOCTL_ARG*) #define IOCTL_ESDCAN_EEI_STOP _IOW (IOCTL_BASE, 86, IOCTL_ARG*) #define IOCTL_ESDCAN_EEI_TRIGGER_NOW _IOW (IOCTL_BASE, 87, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_UPDATE_T _IOW (IOCTL_BASE,101, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF_T _IOW (IOCTL_BASE,102, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON_T _IOW (IOCTL_BASE,103, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_DESTROY_T _IOW (IOCTL_BASE,104, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_CREATE_X _IOW (IOCTL_BASE,105, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_UPDATE_X _IOW (IOCTL_BASE,106, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF_X _IOW (IOCTL_BASE,107, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON_X _IOW (IOCTL_BASE,108, IOCTL_ARG*) #define IOCTL_ESDCAN_TX_OBJ_DESTROY_X _IOW (IOCTL_BASE,109, IOCTL_ARG*) #define IOCTL_ESDCAN_GET_INFO _IOR (IOCTL_BASE,110, IOCTL_ARG*) #if PLATFORM_64BIT #define GEN_IOCTL32(arg) (((arg) & (~IOCSIZE_MASK)) | (0x4 << IOCSIZE_SHIFT)) /* patch pointer size difference in ioctl commands */ #define REGISTER_IOCTL_32(arg, ret) \ if ( ret |= register_ioctl32_conversion(arg##_32, esdcan_ioctl_32) ) { \ CAN_PRINT(("esd CAN driver: Problem with registering IOCTL32: 0x%x!\n", arg##_32)); \ } #define REGISTER_IOCTL_COMPAT(arg, ret) \ if ( ret |= register_ioctl32_conversion(arg, NULL) ) { \ CAN_PRINT(("esd CAN driver: Problem with registering IOCTL32: 0x%x!\n", arg)); \ } #define UNREGISTER_IOCTL_32(arg) \ if ( unregister_ioctl32_conversion(arg##_32) ) { \ CAN_PRINT(("esd CAN driver: Problem with unregistering IOCTL32: 0x%x!\n", arg##_32)); \ } #define UNREGISTER_IOCTL_COMPAT(arg) \ if ( unregister_ioctl32_conversion(arg) ) { \ CAN_PRINT(("esd CAN driver: Problem with unregistering IOCTL32: 0x%x!\n", arg)); \ } #define IOCTL_ESDCAN_CREATE_32 GEN_IOCTL32(IOCTL_ESDCAN_CREATE) #define IOCTL_ESDCAN_ID_RANGE_ADD_32 GEN_IOCTL32(IOCTL_ESDCAN_ID_RANGE_ADD) #define IOCTL_ESDCAN_ID_RANGE_DEL_32 GEN_IOCTL32(IOCTL_ESDCAN_ID_RANGE_DEL) #define IOCTL_ESDCAN_SET_BAUD_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_BAUD) #define IOCTL_ESDCAN_SET_MODE_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_MODE) #define IOCTL_ESDCAN_SET_TIMEOUT_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_TIMEOUT) #define IOCTL_ESDCAN_SEND_32 GEN_IOCTL32(IOCTL_ESDCAN_SEND) #define IOCTL_ESDCAN_TAKE_32 GEN_IOCTL32(IOCTL_ESDCAN_TAKE) #define IOCTL_ESDCAN_DEBUG_32 GEN_IOCTL32(IOCTL_ESDCAN_DEBUG) #define IOCTL_ESDCAN_GET_BAUD_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_BAUD) #define IOCTL_ESDCAN_DESTROY_32 /* same as IOCTL_ESDCAN_DESTROY */ #define IOCTL_ESDCAN_DESTROY_DEPRECATED_32 GEN_IOCTL32(IOCTL_ESDCAN_DESTROY_DEPRECATED) #define IOCTL_ESDCAN_TX_ABORT_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_ABORT) #define IOCTL_ESDCAN_RX_ABORT_32 GEN_IOCTL32(IOCTL_ESDCAN_RX_ABORT) #define IOCTL_ESDCAN_TX_OBJ_CREATE_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_CREATE) #define IOCTL_ESDCAN_TX_OBJ_UPDATE_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_UPDATE) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF) #define IOCTL_ESDCAN_TX_OBJ_DESTROY_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_DESTROY) #define IOCTL_ESDCAN_RX_OBJ_32 GEN_IOCTL32(IOCTL_ESDCAN_RX_OBJ) #define IOCTL_ESDCAN_READ_32 GEN_IOCTL32(IOCTL_ESDCAN_READ) #define IOCTL_ESDCAN_WRITE_32 GEN_IOCTL32(IOCTL_ESDCAN_WRITE) #define IOCTL_ESDCAN_UPDATE_32 GEN_IOCTL32(IOCTL_ESDCAN_UPDATE) #define IOCTL_ESDCAN_FLUSH_RX_FIFO_32 /* same as IOCTL_ESDCAN_PURGE_TX_FIFO */ #define IOCTL_ESDCAN_FLUSH_RX_FIFO_DEPRECATED_32 GEN_IOCTL32(IOCTL_ESDCAN_FLUSH_RX_FIFO_DEPRECATED) #define IOCTL_ESDCAN_GET_RX_MESSAGES_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_RX_MESSAGES) #define IOCTL_ESDCAN_GET_RX_TIMEOUT_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_RX_TIMEOUT) #define IOCTL_ESDCAN_GET_TX_TIMEOUT_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_TX_TIMEOUT) #define IOCTL_ESDCAN_GET_TIMESTAMP_FREQ_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_TIMESTAMP_FREQ) #define IOCTL_ESDCAN_GET_TIMESTAMP_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_TIMESTAMP) #define IOCTL_ESDCAN_GET_TICKS_FREQ_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_TICKS_FREQ) #define IOCTL_ESDCAN_GET_TICKS_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_TICKS) #define IOCTL_ESDCAN_SEND_T_32 GEN_IOCTL32(IOCTL_ESDCAN_SEND_T) #define IOCTL_ESDCAN_WRITE_T_32 GEN_IOCTL32(IOCTL_ESDCAN_WRITE_T) #define IOCTL_ESDCAN_TAKE_T_32 GEN_IOCTL32(IOCTL_ESDCAN_TAKE_T) #define IOCTL_ESDCAN_READ_T_32 GEN_IOCTL32(IOCTL_ESDCAN_READ_T) #define IOCTL_ESDCAN_PURGE_TX_FIFO_32 /* same as IOCTL_ESDCAN_PURGE_TX_FIFO */ #define IOCTL_ESDCAN_PURGE_TX_FIFO_DEPRECATED_32 GEN_IOCTL32(IOCTL_ESDCAN_PURGE_TX_FIFO_DEPRECATED) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON) #define IOCTL_ESDCAN_SET_RX_TIMEOUT_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_RX_TIMEOUT) #define IOCTL_ESDCAN_SET_TX_TIMEOUT_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_TX_TIMEOUT) #define IOCTL_ESDCAN_GET_FEATURES_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_FEATURES) #define IOCTL_ESDCAN_TX_OBJ_SCHEDULE_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_SCHEDULE) #define IOCTL_ESDCAN_TX_OBJ_SCHEDULE_START_32 /* same as IOCTL_ESDCAN_TX_OBJ_SCHEDULE_START */ #define IOCTL_ESDCAN_TX_OBJ_SCHEDULE_STOP_32 /* same as IOCTL_ESDCAN_TX_OBJ_SCHEDULE_STOP */ #define IOCTL_ESDCAN_SET_20B_HND_FILTER_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_20B_HND_FILTER) #define IOCTL_ESDCAN_GET_SERIAL_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_SERIAL) #define IOCTL_ESDCAN_SET_ALT_RTR_ID_32 /* same as IOCTL_ESDCAN_SET_ALT_RTR_ID */ #define IOCTL_ESDCAN_SET_BUSLOAD_INTERVAL_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_BUSLOAD_INTERVAL) #define IOCTL_ESDCAN_GET_BUSLOAD_INTERVAL_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_BUSLOAD_INTERVAL) #define IOCTL_ESDCAN_GET_BITRATE_DETAILS_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_BITRATE_DETAILS) #define IOCTL_ESDCAN_GET_BUS_STATISTIC_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_BUS_STATISTIC) #define IOCTL_ESDCAN_RESET_BUS_STATISTIC_32 /* same as IOCTL_ESDCAN_RESET_BUS_STATISTIC */ #define IOCTL_ESDCAN_GET_ERROR_COUNTER_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_ERROR_COUNTER) #define IOCTL_ESDCAN_SER_REG_READ_32 GEN_IOCTL32(IOCTL_ESDCAN_SER_REG_READ) #define IOCTL_ESDCAN_SER_REG_WRITE_32 GEN_IOCTL32(IOCTL_ESDCAN_SER_REG_WRITE) #define IOCTL_ESDCAN_RESET_CAN_ERROR_CNT_32 /* same as IOCTL_ESDCAN_RESET_CAN_ERROR_CNT */ #define IOCTL_ESDCAN_ID_REGION_ADD_32 GEN_IOCTL32(IOCTL_ESDCAN_ID_REGION_ADD) #define IOCTL_ESDCAN_ID_REGION_DEL_32 GEN_IOCTL32(IOCTL_ESDCAN_ID_REGION_DEL) #define IOCTL_ESDCAN_SET_TX_TS_WIN_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_TX_TS_WIN) #define IOCTL_ESDCAN_GET_TX_TS_WIN_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_TX_TS_WIN) #define IOCTL_ESDCAN_SET_TX_TS_TIMEOUT_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_TX_TS_TIMEOUT) #define IOCTL_ESDCAN_GET_TX_TS_TIMEOUT_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_TX_TS_TIMEOUT) #define IOCTL_ESDCAN_SET_HND_FILTER_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_HND_FILTER) #define IOCTL_ESDCAN_SEND_X_32 GEN_IOCTL32(IOCTL_ESDCAN_SEND_X) #define IOCTL_ESDCAN_WRITE_X_32 GEN_IOCTL32(IOCTL_ESDCAN_WRITE_X) #define IOCTL_ESDCAN_TAKE_X_32 GEN_IOCTL32(IOCTL_ESDCAN_TAKE_X) #define IOCTL_ESDCAN_READ_X_32 GEN_IOCTL32(IOCTL_ESDCAN_READ_X) #define IOCTL_ESDCAN_SET_BAUD_X_32 GEN_IOCTL32(IOCTL_ESDCAN_SET_BAUD_X) #define IOCTL_ESDCAN_GET_BAUD_X_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_BAUD_X) #define IOCTL_ESDCAN_EEI_CREATE_32 GEN_IOCTL32(IOCTL_ESDCAN_EEI_CREATE) #define IOCTL_ESDCAN_EEI_DESTROY_32 GEN_IOCTL32(IOCTL_ESDCAN_EEI_DESTROY) #define IOCTL_ESDCAN_EEI_STATUS_32 GEN_IOCTL32(IOCTL_ESDCAN_EEI_STATUS) #define IOCTL_ESDCAN_EEI_CONFIGURE_32 GEN_IOCTL32(IOCTL_ESDCAN_EEI_CONFIGURE) #define IOCTL_ESDCAN_EEI_START_32 GEN_IOCTL32(IOCTL_ESDCAN_EEI_START) #define IOCTL_ESDCAN_EEI_STOP_32 GEN_IOCTL32(IOCTL_ESDCAN_EEI_STOP) #define IOCTL_ESDCAN_EEI_TRIGGER_NOW_32 GEN_IOCTL32(IOCTL_ESDCAN_EEI_TRIGGER_NOW) #define IOCTL_ESDCAN_TX_OBJ_UPDATE_T_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_UPDATE_T) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF_T_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF_T) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON_T_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON_T) #define IOCTL_ESDCAN_TX_OBJ_DESTROY_T_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_DESTROY_T) #define IOCTL_ESDCAN_TX_OBJ_CREATE_X_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_CREATE_X) #define IOCTL_ESDCAN_TX_OBJ_UPDATE_X_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_UPDATE_X) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF_X_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_OFF_X) #define IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON_X_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_AUTOANSWER_ON_X) #define IOCTL_ESDCAN_TX_OBJ_DESTROY_X_32 GEN_IOCTL32(IOCTL_ESDCAN_TX_OBJ_DESTROY_X) #define IOCTL_ESDCAN_GET_INFO_32 GEN_IOCTL32(IOCTL_ESDCAN_GET_INFO) #endif /* * Structures used as args for "esdcan"-ioctls */ typedef struct { void *buffer; uint32_t size; } IOCTL_ARG; #if PLATFORM_64BIT typedef struct { uint32_t buffer; uint32_t size; } IOCTL_ARG_32; #endif /* argument for CAN_INIT ioctl */ typedef struct { uint32_t mode; uint32_t queue_size_tx; uint32_t queue_size_rx; } CAN_INIT_ARG; /* argument for CAN_ID_ADD/DEL ioctl */ typedef struct { int32_t id_start; int32_t id_stop; } CAN_ID_RANGE_ARG; typedef struct { int32_t id1st; int32_t cnt; } CAN_ID_REGION_ARG; /* argument for IOCTL_ESDCAN_SER_REG_READ/IOCTL_ESDCAN_SER_REG_WRITE ioctl */ typedef struct { uint32_t addr; uint32_t value; } SERIAL_ARG; /* * Structures used as args for "esdcan"- and "candev"-ioctls */ /* * IOCTL_CAN_SET_TIMEOUT, IOCTL_ESDCAN_SET_TIMEOUT: * arg = CAN_TIMEOUT* */ typedef struct { /* structure for timeout-setting */ uint32_t txtout; /* tx-timeout in msec */ uint32_t rxtout; /* rx-timeout in msec */ } CAN_TIMEOUT, *PCAN_TIMEOUT, CAN_TIMEOUT_ARG; /* * Flag for usSize member of flash_ex structure to indicate wheter * flash data is provided or the provided data is to be programmed. */ #define FLASH_DATA_PROVIDE 0x8000 /* * IOCTL_CAN_DEBUG, IOCTL_ESDCAN_DEBUG: * arg = CAN_DEBUG* */ typedef struct { /* structure for action-routines */ uint32_t password; /* password */ uint32_t cmd; /* command to execute */ union { struct { uint8_t access; /* byte/word/long access */ uint8_t bus; /* bus-nr */ uint8_t reserved[2]; uint32_t address; union { uint8_t c; uint16_t s; uint32_t l; } data; } dm_sm; struct { uint16_t drv_ver; uint16_t firm_ver; uint16_t hard_ver; uint16_t board_stat; int8_t firm_info[14]; uint16_t features; int8_t ctrl_type; int8_t reserved[5]; } ver; struct { uint32_t sector; uint16_t offset; uint16_t len; uint8_t data[14]; } flash; struct { uint16_t usSize; uint32_t ulOffset; uint8_t data[16]; } flash_ex; struct { int8_t mode; } trans_mode; struct { uint32_t uiVerbose; } regs; struct { uint32_t uiXor; /* to be used with esdACC boards */ } leds; struct { uint32_t uiVerbose; } bm_info; struct { uint32_t count; uint32_t delay; } usb_test; struct { uint32_t config; uint32_t output; uint32_t input; } usb_io_test; } p; } CAN_DEBUG, *PCAN_DEBUG, CAN_DEBUG_ARG; typedef struct { /* handle filter mask */ uint32_t acr; uint32_t amr; uint32_t idArea; } CAN_FILTER_MASK, *PCAN_FILTER_MASK; #define CAN_BITRATE_FLAG_SAM 0x00000001 typedef struct { uint32_t baud; /* value configured by user via canSetBaudrate() */ uint32_t valid; /* validity of all _following_ infos (-1 = invalid, CANIO_SUCCESS, CANIO_NOT_IMPLEMENTED) */ uint32_t rate; /* CAN bitrate in Bit/s */ uint32_t clock; /* frequency of CAN controller */ uint8_t ctrl_type; /* CANIO_CANCTL_XXX defines */ uint8_t tq_pre_sp; /* number of time quantas before samplepoint (TSEG1) */ uint8_t tq_post_sp; /* number of time quantas past samplepoint (TSEG2) */ uint8_t sjw; /* syncronization jump width in time quantas (SJW) */ uint32_t error; /* actual deviation of configured baudrate in %*100 */ uint32_t flags; /* baudrate flags (possibly ctrl. specific, e.g. SAM) */ uint32_t reserved1; /* for future use */ uint32_t reserved2; /* for future use */ uint32_t baud_req; /* requested bitrate, while request pending, else -1 (RESERVED IN NTCAN) */ } CAN_BITRATE; #define CAN_BAUDRATE_MODE_OFF 0 #define CAN_BAUDRATE_MODE_INDEX 1 #define CAN_BAUDRATE_MODE_BTR 2 #define CAN_BAUDRATE_MODE_NUM 3 #define CAN_BAUDRATE_MODE_OLDBTR 4 typedef struct { uint32_t mode; /* One of CAN_BAUDRATE_MODE_XXX constants */ union { uint32_t idx; /* esd bitrate table index */ struct { uint32_t brp; /* Bitrate pre-scaler */ uint32_t tseg1; /* TSEG1 register */ uint32_t tseg2; /* TSEG2 register */ uint32_t sjw; /* SJW register */ } btr; uint32_t rate; /* numerical bitrate */ uint32_t oldbtr; /* old bitrate timing register (btr) format */ } m; } CAN_BAUDRATE_CFG; #define CAN_BAUDRATE_CONTROL_STM 0x10000000 /* Self test mode */ #define CAN_BAUDRATE_CONTROL_LOM 0x40000000 /* Listen only mode */ typedef struct { uint32_t control; /* Combination of CAN_BAUDRATE_CONTROL_XXX constants */ CAN_BAUDRATE_CFG arbitration; /* Bitrate in arbitration phase */ CAN_BAUDRATE_CFG data; /* Bitrate in data phase */ uint32_t reserved; } CAN_BAUDRATE_X; typedef struct _CAN_FRAME_COUNT { uint32_t std_data; /* # of std CAN messages */ uint32_t std_rtr; /* # of std RTR requests */ uint32_t ext_data; /* # of ext CAN messages */ uint32_t ext_rtr; /* # of ext RTR requests */ } CAN_FRAME_COUNT; typedef struct _CAN_BUS_STAT { /* keep this struct in sync with NTCAN_BUS_STATISTIC */ uint64_t timestamp; /* Timestamp */ CAN_FRAME_COUNT rcv_count; /* # of received frames */ CAN_FRAME_COUNT xmit_count; /* # of transmitted frames */ uint32_t ctrl_ovr_count; /* # of controller overruns */ uint32_t fifo_ovr_count; /* # of FIFO overruns */ uint32_t err_frames_count; /* # of error frames */ uint32_t rcv_byte_count; /* # of received bytes */ uint32_t xmit_byte_count; /* # of transmitted bytes */ uint32_t abort_frames_count; /* # of aborted frames */ uint32_t rcv_count_fd; /* # of received FD frames */ uint32_t xmit_count_fd; /* # of transmitted FD frames */ uint64_t bit_count; /* # of received bits */ } CAN_BUS_STAT; typedef struct _CAN_CTRL_STATE { uint8_t rcv_err_counter; /* Receive error counter */ uint8_t xmit_err_counter; /* Transmit error counter */ uint8_t status; /* CAN controller status */ uint8_t type; /* CAN controller type */ } CAN_CTRL_STATE; typedef struct _EEI_UNIT { uint32_t handle; /* Handle for ErrorInjection Unit */ uint8_t mode_trigger; /* Trigger mode */ uint8_t mode_trigger_option; /* Options to trigger */ uint8_t mode_triggerarm_delay; /* Enable delayed arming of trigger unit*/ uint8_t mode_triggeraction_delay; /* Enable delayed TX out */ uint8_t mode_repeat; /* Enable repeat */ uint8_t mode_trigger_now; /* Trigger with next TX point */ uint8_t mode_ext_trigger_option; /* Switch between trigger and sending */ uint8_t mode_send_async; /* Send without timing synchronization */ uint8_t reserved1[4]; uint64_t timestamp_send; /* Timestamp for Trigger Timestamp */ uint32_t trigger_pattern[5]; /* Trigger for mode Pattern Match */ uint32_t trigger_mask[5]; /* Mask to trigger Pattern */ uint8_t trigger_ecc; /* ECC for Trigger Field Position */ uint8_t reserved2[3]; uint32_t external_trigger_mask; /* Enable Mask for external Trigger */ uint32_t reserved3[16]; uint32_t tx_pattern[5]; /* TX pattern */ uint32_t tx_pattern_len; /* Length of TX pattern */ uint32_t triggerarm_delay; /* Delay for mode triggerarm delay */ uint32_t triggeraction_delay; /* Delay for mode trigger delay */ uint32_t number_of_repeat; /* Number of repeats in mode repeat */ uint32_t reserved4; uint32_t tx_pattern_recessive[5]; /* Recessive TX pattern (USB400 Addon) */ uint32_t reserved5[9]; } EEI_UNIT; typedef struct _EEI_STATUS { uint32_t handle; /* Handle for ErrorInjection Unit */ uint8_t status; /* Status form Unit */ uint8_t unit_index; /* Error Injection Unit ID */ uint8_t units_total; /* Max Error Units in esdacc core */ uint8_t units_free; /* Free Error Units in esdacc core */ CAN_TIMESTAMP trigger_timestamp; /* Timestamp of trigger time */ uint16_t trigger_cnt; /* Count of trigger in Repeat mode */ uint16_t reserved0; uint32_t reserved1[27]; } EEI_STATUS; typedef struct _CAN_INFO { uint16_t hardware; /* Hardware version */ uint16_t firmware; /* Firmware / FPGA version (0 = N/A) */ uint16_t driver; /* Driver version */ uint16_t dll; /* NTCAN library version */ uint32_t features; /* Device/driver capability flags */ uint32_t serial; /* Serial # (0 = N/A) */ uint64_t timestamp_freq; /* Timestamp frequency (in Hz, 1 = N/A) */ uint32_t ctrl_clock; /* Frequency of CAN controller (in Hz) */ uint8_t ctrl_type; /* Controller type (CANIO_CANCTL_XXX) */ uint8_t base_net; /* Base net number */ uint8_t ports; /* Number of physical ports */ uint8_t trx_type; /* Transceiver type (CANIO_TRX_XXX) */ uint16_t boardstatus; /* Hardware status */ uint16_t firmware2; /* Second firmware version (0 = N/A) */ char boardid[32]; /* Board ID string */ char serial_string[16]; /* Serial # as string */ char drv_build_info[64]; /* Build info of driver */ char lib_build_info[64]; /* Build info of library */ uint8_t reserved2[44]; /* Reserved for future use */ } CAN_INFO; /* * Mode-flags (prefix CANIO_MODE_) are used by user/application * with IOCTL_ESDCAN_SET_MODE to set the driver into a certain mode. * !!! They have to be defined according to ntcan.h !!! */ #define CANIO_MODE_AUTO_ANSWER 0x00000002 /* mode-mask for auto-answer */ #define CANIO_MODE_NO_RTR 0x00000010 /* mode-mask for ignoring rtr */ #define CANIO_MODE_NO_DATA 0x00000020 /* mode-mask for ignoring data */ #define CANIO_MODE_SET_RTR_RCV 0x00000040 /* used to mark active RTR-reception (TODO: ???) */ #define CANIO_MODE_RTR_RCV 0x00000060 /* mode-mask for object mode (TODO: ???) */ #define CANIO_MODE_NO_INTERACTION 0x00000100 /* Ignore locally send interaction messages */ #define CANIO_MODE_MARK_INTERACTION 0x00000200 /* Mark interaction messages in len field */ #define CANIO_MODE_LOCAL_ECHO 0x00000400 /* Echo sent frames to same handle */ /* reserved NTCAN_MODE_SPS_CNTRL 0x00008000 Enable firmware SPS */ #define CANIO_MODE_LOM 0x00010000 /* mode-mask for listening only mode */ #define CANIO_MODE_DEFERRED_TX 0x00020000 /* mode-mask for "scheduled tx" */ #define CANIO_MODE_FD 0x00040000 /* Enable CAN-FD support */ #define CANIO_MODE_OBJECT 0x10000000 /* mode-mask for object mode */ #define CANIO_MODE_OVERLAPPED 0x20000000 /* reserved for windows, only */ #define CANIO_MODE_EVENTS 0x40000000 /* mode-mask for enabled events (TODO: ???) */ /* * Feature flags */ #define FEATURE_FULL_CAN (1<<0) /*! Marks Full-CAN-controller, used by nucleus for flat-mode,... */ #define FEATURE_CAN_20B (1<<1) /*! CAN 2.OB support */ #define FEATURE_DEVICE_NET (1<<2) #define FEATURE_CYCLIC_TX (1<<3) /*! On certain boards with special customer firmware only */ #define FEATURE_TIMESTAMPED_TX (1<<3) /*! SAME AS CYCLIC_TX, Timestamped TX support */ #define FEATURE_RX_OBJECT_MODE (1<<4) /*! DIFFERS FROM MODE FLAG: flat (receive object) mode */ /* AB: the following feature-flags aren't implemented in candev-driver */ #define FEATURE_TS (1<<5) /*! feature flag for hardware timestamping */ #define FEATURE_LOM (1<<6) /*! feature/mode flag for listening-only-mode */ #define FEATURE_SMART_DISCONNECT (1<<7) /*! feature/mode flag for stay-on-bus-after-last-close */ #define FEATURE_LOCAL_ECHO (1<<8) /*! feature/mode interaction with local echo */ #define FEATURE_SMART_ID_FILTER (1<<9) /*! Enabling/disabling ID ranges */ #define FEATURE_SCHEDULING (1<<10) /*! Scheduling feature */ #define FEATURE_DIAGNOSTIC (1<<11) /*! Bus diagnostic support */ #define FEATURE_ERROR_INJECTION (1<<12) /*! esdACC error injection support */ #define FEATURE_IRIGB (1<<13) /*! IRIG-B support */ #define FEATURE_PXI (1<<14) /*! Board supports backplane clock and startrigger for timestamp */ #define FEATURE_CAN_FD (1<<15) /*! CAN-FD support */ #define FEATURE_SELF_TEST (1<<16) /*! Self-test support */ #define FEATURE_MASK_DOCUMENTED (FEATURE_FULL_CAN | \ FEATURE_CAN_20B | \ FEATURE_DEVICE_NET | \ FEATURE_TIMESTAMPED_TX | \ FEATURE_RX_OBJECT_MODE | \ FEATURE_TS | \ FEATURE_SMART_DISCONNECT | \ FEATURE_LOM | \ FEATURE_LOCAL_ECHO | \ FEATURE_SMART_ID_FILTER | \ FEATURE_SCHEDULING | \ FEATURE_DIAGNOSTIC | \ FEATURE_ERROR_INJECTION | \ FEATURE_IRIGB | \ FEATURE_PXI) /* * Following defines are used in a nodes status cell for * - i20: wrong firmware / hardware * - bus status (ok, warn, err. passive, bus off) */ #define CANIO_STATUS_WRONG_FIRMWARE 0x00000001 /*! Wrong firmware version (disables CAN-functionality) */ #define CANIO_STATUS_WRONG_HARDWARE 0x00000002 /*! Wrong hardware version (disables CAN-functionality) */ #define CANIO_STATUS_OK 0x00000000 /*! can Status = OK */ #define CANIO_STATUS_WARN 0x40000000 /*! can status = controller warn */ #define CANIO_STATUS_ERRPASSIVE 0x80000000 /*! can status = error passive */ #define CANIO_STATUS_BUSOFF 0xC0000000 /*! can status = controller off bus */ #define CANIO_STATUS_MASK_BUSSTATE 0xC0000000 /*! use to retrieve bus states */ /* * Flags for scheduling mode */ #define CANIO_SCHED_FLAG_EN 0x00000000 /* ID is enabled */ #define CANIO_SCHED_FLAG_DIS 0x00000002 /* ID is disabled */ #define CANIO_SCHED_FLAG_REL 0x00000000 /* Start time is relative */ #define CANIO_SCHED_FLAG_ABS 0x00000001 /* Start time is absolute */ #define CANIO_SCHED_FLAG_INC8 0x00000100 /* 8 Bit incrementer */ #define CANIO_SCHED_FLAG_INC16 0x00000200 /* 16 Bit incrementer */ #define CANIO_SCHED_FLAG_INC32 0x00000300 /* 32 Bit incrementer */ #define CANIO_SCHED_FLAG_DEC8 0x00000400 /* 8 Bit decrementer */ #define CANIO_SCHED_FLAG_DEC16 0x00000500 /* 16 Bit decrementer */ #define CANIO_SCHED_FLAG_DEC32 0x00000600 /* 32 Bit decrementer */ #define CANIO_SCHED_FLAG_OFS0 0x00000000 /* Counter at offset 0 */ #define CANIO_SCHED_FLAG_OFS1 0x00001000 /* Counter at offset 1 */ #define CANIO_SCHED_FLAG_OFS2 0x00002000 /* Counter at offset 2 */ #define CANIO_SCHED_FLAG_OFS3 0x00003000 /* Counter at offset 3 */ #define CANIO_SCHED_FLAG_OFS4 0x00004000 /* Counter at offset 4 */ #define CANIO_SCHED_FLAG_OFS5 0x00005000 /* Counter at offset 5 */ #define CANIO_SCHED_FLAG_OFS6 0x00006000 /* Counter at offset 6 */ #define CANIO_SCHED_FLAG_OFS7 0x00007000 /* Counter at offset 7 */ /* flags for scheduling mode */ #define CANIO_SCHED_FLAG_EN 0x00000000 /* ID is enabled */ #define CANIO_SCHED_FLAG_DIS 0x00000002 /* ID is disabled */ #define CANIO_SCHED_FLAG_REL 0x00000000 /* Start time is relative */ #define CANIO_SCHED_FLAG_ABS 0x00000001 /* Start time is absolute */ #define CANIO_SCHED_FLAG_INC8 0x00000100 /* 8 Bit incrementer */ #define CANIO_SCHED_FLAG_INC16 0x00000200 /* 16 Bit incrementer */ #define CANIO_SCHED_FLAG_INC32 0x00000300 /* 32 Bit incrementer */ #define CANIO_SCHED_FLAG_DEC8 0x00000400 /* 8 Bit decrementer */ #define CANIO_SCHED_FLAG_DEC16 0x00000500 /* 16 Bit decrementer */ #define CANIO_SCHED_FLAG_DEC32 0x00000600 /* 32 Bit decrementer */ #define CANIO_SCHED_FLAG_OFS0 0x00000000 /* Counter at offset 0 */ #define CANIO_SCHED_FLAG_OFS1 0x00001000 /* Counter at offset 1 */ #define CANIO_SCHED_FLAG_OFS2 0x00002000 /* Counter at offset 2 */ #define CANIO_SCHED_FLAG_OFS3 0x00003000 /* Counter at offset 3 */ #define CANIO_SCHED_FLAG_OFS4 0x00004000 /* Counter at offset 4 */ #define CANIO_SCHED_FLAG_OFS5 0x00005000 /* Counter at offset 5 */ #define CANIO_SCHED_FLAG_OFS6 0x00006000 /* Counter at offset 6 */ #define CANIO_SCHED_FLAG_OFS7 0x00007000 /* Counter at offset 7 */ /* * Debug-command-values */ #define CAN_DEBUG_DM 0 /* dump memory */ #define CAN_DEBUG_SM 1 /* set memory */ #define CAN_DEBUG_IP 2 /* input port */ #define CAN_DEBUG_OP 3 /* output port */ #define CAN_DEBUG_VER 4 /* get version-information */ /*#define CAN_DEBUG_MAP 5 */ /* map memory-space to user-space */ #define CAN_DEBUG_REGISTER 10 /* display register */ /*#define CAN_DEBUG_RXFIFO 11 */ /* display interface rx fifo */ /* #define CAN_DEBUG_CONFIG 20 ?*//* Set/Get/Save config data */ #define CAN_DEBUG_FLASH_ENTER 128 /* enter flash-mode */ #define CAN_DEBUG_FLASH_ERASE 129 /* erase sector */ #define CAN_DEBUG_FLASH_PROG 130 /* flash some bytes */ #define CAN_DEBUG_FLASH_EXIT 131 /* exit flash-mode */ #define CAN_DEBUG_FLASH_PROG_EX 132 /* flash some bytes */ #define CAN_DEBUG_SET_TRANS 140 /* Set firmware mode to 2.0A or 2.0B */ #define CAN_DEBUG_LEDS 150 /* Toggle LEDs, etc. */ #define CAN_DEBUG_BUSMASTER_INFO 151 /* Print information regarding busmastering */ #define CAN_DEBUG_USB_TEST 152 /* Send generated testframes */ #define CAN_DEBUG_USB_IO_TEST 153 /* IO Config for IRIG Trigger Lines */ /* debug-access-values */ #define CAN_ACCESS_BYTE 0 #define CAN_ACCESS_WORD 1 #define CAN_ACCESS_LONG 2 /* * can-error-codes */ #define CANIO_ERRNO_BASE 0x00000100 /* base for esd-codes */ #define CANIO_SUCCESS 0 #define CANIO_RX_TIMEOUT (CANIO_ERRNO_BASE+1) #define CANIO_TX_TIMEOUT (CANIO_ERRNO_BASE+2) /* #define CANIO_UNUSED (CANIO_ERRNO_BASE+3) */ #define CANIO_TX_ERROR (CANIO_ERRNO_BASE+4) #define CANIO_CONTR_OFF_BUS (CANIO_ERRNO_BASE+5) #define CANIO_CONTR_BUSY (CANIO_ERRNO_BASE+6) #define CANIO_CONTR_WARN (CANIO_ERRNO_BASE+7) #define CANIO_OLDDATA (CANIO_ERRNO_BASE+8) #define CANIO_NO_ID_ENABLED (CANIO_ERRNO_BASE+9) #define CANIO_ID_ALREADY_ENABLED (CANIO_ERRNO_BASE+10) #define CANIO_ID_NOT_ENABLED (CANIO_ERRNO_BASE+11) /* #define CANIO_UNUSED (CANIO_ERRNO_BASE+12) */ #define CANIO_INVALID_FIRMWARE (CANIO_ERRNO_BASE+13) #define CANIO_MESSAGE_LOST (CANIO_ERRNO_BASE+14) #define CANIO_INVALID_HARDWARE (CANIO_ERRNO_BASE+15) #define CANIO_PENDING_WRITE (CANIO_ERRNO_BASE+16) #define CANIO_PENDING_READ (CANIO_ERRNO_BASE+17) #define CANIO_INVALID_DRIVER (CANIO_ERRNO_BASE+18) #define CANIO_INVALID_PARAMETER EINVAL #define CANIO_INVALID_HANDLE EBADFD /* #define CANIO_IO_INCOMPLETE not reasonable under Linux */ /* #define CANIO_IO_PENDING not reasonable under Linux */ #define CANIO_NET_NOT_FOUND ENODEV #define CANIO_INSUFFICIENT_RESOURCES ENOMEM #define CANIO_OPERATION_ABORTED EINTR #define CANIO_WRONG_DEVICE_STATE (CANIO_ERRNO_BASE+19) #define CANIO_HANDLE_FORCED_CLOSE (CANIO_ERRNO_BASE+20) #define CANIO_NOT_IMPLEMENTED ENOSYS #define CANIO_NOT_SUPPORTED (CANIO_ERRNO_BASE+21) #define CANIO_CONTR_ERR_PASSIVE (CANIO_ERRNO_BASE+22) #define CANIO_ERROR_NO_BAUDRATE (CANIO_ERRNO_BASE+23) #define CANIO_ERROR_LOM (CANIO_ERRNO_BASE+24) /* Der MT Gedenk Fehlercode... */ /* Errors used in esdcan, but not formerly present in canio.h * Used in situations, where errno-systems return the respecting errno */ #define CANIO_EIO EIO #define CANIO_EFAULT EFAULT #define CANIO_EBUSY EBUSY #define CANIO_EAGAIN EAGAIN #define CANIO_ENOENT ENOENT #define CANIO_ERESTART ERESTART /* This error should never ever reach user level!!! */ #define CANIO_ERROR 1 /* todo: Generic Error...not EPERM */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __CANIO_H__ */
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/flashtail.h
/* -*- linux-c -*- * FILE NAME flashtail.h * copyright 2014 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * system info page resources for CAN-CPIe/402 boards * * * Author: Michael Schmidt * michael.schmidt@esd.eu * * history: * $Log$ * Revision 1.2 2015/05/11 17:29:16 manuel * Removed unused stuff causing trouble for win32 * * Revision 1.1 2014/10/21 17:56:13 mschmidt * Extracted struct _FLASH_TAIL from boardrc.h into flashtail.h. * * * */ /************************************************************************ * * Copyright (c) 1996 - 2015 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd.eu * Germany sales@esd.eu * *************************************************************************/ /*! * \file flashtail.h * \brief Structure of the system info page */ #ifndef BOARD_ESDACC_PCIE402_FLASHTAIL_H_ #define BOARD_ESDACC_PCIE402_FLASHTAIL_H_ #define FPGA_TYPE_ALTERA_GX15 15u #define FPGA_TYPE_ALTERA_GX22 22u #define FPGA_TYPE_ALTERA_GX30 30u #if !defined OSIF_KERNEL # include <stdint.h> typedef int8_t INT8; typedef uint8_t UINT8; typedef int16_t INT16; typedef uint16_t UINT16; typedef int32_t INT32; typedef uint32_t UINT32; typedef int64_t INT64; typedef uint64_t UINT64; typedef char CHAR8; #endif struct _FLASH_TAIL { CHAR8 strBoard[16]; CHAR8 strOrderNumber[16]; CHAR8 strSerialNumber[16]; INT8 ucNumberOfNets; INT8 ucBaseNet; INT8 ucFeatures[2]; UINT32 uiFeaturesExt; CHAR8 strBoardDetails[16]; UINT8 ucTrxId; UINT8 ucFpgaTypeId; UINT8 ucReserved1[2]; UINT32 uiReserved1[41]; INT8 ucMagic[8]; UINT8 ucVersionResv[2]; /* Don't use! Needed for updpcie402, only... */ INT8 ucReserved0[2]; UINT32 uiCrc32; }; static const size_t lengthCrcRegion = 0xFC; #endif /* BOARD_ESDACC_PCIE402_FLASHTAIL_H_ */
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/esdcan.h
/* -*- esdcan-c -*- * FILE NAME esdcan.h * copyright 2002-2015 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * * * * history: * * $Log$ * Revision 1.64 2015/05/29 18:14:23 stefanm * Added <doNotTouch> structure member for power management (other OSes). * * Revision 1.63 2015/05/29 17:02:49 stefanm * Adaption to VERSION96 type. * * Revision 1.62 2015/05/29 14:32:10 stefanm * Now the <crd> pointer in the CAN_NODE structure has its real CAN_CARD type. * * Revision 1.61 2015/01/13 15:31:03 stefanm * Added support for NTCAN_IOCTL_GET_INFO / IOCTL_ESDCAN_GET_INFO. * Will now count active nodes in <num_nodes> of card structure. * New <version_firmware2> is needed for USB400 Cypress updateable FW. * * Revision 1.60 2015/01/09 15:18:51 stefanm * Provide a real board status for the canStatus() call which is kept * now in the card structure. * * Revision 1.59 2014/11/03 12:44:54 manuel * Completely removed PENDING_TXOBJ states * (TXOBJ does not use tx_done so esdcan layer does not need to remember it). * * Revision 1.58 2014/10/27 07:01:34 oliver * Added trx_type to _CAN_NODE structure. * * Revision 1.57 2014/08/21 13:16:32 manuel * cmbuf and cmbuf in in CAN_OCB are now CAN_MSG_X if BOARD_CAN_FD is defined * * Revision 1.56 2014/07/04 10:01:56 hauke * Removed <canio.h> which is included in osif.h and include <boardrc.h> befor <cm.h>. * * Revision 1.55 2013/06/27 12:48:40 andreas * Comment removed * * Revision 1.54 2013/04/26 14:34:18 andreas * Removed unsused cmd member from CAN_OCB structure * * Revision 1.53 2013/01/11 18:27:24 andreas * Added define TX_TS_WIN_DEF * Added tx_ts_win to CAN_NODE * Reworked CAN_OCB structure with rx and tx substructures (like in other esdcan layers) * * Revision 1.52 2012/11/08 14:14:42 andreas * Fixed bug on handle close (two threads entering driver on same handle with ioctl_destroy) * * Revision 1.51 2011/11/01 15:30:02 andreas * Merged with preempt_rt branch * With OSIF_USE_PREEMPT_RT_IMPLEMENTATION the new implementation is used for * all kernels > 2.6.20 * Some cleanup * Updated copyright notice * * Revision 1.50 2011/05/18 16:00:21 andreas * Removed sema_rx_abort from OCB structure * * Revision 1.49 2011/02/17 16:28:19 andreas * Added another RX state flag: RX_STATE_CLOSING * * Revision 1.48 2010/06/16 15:00:50 michael * Smart id filter nucleus support. * New filter not yet connected to user api. * 3rd trial. * * Revision 1.47 2010/04/16 16:26:11 andreas * Moved LNK forward declaration into cm.h * * Revision 1.46 2010/03/16 10:32:12 andreas * Added wqRx waitqueue to CAN_NODE structure (for select implementation) * * Revision 1.45 2009/07/31 14:59:36 andreas * Untabbified * Removed some old, redundant forgotten pci405fw code * * Revision 1.44 2009/03/02 17:50:04 andreas * Fixed Linux dependency (caused by replacement of OSIF_SEMA with * struct semaphore) * * Revision 1.43 2009/02/25 16:23:18 andreas * Replaced usage of OSIF_SEMA by direct use of struct semaphore * Added two semaphores for RX/TX jobs which are interrupted by signal * * Revision 1.42 2008/12/02 11:13:08 andreas * Removed redundant br_info from CAN_NODE struct * * Revision 1.41 2008/11/18 11:41:31 matthias * pmc440fw also requires host handle * * Revision 1.40 2007/11/05 14:58:54 andreas * Added can_stat to CAN_NODE structure * * Revision 1.39 2006/06/27 09:57:08 andreas * Added ctrl_type, ctrl_clock and br_info to CAN_NODE * * Revision 1.38 2005/09/14 15:58:53 michael * filter 20b added * * Revision 1.37 2005/08/22 16:26:58 andreas * Added filter_cmd to ocb-structure * * Revision 1.36 2005/08/03 11:28:08 andreas * Added serial to crd structure (fur use with ioctl get serial) * * Revision 1.35 2005/07/29 08:20:00 andreas * crd-structure stores pointer (pCardIdent) into cardFlavours structure instead of index (flavour), now * * Revision 1.34 2005/07/28 07:34:24 andreas * version_firmware and version_hardware got removed from node-structure. * flavour was added to crd-structure. * * 11.05.04 - removed esdcan_err_put ab * 13.02.03 - added file-pointer to OCB-structure * - changed node->lock_irq into an OSIF_IRQ_MUTEX ab * 27.05.02 - first version mf * */ /************************************************************************ * * Copyright (c) 1996 - 2014 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd-electronics.com * Germany sales@esd-electronics.com * *************************************************************************/ /*! \file esdcan.h * \brief Contains CAN_OCB, CAN_NODE-defines and related stuff. * * \par General rules: * */ #ifndef __ESDCAN_H__ #define __ESDCAN_H__ #include <osif.h> #include <boardrc.h> #include <cm.h> #ifndef OSIF_KERNEL #error "This file may be used in the kernel-context, only! Not for application-use!!!" #endif #ifdef NUC_TX_TS # define TX_TS_WIN_DEF 10 #else # define TX_TS_WIN_DEF 0 #endif #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION #define TX_STATE_PENDING_WRITE 0x01 #define TX_STATE_PENDING_SEND 0x02 #define TX_STATE_ABORT 0x10 #define TX_STATE_SIGNAL_INTERRUPT 0x20 #define TX_STATE_CLOSING 0x40 #define RX_STATE_PENDING_READ 0x01 #define RX_STATE_PENDING_TAKE 0x02 #define RX_STATE_ABORT 0x10 #define RX_STATE_SIGNAL_INTERRUPT 0x20 #define RX_STATE_CLOSING 0x40 #else #define TX_STATE_PENDING_WRITE 0x01 #define TX_STATE_PENDING_SEND 0x02 #define TX_STATE_ABORTING 0x80 #define RX_STATE_PENDING_READ 0x01 #define RX_STATE_PENDING_TAKE 0x02 #define RX_STATE_CLOSING 0x40 #define RX_STATE_ABORTING 0x80 #endif #define CLOSE_STATE_CLOSE_DONE 0x00000001 #define CLOSE_STATE_HANDLE_CLOSED 0x80000000 typedef struct _CAN_OCB CAN_OCB; typedef struct _OSIF_CARD OSIF_CARD; typedef struct _CAN_NODE CAN_NODE; typedef struct _CAN_CARD CAN_CARD; struct _CAN_OCB { VOID *nuc_ocb; VOID *cif_ocb; CAN_NODE *node; CM *rx_cm; struct _rx { UINT32 tout; INT32 result; volatile INT32 state; INT32 cm_count; INT32 cm_size; #ifdef BOARD_CAN_FD CAN_MSG_X *cmbuf; CAN_MSG_X *cmbuf_in; #else CAN_MSG_T *cmbuf; CAN_MSG_T *cmbuf_in; #endif UINT8 *user_buf; } rx; struct _tx { CM *cm; UINT32 tout; INT32 result; volatile INT32 state; INT32 cm_count; INT32 cm_size; UINT8 *user_buf; CM *cm_buf; } tx; INT32 minor; UINT32 mode; UINT32 filter_cmd; struct _filter20b { UINT32 acr; UINT32 amr; } filter20b; volatile UINT32 close_state; struct file *file; /* !!!Leave at end, Linux specific!!! */ #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION wait_queue_head_t wqRx; wait_queue_head_t wqTx; wait_queue_head_t wqCloseDelay; #else struct semaphore sema_rx; struct semaphore sema_tx; struct semaphore sema_tx_abort; /* uninterruptible */ struct semaphore sema_close; #endif }; #ifdef BOARD_CAN_FD #define MAX_NUM_DLC 16 /* number of different length DLC codes */ #else #define MAX_NUM_DLC (8+1) /* number of different length DLC codes */ #endif typedef struct _CAN_NODE_STAT { CAN_BUS_STAT cbs; /* struct to interface to NTCAN */ /* driver internal part */ uint32_t msg_count_std[MAX_NUM_DLC]; /*# of 2.0A msgs*/ uint32_t msg_count_ext[MAX_NUM_DLC]; /*# of 2.0B msgs*/ } CAN_NODE_STAT; struct _CAN_NODE { VOID *nuc_node; VOID *cif_node; UINT32 features; /* flags are ored in layer's attach function */ UINT32 mode; /* enabled features */ UINT32 status; /* node status flags (e.g. CANIO_STATUS_WRONG_* + CANIO_STATUS_MASK_BUSSTATE) */ VOID *base[4]; /* base[0] = sja address */ CAN_CARD *crd; INT32 net_no; /* counts nets over all cards, globally */ INT32 node_no; /* counts nets _per_ card, locally */ OSIF_MUTEX lock; OSIF_IRQ_MUTEX lock_irq; volatile INT32 irq_flag; UINT32 ctrl_clock; /* frequency of CAN controller */ UINT8 ctrl_type; /* type of CAN controller (use CANIO_CANCTL_xxx defines) */ UINT8 trx_type; /* Type of CAN transceiver (use CANIO_TRX_XXX defines) */ UINT32 tx_ts_win; CAN_NODE_STAT can_stat; /* driver internal node statistic */ /* !!!Leave at end, Linux specific!!! */ wait_queue_head_t wqRxNotify; }; struct _CAN_CARD { VOID *base[8]; UINT32 range[8]; UINT32 irq[8]; CAN_NODE *node[8]; INT32 num_nodes; /* # of active nodes on this card for NTCAN_INFO */ INT32 card_no; UINT32 features; CARD_IRQ irqs[8]; VERSION96 version_firmware; VERSION96 version_firmware2; /* for updateable second firmware e.g. Cypress Bootloader USB400 */ /* This is NOT the IRIG FW version which is read via the IRIG lib. */ VERSION96 version_hardware; CARD_IDENT *pCardIdent; UINT32 serial; UINT16 board_status; /* board status flags (wrong firmware/hardware) */ UINT8 doNotTouch; /* TRUE if HW must not be touched */ UINT8 reserved; #if defined (CIF_CARD) /* board specific part (see boardrc.h)... */ CIF_CARD #endif }; #endif
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/board.h
/* -*- linux-c -*- * FILE NAME board.h * copyright 2002 - 2014 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * board layer API * * * Author: Matthias Fuchs * matthias.fuchs@esd-electronics.com * * history: * * 27.05.02 - first version mf * 11.05.04 - changed OSIF_EXTERN into extern and OSIF_CALLTYPE ab * */ /************************************************************************ * * Copyright (c) 1996 - 2014 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd-electronics.com * Germany sales@esd-electronics.com * *************************************************************************/ /*! \file board.h \brief Card interface API This file contains the API for accessing the CAN driver's card layer. The functions are called by the nucleus modules. */ #ifndef __BOARD_H__ #define __BOARD_H__ #include <esdcan.h> #ifdef ESDDBG /*!< Macro for debug prints, same in ALL board layer files... */ # define BOARD_DBG(fmt) OSIF_DPRINT(fmt) #else # define BOARD_DBG(fmt) #endif /* Zones to use with debug prints in boardrc.c */ #define RC_ZONE_FU OSIF_ZONE_BOARD | OSIF_ZONE_FUNC #define RC_ZONE_INIFU OSIF_ZONE_BOARD | OSIF_ZONE_INIT|OSIF_ZONE_FUNC #define RC_ZONE_INI OSIF_ZONE_BOARD | OSIF_ZONE_INIT #define RC_ZONE_IRQ OSIF_ZONE_IRQ /* DO NOT USE ANY MORE BITS (nto will thank you:) */ #define RC_ZONE_ALWAYS 0xFFFFFFFF #define RC_ZONE_WARN OSIF_ZONE_BOARD | OSIF_ZONE_WARN #define RC_ZONE_USR_INIT OSIF_ZONE_BOARD | OSIF_ZONE_USR_INIT #define RC_ZONE OSIF_ZONE_BOARD /* Zones to use with debug prints in board.c */ #define BOARD_ZONE_INI OSIF_ZONE_BOARD | OSIF_ZONE_INIT /* Driver init/deinit */ #define BOARD_ZONE_FU OSIF_ZONE_BOARD | OSIF_ZONE_FUNC /* Function entry/exit */ #define BOARD_ZONE_INIFU OSIF_ZONE_BOARD | OSIF_ZONE_INIT | OSIF_ZONE_FUNC #define BOARD_ZONE_BAUD OSIF_ZONE_BOARD | OSIF_ZONE_FUNC | OSIF_ZONE_BAUD /* Function entry/exit in bitrate setting baud calculation... */ #define BOARD_ZONE_IRQ OSIF_ZONE_IRQ /* DO NOT USE ANY MORE BITS (nto will thank you:) */ #define BOARD_ZONE OSIF_ZONE_BOARD #ifndef CIF_TS2MS #define CIF_TS2MS(ts, tsf) ts *= 1000; OSIF_DIV64_64(ts, tsf) #endif extern CARD_IDENT cardFlavours[]; extern INT32 cif_open( CAN_OCB *ocb, CAN_NODE *node, INT32 flags ); extern INT32 cif_close( CAN_OCB *ocb ); extern INT32 cif_node_attach( CAN_NODE *node, UINT32 queue_size_rx); extern INT32 cif_node_detach( CAN_NODE *node ); extern INT32 cif_id_filter( CAN_NODE *node, UINT32 cmd, UINT32 id, UINT32 *count ); extern INT32 OSIF_CALLTYPE cif_tx( CAN_NODE *node ); extern INT32 cif_tx_obj( CAN_NODE *node, UINT32 cmd, VOID *arg ); extern INT32 cif_tx_abort( CAN_NODE *node, CM *cm, INT32 status ); extern INT32 cif_baudrate_set( CAN_NODE *node, UINT32 baud ); /* can_node MUST be provided, ocb and waitContext might be NULL (should fail if ocb or waitContext needed then) */ extern INT32 cif_ioctl( CAN_NODE *can_node, CAN_OCB *ocb, VOID *waitContext, UINT32 cmd, VOID *buf_in, UINT32 len_in, VOID *buf_out, UINT32 *len_out ); extern INT32 cif_timestamp( CAN_NODE *node, OSIF_TS *timestamp ); /* 1) implementation for soft timestamps is in board/<board>/board.c 2) implementation for hard timestamps is in board/<board>/boardrc.c (this is very hardware specific !) */ extern INT32 cif_softts_get( VOID *dummy, OSIF_TS *ts ); extern INT32 cif_softts_freq_get( VOID *dummy, OSIF_TS_FREQ *ts_freq ); /* Enable/disable the interrupt (also implicitely called during attach/detach) */ extern INT32 OSIF_CALLTYPE can_board_enable_interrupt(CAN_CARD *crd); extern INT32 OSIF_CALLTYPE can_board_disable_interrupt(CAN_CARD *crd); INT32 OSIF_CALLTYPE can_board_attach_pre(CAN_CARD *crd); #if defined(OSIF_PNP_OS) INT32 OSIF_CALLTYPE can_board_attach( CAN_CARD *crd, OSIF_POWER_STATE targetState ); INT32 OSIF_CALLTYPE can_board_attach_final( CAN_CARD *crd, OSIF_POWER_STATE targetState ); INT32 OSIF_CALLTYPE can_board_detach( CAN_CARD *crd, OSIF_POWER_STATE targetState ); /* CAN_BOARD_DETACH_FINAL may be defined in boardrc.h */ # ifndef CAN_BOARD_DETACH_FINAL # define CAN_BOARD_DETACH_FINAL(pCrd, targetState) # else INT32 OSIF_CALLTYPE can_board_detach_final( CAN_CARD *crd, OSIF_POWER_STATE targetState ); # endif #else INT32 OSIF_CALLTYPE can_board_attach( CAN_CARD *crd ); INT32 OSIF_CALLTYPE can_board_attach_final( CAN_CARD *crd ); INT32 OSIF_CALLTYPE can_board_detach( CAN_CARD *crd ); /* CAN_BOARD_DETACH_FINAL may be defined in boardrc.h */ #ifndef CAN_BOARD_DETACH_FINAL # define CAN_BOARD_DETACH_FINAL(pCrd) # else INT32 OSIF_CALLTYPE can_board_detach_final( CAN_CARD *crd ); #endif #endif /* of OSIF_PNP_OS */ #if defined (BOARD_USB) VOID OSIF_CALLTYPE usb_write_tx_cm(const volatile UINT32 *pAddr, CM *pCm); VOID OSIF_CALLTYPE usb_write_tx_ts_cm(const volatile UINT32 *pAddr, CM *pCm); #endif #endif /* __BOARD_H__ */
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/nucleus.h
/* -*- esdcan-c -*- * FILE NAME nucleus.h * copyright 2002 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * ... * * * Author: Matthias Fuchs * matthias.fuchs@esd-electronics.com * * history: * * 07.03.06 - added nuc_deferred_tx_messages * - added nuc_tx_messages mk * 11.05.04 - changed OSIF_EXTERN into extern and OSIF_CALLTYPE ab * 13.11.03 - added nuc_get_ocb() * renamed nuc_tx_abort_force() into nuc_tx_abort_board() ab * 24.05.02 - first version mf * */ /************************************************************************ * * Copyright (c) 1996 - 2015 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd-electronics.com * Germany sales@esd-electronics.com * *************************************************************************/ /*! \file nucleus.h * \brief Contains defines and prototypes of the CAN-nucleus. * * \par General rules: * */ #ifndef __NUCLEUS_H__ #define __NUCLEUS_H__ #include <esdcan.h> #include <board.h> #ifndef OSIF_KERNEL #error "This file may be used in the kernel-context, only! Not for application-use!!!" #endif /* #define NUC_CHECK_LINKS */ /* for debugging only, degrades performance significantly */ #ifndef NUC_NODE_RX_QUEUE_SIZE #define NUC_NODE_RX_QUEUE_SIZE 1024 /* default very big rx queue inside node */ #endif #define RX_LOOKUP_MAX_COUNT 4 #define NUC_TX_OBJ_CREATE 0 #define NUC_TX_OBJ_AUTOANSWER_ON 1 #define NUC_TX_OBJ_AUTOANSWER_OFF 2 #define NUC_TX_OBJ_UPDATE 3 #define NUC_TX_OBJ_DESTROY 4 #define NUC_TX_OBJ_SCHEDULE 5 #define NUC_TX_OBJ_SCHEDULE_START 6 #define NUC_TX_OBJ_SCHEDULE_STOP 7 #define NUC_RX_OBJ_CREATE 0 #define NUC_RX_OBJ_TAKE 1 #define NUC_RX_OBJ_DESTROY 2 #define NUC_STAT_CM_RX 0 #define NUC_STAT_CM_TX 1 #define NUC_STAT_CTRL_OVERR 2 #define NUC_STAT_FIFO_OVERR 3 #define NUC_STAT_ERROR_FRAME 4 #define NUC_STAT_ABORT 5 /* Macros to operate on linked list (type definition in osif.h) */ #define INIT_LNK(lnk, _base) (lnk)->next=NULL; (lnk)->prev=NULL; (lnk)->base = (_base) #define INIT_LNK_ROOT(lnk) (lnk)->next=(lnk); (lnk)->prev=(lnk) #define GET_LNK_FIRST(root) ((root) == (root)->next ? NULL : (root)->next) #define GET_LNK_NEXT(lnk, root) ((root) == (lnk)->next ? NULL : (lnk)->next) #define GET_LNK_LAST(root) ((root) == (root)->prev ? NULL : (root)->prev) #define GET_LNK_PREV(lnk, root) ((root) == (lnk)->prev ? NULL : (lnk)->prev) #define ASK_LNK_CHANGED(root) (root)->base == NULL ? 0 : ((root)->base = NULL, 1) #define SET_LNK_CHANGED(root) (root)->base = (VOID *)(UINTPTR)1 extern UINT32 baud_table[]; typedef struct _NUC_OCB NUC_OCB; /* only nucleus internal usage! */ typedef struct _NUC_NODE NUC_NODE; /* only nucleus internal usage! */ typedef struct _NUC_CALLBACKS NUC_CALLBACKS; struct _NUC_CALLBACKS { INT32 (OSIF_CALLTYPE *close_done)( CAN_OCB *ocb ); INT32 (OSIF_CALLTYPE *tx_done)( CAN_OCB *ocb, INT32 result, UINT32 cm_count ); INT32 (OSIF_CALLTYPE *tx_get)( CAN_OCB *ocb, CM *cm ); INT32 (OSIF_CALLTYPE *tx_obj_get)( CAN_OCB *ocb, CM *cm ); INT32 (OSIF_CALLTYPE *tx_obj_sched_get)( CAN_OCB *ocb, CMSCHED *sched ); INT32 (OSIF_CALLTYPE *rx_done)( CAN_OCB *ocb, INT32 result, UINT32 cm_count ); INT32 (OSIF_CALLTYPE *rx_put)( CAN_OCB *ocb, CM *cm ); INT32 (OSIF_CALLTYPE *rx_obj_put)( CAN_OCB *ocb, CM *cm, UINT32 *next_id ); INT32 (OSIF_CALLTYPE *ioctl_done)( CAN_OCB *ocb, VOID *waitContext, UINT32 cmd, INT32 result, UINT32 len_out ); /* INT32 (*err_put)( CAN_NODE *can_node, INT32 err ); */ INT32 (OSIF_CALLTYPE *rx_notify)( CAN_OCB *ocb ); }; /* * nucleus helper routines to oerate on linked lists (type definition in osif.h) */ extern INT32 OSIF_CALLTYPE nuc_link_obj(LNK *obj, LNK *root); extern INT32 OSIF_CALLTYPE nuc_unlink_obj(LNK *obj ); /* * nucleus interface for OS module */ extern INT32 OSIF_CALLTYPE nuc_open( CAN_OCB *ocb, CAN_NODE *node, NUC_CALLBACKS *cm, UINT32 flags, UINT32 queue_size_tx, UINT32 queue_size_rx ); extern INT32 OSIF_CALLTYPE nuc_close( CAN_OCB *ocb ); extern INT32 OSIF_CALLTYPE nuc_tx_abort( CAN_OCB *ocb, INT32 status, UINT64 host_hnd ); extern INT32 OSIF_CALLTYPE nuc_rx_abort( CAN_OCB *ocb, INT32 status ); extern INT32 OSIF_CALLTYPE nuc_rx_purge( CAN_OCB *ocb ); extern INT32 OSIF_CALLTYPE nuc_rx_messages( CAN_OCB *ocb, UINT32 *count ); extern INT32 OSIF_CALLTYPE nuc_tx_messages( CAN_OCB *ocb, UINT32 *count ); extern INT32 OSIF_CALLTYPE nuc_deferred_tx_messages( CAN_OCB *ocb, UINT32 *count ); extern INT32 OSIF_CALLTYPE nuc_ioctl( CAN_OCB *can_ocb, VOID *waitContext, UINT32 cmd, VOID *buf_in, UINT32 len_in, VOID *buf_out, UINT32 *len_out ); extern INT32 OSIF_CALLTYPE nuc_rx( CAN_OCB *ocb, UINT32 timeout, UINT32 *count ); extern INT32 OSIF_CALLTYPE nuc_rx_obj( CAN_OCB *ocb, UINT32 *count, UINT32 id ); extern INT32 OSIF_CALLTYPE nuc_tx( CAN_OCB *ocb, UINT32 timeout, UINT32 *count ); extern INT32 OSIF_CALLTYPE nuc_tx_obj( CAN_OCB *ocb, UINT32 cmd, UINT32 *count ); extern INT32 OSIF_CALLTYPE nuc_tx_obj_schedule_stop( CAN_NODE *can_node ); extern INT32 OSIF_CALLTYPE nuc_node_attach( CAN_NODE *node, UINT32 queue_size_rx ); extern INT32 OSIF_CALLTYPE nuc_node_detach( CAN_NODE *node ); extern INT32 OSIF_CALLTYPE nuc_baudrate_set( CAN_NODE *node, UINT32 baud ); extern INT32 OSIF_CALLTYPE nuc_baudrate_get( CAN_NODE *node, UINT32 *baud ); extern INT32 OSIF_CALLTYPE nuc_baudrate_get_info( CAN_NODE *can_node, UINT32 baud_req, CAN_BITRATE *baud_info ); extern VOID OSIF_CALLTYPE nuc_baudrate_set_info( CAN_NODE *can_node, CAN_BITRATE *baud_info ); extern INT32 OSIF_CALLTYPE nuc_baudrate_calc( CAN_NODE *node, UINT32 rate, CAN_BITRATE *baud_info ); extern VOID OSIF_CALLTYPE nuc_baudrate_change_event( CAN_NODE *can_node, OSIF_TS *timestamp ); extern INT32 OSIF_CALLTYPE nuc_id_filter_mask( CAN_OCB *can_ocb, UINT32 amr, UINT32 acr, UINT32 idArea ); extern INT32 OSIF_CALLTYPE nuc_id_filter( CAN_OCB *ocb, UINT32 cmd, UINT32 id, UINT32 *count ); extern INT32 OSIF_CALLTYPE nuc_id_range_check( UINT32 id_1st, UINT32 id_lst ); extern INT32 OSIF_CALLTYPE nuc_id_filter_restore(CAN_NODE *can_node); extern INT32 OSIF_CALLTYPE nuc_timestamp( CAN_NODE *node, OSIF_TS *timestamp, OSIF_TS_FREQ *frequency ); extern CAN_OCB* OSIF_CALLTYPE nuc_ocb_get( CAN_NODE *can_node, CAN_OCB *ocb ); /* * nucleus interface for CIF module */ extern VOID OSIF_CALLTYPE nuc_tx_get( CAN_NODE *node, CM **cm ); extern VOID OSIF_CALLTYPE nuc_tx_ts_get( CAN_NODE *node, CM **cm ); extern INT32 OSIF_CALLTYPE nuc_tx_done( CAN_NODE *node, INT32 status, CM *cm ); extern INT32 OSIF_CALLTYPE nuc_tx_done_cm( CAN_NODE *node, INT32 status, CM *cm ); extern INT32 OSIF_CALLTYPE nuc_tx_done_trigger( CAN_NODE *node ); extern INT32 OSIF_CALLTYPE nuc_rx_put( CAN_NODE *node, CM **cm ); extern INT32 OSIF_CALLTYPE nuc_rx_put_cm( CAN_NODE *node, CM **cm ); extern INT32 OSIF_CALLTYPE nuc_rx_put_trigger( CAN_NODE *node ); /* extern INT32 OSIF_CALLTYPE nuc_err_put( CAN_NODE *node, INT32 error ); */ extern VOID OSIF_CALLTYPE nuc_tx_abort_board( INT32 status, CM *cm ); extern INT32 OSIF_CALLTYPE nuc_ioctl_done( CAN_OCB *can_ocb, VOID *waitContext, UINT32 cmd, INT32 status, INT32 len_out ); extern INT32 OSIF_CALLTYPE nuc_busload_start( CAN_NODE *node ); extern VOID OSIF_CALLTYPE nuc_busload_stop( CAN_NODE *node ); #ifdef BUS_STATISTICS extern VOID OSIF_CALLTYPE nuc_count_cm( CAN_NODE *node, CM *cm, INT32 type ); #else # define nuc_count_cm(mnode, cm, type) #endif #ifdef NUC_CHECK_LINKS int nuc_check_links(CAN_OCB *can_ocb); #else # define nuc_check_links(can_ocb) #endif #endif
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/osifi.h
/* -*- esdcan-c -*- * FILE NAME osifi.h * * BRIEF MODULE DESCRIPTION * ... * * history: * * $Log$ * Revision 1.88 2015/05/29 18:26:10 stefanm * Need a value for OSIF_CACHE_DMA_DEFAULTS. Sigh! * * Revision 1.87 2015/05/29 18:20:22 stefanm * Enable the default (dummy) implementation for the DMA handling * abstraction by defining OSIF_CACHE_DMA_DEFAULTS. * * Revision 1.86 2014/05/20 12:27:20 andreas * Whitespace change, only * * Revision 1.85 2013/12/30 16:53:35 frank * Made adaptions needed for directly accessing the SPI controller via esdcan-of-spi-connector and esd-omap2-mcspi * * Revision 1.84 2013/11/19 15:20:01 frank * Added SPI support (BOARD_SPI) * * Revision 1.83 2013/08/08 13:09:27 matthias * use software timestamps on ARM * * Revision 1.82 2013/07/16 14:17:00 andreas * Typo in comment fixed * * Revision 1.81 2013/04/26 14:26:28 andreas * White space change * * Revision 1.80 2013/01/18 16:56:46 andreas * Changed OSIF_TIMER implementation * - added CAN_NODE parameter to OSIF_TIMER_CREATE * - OSIF_TIMER structure is defined in osif.h and in osifi.h there's only a static extension OSIF_TIMER_SYS_PART * * Revision 1.79 2013/01/14 12:39:16 andreas * Removed rubbish in comment * * Revision 1.78 2012/10/23 15:28:44 andreas * Typo * * Revision 1.77 2012/02/17 18:39:58 andreas * Fixed OSIF_CALLTYPE position * Untabbified * * Revision 1.76 2011/11/01 15:26:55 andreas * Merged with preempt_rt branch * With OSIF_USE_PREEMPT_RT_IMPLEMENTATION the new implementation is used for * all kernels > 2.6.20 * Using correct defines for IRQ handler return values as of kernels 2.6.0+ * * Revision 1.75 2011/04/05 11:31:53 andreas * Changed to make use of new CHAR8 datatype * * Revision 1.74 2010/04/16 16:58:42 andreas * Fixed or at least unified OSIF_CALLTYPE declaration on dpc and timer create * * Revision 1.73 2010/03/16 10:50:56 andreas * Added include of linux/wait.h for select implementation * * Revision 1.72 2010/03/09 10:08:05 matthias * Beginning with 2.6.33 linux/autoconf.h moved to generated/autoconf.h. Also there is no need to include it. The kernel's build system passes it via -include option to gcc. * * Revision 1.71 2009/07/03 10:42:49 tkoerper * - Added #ifdefs for arm * * Revision 1.70 2009/05/18 08:38:30 andreas * Removed old osif_irq_(de)attach() stuff (already #if 0 for a long time) * * Revision 1.69 2009/02/25 16:15:40 andreas * Removed osif_sema_-calls * * Revision 1.68 2009/01/29 10:11:05 andreas * Removed osif_in_irq_lock()/-unlock() functions * * Revision 1.67 2008/12/10 10:54:46 manuel * Introduced inline functions for ISA port accesses * * Revision 1.66 2007/06/05 09:00:06 andreas * Added osif_usleep() * * Revision 1.65 2007/05/24 12:35:53 michael * BUGFIX: segfault in osif_div64_32 * * Revision 1.64 2007/05/24 10:10:28 michael * osif_div64_64 removed. * * Revision 1.63 2007/01/24 07:39:53 andreas * Changed #ifdef's around osif_tick_frequency() in order to release PPC host * driver for PMC331 * * Revision 1.62 2006/12/22 09:57:52 andreas * Fixed for kernels 2.6.19 * Exchanged include order of version.h and config.h/autoconf.h * Including autoconf.h instead of config.h for kernels >= 2.6.19 * * Revision 1.61 2006/10/16 07:18:38 andreas * Another fix for optimized swap macros (swap16 works with gcc2 and gcc3, again) * * Revision 1.60 2006/10/13 14:59:25 andreas * Another one for the optimized swap macros. * 32- and 64-Bit swaps are optimized for x86_64, too * * Revision 1.59 2006/10/13 14:08:39 andreas * Optimized macro for 64-Bit wasn't working under x86_64 * Added another variant for x86_64 * * Revision 1.58 2006/10/13 12:02:43 andreas * Deactivated optimized 32-Bit swap macro for x86_64 * * Revision 1.57 2006/10/13 10:08:17 andreas * Optimized macro for 64-Bit swap deactivated for gcc 2.x * * Revision 1.56 2006/10/12 10:35:23 manuel * Introduced inline assembler macros for swaps on x86 * * Revision 1.55 2006/02/14 09:17:46 matthias * -don't use OSIF_CALLTYPE with regparm(0) on PPC (not suppoted by ppc compiler) * * Revision 1.54 2005/12/08 11:33:41 andreas * Added comment for kernel 2.2.x users * * Revision 1.53 2005/11/02 07:00:40 andreas * Added declaration of osif_make_ntcan_serial() * * Revision 1.52 2005/10/06 07:43:03 matthias * added 64bit swap macros * * Revision 1.51 2005/09/23 15:28:37 manuel * Removed OSIF_PCI_OFFSET=0xC0000000 for PPC * * Revision 1.50 2005/07/27 15:50:51 andreas * Corrected OSIF_IRQ_HANDLER_CALLTYPE definition * * Revision 1.49 2005/07/13 08:57:04 matthias * added OSIF_IRQ_HANDLER_CALLTYPE * * Revision 1.48 2005/04/20 13:00:47 andreas * Added osif_ser_out() (prints debug output to serial) * * Revision 1.47 2004/10/29 15:28:53 matthias * use UINT32 instead of u32 * * Revision 1.46 2004/10/29 14:54:11 matthias * added osif_div64_64 * * Revision 1.45 2004/10/11 09:11:51 andreas * Changes for linux kernel 2.6 * (swap functions, i/o functions, etc.) * Added cvs log tag * Sorted history * * 13.05.04 - Added OSIF_CALLTYPE to timer functions ab * 11.05.04 - Reworked interrupt handler stuff again * Changed OSIF_EXTERN to extwern OSIF_CALLTYPE ab * 07.05.04 - Changed definition of interrupt handler stuff to * comply with kernel 2.6 ab * 06.05.04 - changed include of modversions for kernel 2.6.x * added asmlinkage to OSIF_EXTERN for kernel 2.6.x * added OSIF_BIG_ENDIAN, etc. for kernel 2.6.x ab * 01.12.03 - removed #ifdef in spinlock-structure ab * 26.11.03 - Removed OSIF_PCI_MALLOC warnings for non 405-cards ab * 13.11.03 - Corrected debug-info in mutexes ab * 13.11.03 - OSIF_MUTEX is a sema now Old one is now * OSIF_BUSY_MUTEX mt * 05.11.03 - Removed IRQ-flags from mutex structure again ab * 03.11.03 - added field for IRQ-flags in mutex-structure ab * 27.10.03 - New output function osif_dprint (with verbose mask) ab * 18.09.03 - Only one thread for all DPC's mt * 24.05.02 - first version mf * */ /************************************************************************ * * Copyright (c) 1996 - 2013 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd.eu * Germany support@esd.eu * *************************************************************************/ /*! \file osifi.h \brief OSIF operating system wrapping header This file contains the OSIF prototypes and user macros. Any driver should call the OSIF_<xxx> macros instead of the osif_<xxx> functions. */ #ifndef __OSIFI_H__ #define __OSIFI_H__ #include <linux/version.h> #if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32)) # if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19)) # include <linux/autoconf.h> # else # include <linux/config.h> # endif #endif #include <linux/errno.h> #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27) # include <linux/semaphore.h> #else # include <asm/semaphore.h> #endif #include <linux/wait.h> #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,18) # include <linux/irqreturn.h> #else # include <linux/interrupt.h> #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # ifdef OSIF_CALLTYPE # undef OSIF_CALLTYPE # endif # if !defined(CONFIG_PPC) && !defined(CONFIG_ARM) # define OSIF_CALLTYPE __attribute__((regparm(0))) /* asmlinkage */ # else # define OSIF_CALLTYPE # endif # if defined(CONFIG_X86) # define OSIF_ARCH_X86 # define OSIF_LITTLE_ENDIAN # endif # if defined(CONFIG_PPC) # define OSIF_ARCH_PPC # define OSIF_BIG_ENDIAN # endif # if defined(CONFIG_ARM) # define OSIF_ARCH_ARM # define OSIF_LITTLE_ENDIAN # endif #endif /* BL Note: Actually not a Linux induced version discrepancy, but code is only tested on versions higher 2.6.20 */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20) # define OSIF_USE_PREEMPT_RT_IMPLEMENTATION #endif /* * Select the default (dummy) implementation for cache DMA abstraction. * Keep in mind that for Linux the functions always must be implemented * if you stop using the default (dummy) implementation. */ #define OSIF_CACHE_DMA_DEFAULTS 1 #include "sysdep.h" #ifndef NULL # define NULL ((void*)0) #endif #include <osif_spi.h> #ifdef __KERNEL__ typedef struct _OSIF_SPIDEV OSIF_SPIDEV; struct _OSIF_SPIDEV { // spi_funcs_t* funcs; /* SPI master library function table */ // struct spi_device* dev; /* SPI device handle */ struct spi_candev *scdev; // int devno; /* Device number on bus */ }; typedef struct __OSIF_MUTEX *OSIF_MUTEX; typedef struct __OSIF_SPINLOCK *OSIF_BUSY_MUTEX, *OSIF_IRQ_MUTEX; typedef struct __OSIF_DPC _OSIF_DPC, *OSIF_DPC; struct __OSIF_DPC { OSIF_DPC next; INT8 linked; INT8 running; INT8 destroy; INT8 reserved; VOID (OSIF_CALLTYPE *func)(VOID *); VOID *arg; }; typedef struct _OSIF_LINUX_TIMER OSIF_LINUX_TIMER; #define OSIF_TIMER_SYS_PART /* no static extension of OSIF_TIMER struct */ #define OSIF_IRQ_HANDLER_CALLTYPE OSIF_CALLTYPE #define OSIF_IRQ_HANDLER_PARAMETER void* #define OSIF_IRQ_HANDLER(func,arg) int (OSIF_IRQ_HANDLER_CALLTYPE func) ( void *arg ) #define OSIF_IRQ_HANDLER_P int (OSIF_IRQ_HANDLER_CALLTYPE *) ( void *arg ) #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # define OSIF_IRQ_HANDLED (IRQ_HANDLED) # define OSIF_IRQ_HANDLED_NOT (IRQ_NONE) #else # define OSIF_IRQ_HANDLED (1) /* Equal to Linux2.6 IRQ_HANDLED */ # define OSIF_IRQ_HANDLED_NOT (0) #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # define OSIF_IRQ_HANDLER_RETURN( arg ) return IRQ_RETVAL(arg) #else # define OSIF_IRQ_HANDLER_RETURN( arg ) return arg #endif typedef struct pci_dev *OSIF_PCIDEV; #define OSIF_PCI_VADDR void * #define OSIF_PCI_MADDR UINT32 /* * Dear kernel 2.2.x user, * we are not able to determine the exact version, when * dma_addr_t was introduced into 2.2.x kernels. * If the following typedef leads to an compiletime error, * please comment the typedef. */ #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,0) typedef u32 dma_addr_t; #endif typedef struct __OSIF_PCI_PADDR _OSIF_PCI_PADDR, *OSIF_PCI_PADDR; #if defined(__GNUC__) && defined(CONFIG_X86) static inline void osif_io_out8(UINT8 *addr, UINT8 data) { asm volatile("outb %0,%1" : : "a" (data), "dN" ((UINT16)(UINTPTR)addr)); } static inline UINT8 osif_io_in8(UINT8 *addr) { UINT8 data; asm volatile("inb %1,%0" : "=a" (data) : "dN" ((UINT16)(UINTPTR)addr)); return data; } static inline void osif_io_out16(UINT16 *addr, UINT16 data) { asm volatile("outw %0,%1" : : "a" (data), "dN" ((UINT16)(UINTPTR)addr)); } static inline UINT16 osif_io_in16(UINT16 *addr) { UINT16 data; asm volatile("inw %1,%0" : "=a" (data) : "dN" ((UINT16)(UINTPTR)addr)); return data; } static inline void osif_io_out32(UINT32 *addr, UINT32 data) { asm volatile("outl %0,%1" : : "a" (data), "dN" ((UINT16)(UINTPTR)addr)); } static inline UINT32 osif_io_in32(UINT32 *addr) { UINT32 data; asm volatile("inl %1,%0" : "=a" (data) : "dN" ((UINT16)(UINTPTR)addr)); return data; } #else extern void OSIF_CALLTYPE osif_io_out8(UINT8 *addr, UINT8 data); extern UINT8 OSIF_CALLTYPE osif_io_in8(UINT8 *addr); extern void OSIF_CALLTYPE osif_io_out16(UINT16 *addr, UINT16 data); extern UINT16 OSIF_CALLTYPE osif_io_in16(UINT16 *addr); extern void OSIF_CALLTYPE osif_io_out32(UINT32 *addr, UINT32 data); extern UINT32 OSIF_CALLTYPE osif_io_in32(UINT32 *addr); #define OSIF_USE_IO_FUNCTIONS #endif #define osif_mem_out8( addr, data ) (*(volatile UINT8* )(addr)) = (data) #define osif_mem_in8( addr ) (*(volatile UINT8* )(addr)) #define osif_mem_out16( addr, data ) (*(volatile UINT16*)(addr)) = (data) #define osif_mem_in16( addr ) (*(volatile UINT16*)(addr)) #define osif_mem_out32( addr, data ) (*(volatile UINT32*)(addr)) = (data) #define osif_mem_in32( addr ) (*(volatile UINT32*)(addr)) #if defined(__GNUC__) && defined(CONFIG_X86) /* too bad we cannot use 486 assembler here, because nucleus is compiled without knowledge of the system it is later used on */ #if (__GNUC__ > 2) #define osif_swap16(x) \ ({ \ register UINT16 __x; \ asm ("xchg %b1,%h1" : "=Q" (__x) : "0" ((UINT16)x)); \ __x; \ }) #else #define osif_swap16(x) \ ({ \ register UINT16 __x; \ asm ("xchg %b1,%h1" : "=q" (__x) : "0" ((UINT16)x)); \ __x; \ }) #endif #else /* sorry, no inline assembler macros for you */ #define osif_swap16(x) \ ({ \ UINT16 __x = (x); \ ((UINT16)( \ (((UINT16)(__x) & (UINT16)0x00ffU) << 8) | \ (((UINT16)(__x) & (UINT16)0xff00U) >> 8) )); \ }) #endif #if defined(__GNUC__) && defined(CONFIG_X86) #if !defined(CONFIG_X86_64) #define osif_swap32(x) \ ({ \ register UINT32 __x; \ asm ("xchg %b1,%h1; roll $16,%1; xchg %b1,%h1" : "=q" (__x) : "0" ((UINT32)x)); \ __x; \ }) #else #define osif_swap32(x) \ ({ \ register UINT32 __x; \ asm ("bswap %1" : "=r" (__x) : "0" ((UINT32)x)); \ __x; \ }) #endif #else /* sorry, no inline assembler macros for you */ #define osif_swap32(x) \ ({ \ UINT32 __x = (x); \ ((UINT32)( \ (((UINT32)(__x) & (UINT32)0x000000ffUL) << 24) | \ (((UINT32)(__x) & (UINT32)0x0000ff00UL) << 8) | \ (((UINT32)(__x) & (UINT32)0x00ff0000UL) >> 8) | \ (((UINT32)(__x) & (UINT32)0xff000000UL) >> 24) )); \ }) #endif #if (__GNUC__ > 2) && defined(CONFIG_X86) #if !defined(CONFIG_X86_64) #define osif_swap64(x) \ ({ \ register UINT64 __x; \ asm ("xchg %%ah,%%al; roll $16,%%eax; xchg %%ah,%%al; " \ "xchg %%eax,%%edx; " \ "xchg %%ah,%%al; roll $16,%%eax; xchg %%ah,%%al" : "=A" (__x) : "0" ((UINT64)x)); \ __x; \ }) #else #define osif_swap64(x) \ ({ \ register UINT64 __x; \ asm ("bswap %1" : "=r" (__x) : "0" ((UINT64)x)); \ __x; \ }) #endif #else /* sorry, no inline assembler macros for you */ #define osif_swap64(x) \ ({ \ UINT64 __x = (x); \ ((UINT64)( \ (((UINT64)(__x) & (UINT64)0x00000000000000ffULL) << (8*7)) | \ (((UINT64)(__x) & (UINT64)0x000000000000ff00ULL) << (8*5)) | \ (((UINT64)(__x) & (UINT64)0x0000000000ff0000ULL) << (8*3)) | \ (((UINT64)(__x) & (UINT64)0x00000000ff000000ULL) << (8*1)) | \ (((UINT64)(__x) & (UINT64)0x000000ff00000000ULL) >> (8*1)) | \ (((UINT64)(__x) & (UINT64)0x0000ff0000000000ULL) >> (8*3)) | \ (((UINT64)(__x) & (UINT64)0x00ff000000000000ULL) >> (8*5)) | \ (((UINT64)(__x) & (UINT64)0xff00000000000000ULL) >> (8*7)) )); \ }) #endif #ifdef OSIF_LITTLE_ENDIAN #define osif_cpu2be16(x) osif_swap16(x) #define osif_cpu2be32(x) osif_swap32(x) #define osif_cpu2be64(x) osif_swap64(x) #define osif_be162cpu(x) osif_swap16(x) #define osif_be322cpu(x) osif_swap32(x) #define osif_be642cpu(x) osif_swap64(x) #define osif_cpu2le16(x) (x) #define osif_cpu2le32(x) (x) #define osif_cpu2le64(x) (x) #define osif_le162cpu(x) (x) #define osif_le322cpu(x) (x) #define osif_le642cpu(x) (x) #else #define osif_cpu2be16(x) (x) #define osif_cpu2be32(x) (x) #define osif_cpu2be64(x) (x) #define osif_be162cpu(x) (x) #define osif_be322cpu(x) (x) #define osif_be642cpu(x) (x) #define osif_cpu2le16(x) osif_swap16(x) #define osif_cpu2le32(x) osif_swap32(x) #define osif_cpu2le64(x) osif_swap64(x) #define osif_le162cpu(x) osif_swap16(x) #define osif_le322cpu(x) osif_swap32(x) #define osif_le642cpu(x) osif_swap64(x) #endif #define osif_strtoul(pc,pe,b) simple_strtoul(pc,pe,b) extern INT32 OSIF_CALLTYPE osif_attach( VOID ); extern INT32 OSIF_CALLTYPE osif_detach( VOID ); extern INT32 osif_spi_attach(OSIF_SPIDEV *pDev, uint32_t spiClk); extern INT32 osif_spi_detach(OSIF_SPIDEV *pDev); extern INT32 osif_spi_xfer(OSIF_SPIDEV *pDev, OSIF_SPIMSG *pMsg); extern INT32 OSIF_CALLTYPE osif_malloc(UINT32 size, VOID **p); extern INT32 OSIF_CALLTYPE osif_free(VOID *ptr); extern INT32 OSIF_CALLTYPE osif_memset(VOID *ptr, UINT32 val, UINT32 size); extern INT32 OSIF_CALLTYPE osif_memcpy(VOID *dst, VOID *src, UINT32 size); extern INT32 OSIF_CALLTYPE osif_memcmp(VOID *dst, VOID *src, UINT32 size); extern VOID OSIF_CALLTYPE set_output_mask(UINT32 mask); #ifdef OSIF_OS_RTAI # ifdef BOARD_pci405fw extern INT32 OSIF_CALLTYPE pci405_printk(const char *fmt, ...); extern INT32 OSIF_CALLTYPE pci405_printk_init( VOID ); extern INT32 OSIF_CALLTYPE pci405_printk_cleanup( VOID ); # define osif_print(fmt... ) pci405_printk( ## fmt ) # else # define osif_print(fmt... ) rt_printk( ## fmt ) # endif #else extern INT32 OSIF_CALLTYPE osif_print(const CHAR8 *fmt, ...); #endif extern INT32 OSIF_CALLTYPE osif_dprint(UINT32 output_mask, const CHAR8 *fmt, ...); extern INT32 OSIF_CALLTYPE osif_snprintf(CHAR8 *str, INT32 size, const CHAR8 *format, ...); extern INT32 OSIF_CALLTYPE osif_mutex_create(OSIF_MUTEX *m); extern INT32 OSIF_CALLTYPE osif_mutex_destroy(OSIF_MUTEX *m); extern INT32 OSIF_CALLTYPE osif_mutex_lock(OSIF_MUTEX *m); extern INT32 OSIF_CALLTYPE osif_mutex_unlock(OSIF_MUTEX *m); extern INT32 OSIF_CALLTYPE osif_irq_mutex_create(OSIF_IRQ_MUTEX *im); extern INT32 OSIF_CALLTYPE osif_irq_mutex_destroy(OSIF_IRQ_MUTEX *im); extern INT32 OSIF_CALLTYPE osif_irq_mutex_lock(OSIF_IRQ_MUTEX *im); extern INT32 OSIF_CALLTYPE osif_irq_mutex_unlock(OSIF_IRQ_MUTEX *im); extern INT32 OSIF_CALLTYPE osif_sleep(INT32 ms); extern INT32 OSIF_CALLTYPE osif_usleep(INT32 us); extern INT32 OSIF_CALLTYPE osif_dpc_create( OSIF_DPC *dpc, VOID(OSIF_CALLTYPE *func)(VOID *), VOID *arg ); extern INT32 OSIF_CALLTYPE osif_dpc_destroy( OSIF_DPC *dpc ); extern INT32 OSIF_CALLTYPE osif_dpc_trigger( OSIF_DPC *dpc ); extern INT32 OSIF_CALLTYPE osif_timer_create( OSIF_TIMER *timer, VOID(OSIF_CALLTYPE *func)(VOID *), VOID *arg, VOID *pCanNode ); extern INT32 OSIF_CALLTYPE osif_timer_destroy( OSIF_TIMER *timer ); extern INT32 OSIF_CALLTYPE osif_timer_set( OSIF_TIMER *timer, UINT32 ms ); extern INT32 OSIF_CALLTYPE osif_timer_get( OSIF_TIMER *t, UINT32 *ms ); extern UINT64 OSIF_CALLTYPE osif_ticks( VOID ); extern UINT64 OSIF_CALLTYPE osif_tick_frequency( VOID ); extern INT32 OSIF_CALLTYPE osif_pci_malloc(OSIF_PCIDEV pcidev, OSIF_PCI_VADDR *vaddr, OSIF_PCI_PADDR *paddr, OSIF_PCI_MADDR *maddr, UINT32 size); extern INT32 OSIF_CALLTYPE osif_pci_free(OSIF_PCIDEV pcidev, OSIF_PCI_VADDR vaddr, OSIF_PCI_PADDR *paddr, OSIF_PCI_MADDR maddr, UINT32 size); extern UINT32 OSIF_CALLTYPE osif_pci_get_phy_addr(OSIF_PCI_PADDR paddr); extern INT32 OSIF_CALLTYPE osif_pci_read_config_byte(OSIF_PCIDEV pcidev, INT32 offs, UINT8 *ptr); extern INT32 OSIF_CALLTYPE osif_pci_read_config_word(OSIF_PCIDEV pcidev, INT32 offs, UINT16 *ptr); extern INT32 OSIF_CALLTYPE osif_pci_read_config_long(OSIF_PCIDEV pcidev, INT32 offs, UINT32 *ptr); extern INT32 OSIF_CALLTYPE osif_pci_write_config_byte(OSIF_PCIDEV pcidev, INT32 offs, UINT8 val); extern INT32 OSIF_CALLTYPE osif_pci_write_config_word(OSIF_PCIDEV pcidev, INT32 offs, UINT16 val); extern INT32 OSIF_CALLTYPE osif_pci_write_config_long(OSIF_PCIDEV pcidev, INT32 offs, UINT32 val); extern INT32 OSIF_CALLTYPE osif_load_from_file( UINT8 *destaddr, UINT8 *filename ); extern VOID OSIF_CALLTYPE osif_ser_out(CHAR8 *str); #define osif_div64_32(n, base) _osif_div64_32_(&(n), (base)) extern UINT32 OSIF_CALLTYPE _osif_div64_32_(UINT64 *n, UINT32 base); /* * If we get a serial it is assumed that it has the format CCNNNNNN where * C is a character from 'A'to 'P' and N is a number from '0' to '9' * This is converted into an 32-bit integer with bit 31-28 as alphabetical * offset to 'A' of the first char in serial, bit 27-24 as alphabetical * offset to 'A' of the second char in serial and the remaining 24 bits * as serial. So we have an effective range from AA000000 to PPFFFFFF. */ extern INT32 OSIF_CALLTYPE osif_make_ntcan_serial(const CHAR8 *pszSerial, UINT32 *pulSerial); #ifndef OSIF_PCI_OFFSET # define OSIF_PCI_OFFSET 0 #endif /* * If OSIF_TICK_FREQ is not defined here, UINT64 osif_tick_frequency() * must be implemented in osif.c * Here we define the frequency to 1MHz in order to work with * gettimeofday() */ #if defined(HOST_DRIVER) || defined(OSIF_ARCH_ARM) # define OSIF_TICK_FREQ 1000000LL #endif #define OSIF_READB(base, reg) (*(volatile UINT8* )((base)+(reg))) #define OSIF_WRITEB(base, reg, data) (*(volatile UINT8* )((base)+(reg))) = (data) #define OSIF_KERNEL #endif /* __KERNEL__ */ #define OSIF_ERRNO_BASE 0x00000100 /* base for esd-codes */ #endif
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/dkms.conf
# Autogenerated dkms.conf file for pcie402 PACKAGE_NAME="esdcan-pcie402-linux-2.6.x-x86_64" PACKAGE_VERSION="3.10.4" BUILT_MODULE_NAME[0]="esdcan-pcie402" BUILD_EXCLUSIVE_ARCH="x86_64" BUILD_MODULE_LOCATION[0]="." # DEST_MODULE_LOCATION will be overridden to a distribution # specific installation path in most cases. DEST_MODULE_LOCATION[0]="/kernel/drivers/esdcan" AUTOINSTALL="yes"
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/esdaccrc.h
/* -*- linux-c -*- * FILE NAME boardrc.h * copyright 2013-2014 by esd electronic system design gmbh * * BRIEF MODULE DESCRIPTION * Common "boardrc ressources" for all esdACC boards * * * Author: Andreas Block * andreas.block@esd-electronics.com * * history: * $Log$ * Revision 1.16 2015/10/22 08:49:41 oliver * - Definition of data structures to support a message queue based communication mechanism * between USB driver callback (DPC) and the CAN driver backend which is no longer limited * to a shared memory region with just 256 entries. * Fixes issue #2594 (http://mantis.esd/mantis/view.php?id=2594) * * Revision 1.15 2015/07/28 12:46:06 hauke * Renamed bm busload feature to bm statistic. * * Revision 1.14 2015/05/29 12:26:07 michael * LYNXOS support * * Revision 1.13 2015/05/08 16:39:03 stefanm * Rename CAN_TS and CAN_TS_FREQ to OSIF_TS and OSIF_TS_FREQ. * This should now also be used instead of CAN_TIMESTAMP / TIMESTAMP * in the whole esdcan driver tree. * * Revision 1.12 2014/12/09 11:09:42 hauke * Added new Features New Prescaler and Measured Busload * Added BM MSG for Measured Busload (not completed) * * Revision 1.11 2014/06/11 14:18:25 andreas * Change to compile for Solaris on Ultra601 * * Revision 1.10 2014/05/19 10:26:28 andreas * Renamed register mask defines to have a more unique naming throughout esdACC sources * Added CAN-FD busmaster message structure * Small fix to RX/TX_DONE message * * Revision 1.9 2014/03/24 09:26:38 stefanm * Corrected comment together with Andreas. * * Revision 1.8 2014/01/27 15:26:23 andreas * Added ledXor register in overview module * Added masks to decode ID and DLC in RX/TX messages * * Revision 1.7 2013/10/24 15:47:46 andreas * Added BOARD_TIMER_LOCK()/UNLOCK() macros * Fixed structure for busmaster and non-busmaster compilations * (struct in busmaster version had redundant members) * * Revision 1.6 2013/09/10 17:15:50 andreas * Renamed busmaster message "error" into "error warn" * * Revision 1.5 2013/08/27 13:16:53 andreas * Added msiAddrOffs register * * Revision 1.4 2013/08/14 13:40:41 andreas * Feature flag states were printed regardless of verbose level * * Revision 1.3 2013/08/14 09:33:50 andreas * Added macros for version and info register * Added bitmasks for feature flag decoding * * Revision 1.2 2013/08/01 12:33:57 andreas * Added MSI data register for MSI generation in overview structure * * Revision 1.1 2013/07/15 11:55:53 andreas * Header to be shared between different esdacc busmaster implementations * * */ /************************************************************************ * * Copyright (c) 2013 - 2013 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd.eu * Germany sales@esd.eu * *************************************************************************/ /*! \file esdaccrc.h \brief Common esdACC board ressources This file contains common esdACC constants and types for board specific layer. */ #ifndef __ESDACCRC_H__ #define __ESDACCRC_H__ /* * NOTE: * This header needs some defines from boardrc.h, BEFORE being included! */ #include <osif.h> /* * Default level for printing decoded strappings and feature flags on driver startup */ #define ESDACC_ZONE_FEATURES OSIF_ZONE_USR_RES3 #if !defined(__sun) && !defined(__LYNXOS) #define FLAG_PRINT_STATE(features, mask) (((features) & (mask)) ? OSIF_DPRINT((ESDACC_ZONE_FEATURES, "+")) : OSIF_DPRINT((ESDACC_ZONE_FEATURES, "-"))) #else #define FLAG_PRINT_STATE(features, mask) \ do { \ if ((features) & (mask)) { \ OSIF_DPRINT((ESDACC_ZONE_FEATURES, "+")); \ } else { \ OSIF_DPRINT((ESDACC_ZONE_FEATURES, "-")); \ } \ } while(0) #endif /* * Defines to be used with overview registers */ #define REG_OV_VERSION_MINOR_GET(reg) (UINT8)((reg) & 0x000000FF) #define REG_OV_VERSION_MAJOR_GET(reg) (UINT8)(((reg) & 0x0000FF00) >> 8) #define REG_OV_VERSION_FEATURES_GET(reg) (UINT16)(((reg) & 0xFFFF0000) >> 16) #define FEATURE_IDX_ACCEPTANCE_FILTER 0 #define FEATURE_IDX_OVERLOAD_FRAMES 1 #define FEATURE_IDX_TRIPLE_SAMPLING 2 #define FEATURE_IDX_ALC 3 #define FEATURE_IDX_TIMESTAMPED_TX 4 #define FEATURE_IDX_LED1_CONTROL 5 #define FEATURE_IDX_LED2_CONTROL 6 #define FEATURE_IDX_BUSMASTER 7 #define FEATURE_IDX_ERROR_INJECTION 8 #define FEATURE_IDX_BROKEN_FRAMES 9 #define FEATURE_IDX_EXTERNAL_TS 10 #define FEATURE_IDX_CAN_FD 11 #define FEATURE_IDX_NEW_PRESCALER 12 #define FEATURE_IDX_STATISTIC 13 #define FEATURE_IDX_EXTEND 15 /* for extending feature mask (look at another register if set) */ #define FEATURE_MASK_ACCEPTANCE_FILTER (1 << FEATURE_IDX_ACCEPTANCE_FILTER) #define FEATURE_MASK_OVERLOAD_FRAMES (1 << FEATURE_IDX_OVERLOAD_FRAMES) #define FEATURE_MASK_TRIPLE_SAMPLING (1 << FEATURE_IDX_TRIPLE_SAMPLING) #define FEATURE_MASK_ALC (1 << FEATURE_IDX_ALC) #define FEATURE_MASK_TIMESTAMPED_TX (1 << FEATURE_IDX_TIMESTAMPED_TX) #define FEATURE_MASK_LED1_CONTROL (1 << FEATURE_IDX_LED1_CONTROL) #define FEATURE_MASK_LED2_CONTROL (1 << FEATURE_IDX_LED2_CONTROL) #define FEATURE_MASK_BUSMASTER (1 << FEATURE_IDX_BUSMASTER) #define FEATURE_MASK_ERROR_INJECTION (1 << FEATURE_IDX_ERROR_INJECTION) #define FEATURE_MASK_BROKEN_FRAMES (1 << FEATURE_IDX_BROKEN_FRAMES) #define FEATURE_MASK_EXTERNAL_TS (1 << FEATURE_IDX_EXTERNAL_TS) #define FEATURE_MASK_CAN_FD (1 << FEATURE_IDX_CAN_FD) #define FEATURE_MASK_NEW_PRESCALER (1 << FEATURE_IDX_NEW_PRESCALER) #define FEATURE_MASK_STATISTIC (1 << FEATURE_IDX_STATISTIC) #define FEATURE_MASK_EXTEND (1 << FEATURE_IDX_EXTEND) #define REG_OV_INFO_NUM_CAN_GET(reg) (UINT8)((reg) & 0x000000FF) #define REG_OV_INFO_NUM_ACTIVE_GET(reg) (UINT8)(((reg) & 0x0000FF00) >> 8) #define REG_OV_INFO_STRAPPINGS_GET(reg) (UINT16)(((reg) & 0xFFFF0000) >> 16) /* Defines for strapping bits and masks are to be found in boardrc.h */ /* Use in overview module's mode register */ /* NOTE: Not all bits need to be present in an FPGA implementation */ #define REG_OV_MODE_MASK_ENDIAN_LITTLE 0x00000001 #define REG_OV_MODE_MASK_BM_ENABLE 0x00000002 #define REG_OV_MODE_MASK_MODE_LED 0x00000004 /* #define REG_OV_MODE_MASK_RESERVED 0x00000008 */ #define REG_OV_MODE_MASK_TIMER 0x00000070 #define REG_OV_MODE_MASK_TIMER_ENABLE 0x00000010 #define REG_OV_MODE_MASK_TIMER_ONE_SHOT 0x00000020 #define REG_OV_MODE_MASK_TIMER_ABSOLUTE 0x00000040 #define REG_OV_MODE_MASK_TS_SRC 0x00000180 /* always set both bits at same time */ #define REG_OV_MODE_MASK_REARIO 0x00000200 #define REG_OV_MODE_MASK_REARIO_TEST 0x00000400 #define REG_OV_MODE_MASK_I2C_ENABLE 0x00000800 #define REG_OV_MODE_MASK_PXI_ST 0x00003000 #define REG_OV_MODE_MASK_PXI_ST_EN 0x00001000 /* Star trigger enable */ #define REG_OV_MODE_MASK_PXI_ST_INV 0x00002000 /* Star trigger invert */ #define REG_OV_MODE_MASK_MSI_ENABLE 0x00004000 #define REG_OV_MODE_MASK_NEW_PRESCALER 0x00008000 #define REG_OV_MODE_MASK_BM_STATISTIC 0x00010000 #define REG_OV_MODE_MASK_IRQ_CNT_DISABLE 0x00020000 /* #define REG_OV_MODE_MASK_RESERVED 0x7FFE0000 */ #define REG_OV_MODE_MASK_FPGA_RESET 0x80000000 #define REG_OV_MODE_TS_SRC_INTERN 0x00000000 #define REG_OV_MODE_TS_SRC_PXI 0x00000080 #define REG_OV_MODE_TS_SRC_IRIGB 0x00000100 /* equals IRIG-B enable */ #define REG_OV_MODE_TS_SRC_RESV 0x00000180 /* Use in overview module's bmIrqMask register */ #define BM_IRQ_MASK_ALL 0xAAAAAAAA #define BM_IRQ_MASK 0x00000002 #define BM_IRQ_UNMASK 0x00000001 #define ESDACCRC_OVERVIEW_PARTITION_1 \ /* System overview */ \ volatile UINT32 probe; /* 0x0000 */ \ volatile UINT32 version; /* 0x0004 */ \ volatile UINT32 info; /* 0x0008 */ \ volatile UINT32 freqCore; /* 0x000C */ \ volatile UINT32 freqTsLow; /* 0x0010 */ \ volatile UINT32 freqTsHigh; /* 0x0014 */ \ volatile UINT32 irqStatAll; /* 0x0018 */ \ volatile UINT32 tsCurrentLow; /* 0x001C */ \ volatile UINT32 tsCurrentHigh; /* 0x0020 */ \ volatile UINT32 irigBScratch; /* 0x0024 */ \ volatile UINT32 irqStatLocal; /* 0x0028 */ \ volatile UINT32 mode; /* 0x002C */ \ volatile UINT32 timerCompareLow; /* 0x0030 */ \ volatile UINT32 timerCompareHigh; /* 0x0034 */ \ volatile UINT32 timerCurrentLow; /* 0x0038 */ \ volatile UINT32 timerCurrentHigh; /* 0x003C */ \ volatile UINT32 timerCalib; /* 0x0040 */ \ volatile UINT32 ledXor; /* 0x0044 */ \ UINT32 p1_reserved1[10]; /* 0x0048-0x006C */ \ volatile UINT32 bmIrqCnt; /* 0x0070 */ \ volatile UINT32 bmIrqMask; /* 0x0074 */ \ UINT32 p1_reserved2[2]; /* 0x0078-0x007C */ \ volatile UINT32 msiData; /* 0x0080 */ \ volatile UINT32 msiAddrOffs; /* 0x0084 */ \ UINT32 p1_reserved3[478] /* Pad to end of 2kB or 512 longwords per "partition"/"sub unit" */ /* * Messages used in busmaster FIFOs. * Data is already swapped correctly by FPGA to host endianess */ #define BM_MSG_FIFO_NUM_MSGS 256 /* Size in messages */ #define BM_MSG_ID_RXTX_DONE 0x01 #define BM_MSG_ID_TX_ABORT 0x02 #define BM_MSG_ID_OVERRUN 0x03 #define BM_MSG_ID_BUS_ERROR 0x04 #define BM_MSG_ID_ERROR_PASSIVE 0x05 #define BM_MSG_ID_ERROR_WARN 0x06 #define BM_MSG_ID_TIMESLICE 0x07 #define BM_MSG_ID_HW_TIMER 0x08 #define BM_MSG_ID_HOTPLUG 0x09 #define BM_MSG_ID_CAN_FD_DATA_0 0x0A #define BM_MSG_ID_CAN_FD_DATA_1 0x0B #define BM_MSG_ID_STATISTIC 0x0C typedef struct _BM_MSG_CAN_ANY BM_MSG_CAN_ANY; typedef struct _BM_MSG_CAN_RXTX_DONE BM_MSG_CAN_RXTX_DONE; typedef struct _BM_MSG_CAN_FD_DATA BM_MSG_CAN_FD_DATA; typedef struct _BM_MSG_CAN_TX_ABORT BM_MSG_CAN_TX_ABORT; typedef struct _BM_MSG_CAN_OVERRUN BM_MSG_CAN_OVERRUN; typedef struct _BM_MSG_CAN_BUS_ERROR BM_MSG_CAN_BUS_ERROR; typedef struct _BM_MSG_CAN_ERROR_PASSIVE BM_MSG_CAN_ERROR_PASSIVE; typedef struct _BM_MSG_CAN_ERROR_WARN BM_MSG_CAN_ERROR_WARN; typedef struct _BM_MSG_CAN_TIMESLICE BM_MSG_CAN_TIMESLICE; typedef struct _BM_MSG_CAN_STATISTIC BM_MSG_CAN_STATISTIC; typedef struct _BM_MSG_OV_HW_TIMER BM_MSG_OV_HW_TIMER; typedef struct _BM_MSG_OV_HOTPLUG BM_MSG_OV_HOTPLUG; typedef struct _BM_MSG_STATISTIC BM_MSG_STATISTIC; typedef union _BM_MSG BM_MSG; typedef UINT32 BM_MSG_PLAIN[8]; typedef struct _BM_STUFF BM_STUFF; typedef struct _BM_USB_STUFF BM_USB_STUFF; struct _BM_MSG_CAN_RXTX_DONE { UINT8 msgId; UINT8 txFifoLevel; UINT8 reserved1[2]; UINT8 txTsFifoLevel; UINT8 reserved2[3]; UINT32 id; union { UINT32 ui; /* Don't use longword access, as dlc is NOT swapped to host endianess in FPGA */ struct { UINT8 len; UINT8 reserved0; UINT8 bits; UINT8 state; } rxtx; struct { UINT8 len; UINT8 msg_lost; /* TODO */ UINT8 bits; UINT8 state; } rx; struct { UINT8 len; UINT8 txFifoIdx; UINT8 bits; UINT8 state; } tx; /* BL TODO: since byte four is used for state bits, we are missing room for an ECC byte */ } dlc; UINT8 data[8]; OSIF_TS timestamp; }; #define RXTX_LEN_MASK_LENGTH 0x0F #define RXTX_LEN_BIT_RTR 0x10 #define RXTX_LEN_BIT_TX 0x20 /* TX Done */ #define RXTX_LEN_BIT_SR 0x40 /* Self reception */ #define RXTX_LEN_BIT_TXFIFO 0x80 /* Frame was transmitted through TX FIFO (0) or TX TS FIFO (1) */ #define RXTX_STATE_RESERVED 0x3F #define RXTX_STATE_CAN_FD 0x40 #define RXTX_STATE_OVERRUN 0x80 #define RXTX_ID_MASK_ID 0x2FFFFFFF /* Mask for part of ID passed through to NTCAN */ #define RXTX_ID_BIT_20B 0x20000000 struct _BM_MSG_CAN_FD_DATA { UINT8 msgId; UINT8 reserved1[3]; union { UINT8 ui8[28]; UINT32 ui32[7]; } d; }; struct _BM_MSG_CAN_TX_ABORT { UINT8 msgId; UINT8 txFifoLevel; UINT16 abortMask; UINT8 txTsFifoLevel; UINT8 reserved2[1]; UINT16 abortMaskTxTs; OSIF_TS ts; UINT32 reserved3[4]; }; struct _BM_MSG_CAN_OVERRUN { UINT8 msgId; UINT8 txFifoLevel; UINT8 lostCnt; /* TODO */ UINT8 reserved1; UINT8 txTsFifoLevel; UINT8 reserved2[3]; OSIF_TS ts; UINT32 reserved3[4]; }; struct _BM_MSG_CAN_BUS_ERROR { UINT8 msgId; UINT8 txFifoLevel; UINT8 ecc; UINT8 reserved1; UINT8 txTsFifoLevel; UINT8 reserved2[3]; OSIF_TS ts; UINT32 regStatus; UINT32 regBtr; UINT32 reserved3[2]; }; struct _BM_MSG_CAN_ERROR_PASSIVE { UINT8 msgId; UINT8 txFifoLevel; UINT8 reserved1[2]; UINT8 txTsFifoLevel; UINT8 reserved2[3]; OSIF_TS ts; UINT32 regStatus; UINT32 reserved3[3]; }; struct _BM_MSG_CAN_ERROR_WARN { UINT8 msgId; UINT8 txFifoLevel; UINT8 reserved1[2]; UINT8 txTsFifoLevel; UINT8 reserved2[3]; OSIF_TS ts; UINT32 regStatus; UINT32 reserved3[3]; }; struct _BM_MSG_CAN_TIMESLICE { UINT8 msgId; UINT8 txFifoLevel; UINT8 reserved1[2]; UINT8 txTsFifoLevel; UINT8 reserved2[3]; OSIF_TS ts; UINT32 reserved3[4]; }; struct _BM_MSG_CAN_STATISTIC { UINT8 msgId; UINT8 txFifoLevel; UINT8 reserved1[2]; UINT8 txTsFifoLevel; UINT8 reserved2[3]; OSIF_TS ts; UINT32 regStatus; UINT32 idleCnt; UINT32 reserved3[2]; }; struct _BM_MSG_CAN_ANY { UINT8 msgId; UINT8 txFifoLevel; UINT8 reserved1[2]; UINT8 txTsFifoLevel; UINT8 reserved2[3]; OSIF_TS ts; /* any except RX/TX done */ UINT32 reserved3[4]; }; struct _BM_MSG_OV_HW_TIMER { UINT8 msgId; UINT8 reserved1[3]; UINT32 reserved2[1]; OSIF_TS timer; UINT32 reserved3[4]; }; struct _BM_MSG_OV_HOTPLUG { UINT8 msgId; UINT8 reserved1[3]; UINT32 reserved2[7]; }; union _BM_MSG { BM_MSG_PLAIN plain; BM_MSG_CAN_ANY canAny; BM_MSG_CAN_RXTX_DONE rxtxDone; BM_MSG_CAN_FD_DATA canFdData; BM_MSG_CAN_TX_ABORT txAbort; BM_MSG_CAN_OVERRUN overrun; BM_MSG_CAN_BUS_ERROR busError; BM_MSG_CAN_ERROR_PASSIVE errorPassive; BM_MSG_CAN_ERROR_WARN errorWarn; BM_MSG_CAN_TIMESLICE timeslice; BM_MSG_CAN_STATISTIC statistic; BM_MSG_OV_HW_TIMER hwTimer; BM_MSG_OV_HOTPLUG hotplug; }; typedef BM_MSG BM_IRQ_MSG_FIFO[BM_MSG_FIFO_NUM_MSGS]; #if defined(BOARD_USB) struct _BM_USB_STUFF { /* USB related stuff */ LNK lnk; /* Linked list of pending BM messages */ OSIF_DPC dpc; /* DPC of backends */ UINT32 msg_lost; /* Message lost counter */ }; typedef struct _BM_USB_MSG { LNK lnk; BM_MSG bm_msg; } BM_USB_MSG; #else struct _BM_STUFF { /* busmaster stuff */ volatile UINT32 *pBmIrqCntNew; /* IRQ counter delivered by FPGA (above busmaster FIFOs) */ UINT32 bmIrqCntLocal; /* IRQ counter as far as dpc already processed the bm messages */ UINT32 bmFifoTail; /* FIFO tail pointer to next message, which needs to be processed */ BM_IRQ_MSG_FIFO *pBmFifo; OSIF_DPC dpc; /* only used for CAN cores */ }; #endif #ifndef ESDACC_USE_NO_HW_TIMER /* * HW Timer stuff */ #ifdef BOARD_BUSMASTER #define BOARD_TIMER_LOCK(pHwTimer) OSIF_MUTEX_LOCK(&(pHwTimer)->lockTimer) #define BOARD_TIMER_UNLOCK(pHwTimer) OSIF_MUTEX_UNLOCK(&(pHwTimer)->lockTimer) #else #define BOARD_TIMER_LOCK(pHwTimer) OSIF_IRQ_MUTEX_LOCK(&(pHwTimer)->lockTimerIrq) #define BOARD_TIMER_UNLOCK(pHwTimer) OSIF_IRQ_MUTEX_UNLOCK(&(pHwTimer)->lockTimerIrq) #endif /* ifdef BOARD_BUSMASTER */ typedef struct _CIF_TIMER_BASE CIF_TIMER_BASE; typedef struct _CIF_TIMER CIF_TIMER; struct _CIF_TIMER_BASE { LNK lnkTimer; LNK lnkTimerActive; #ifdef BOARD_BUSMASTER OSIF_MUTEX lockTimer; #else OSIF_IRQ_MUTEX lockTimerIrq; #endif /* ifdef BOARD_BUSMASTER */ OSIF_IRQ_MUTEX lockTimerAccess; UINT32 idxCalib; UINT32 cntCalib; /* To be subtracted from lower 32-Bits of every timer's duration (system latency) */ OSIF_TIMER timerCalib; }; struct _CIF_TIMER { LNK lnkTimer; LNK lnkTimerActive; OSIF_TS expires; VOID *pCrd; #ifndef BOARD_BUSMASTER OSIF_DPC dpc; #endif /* ifndef BOARD_BUSMASTER */ VOID (OSIF_CALLTYPE *func)(VOID *); VOID *arg; volatile UINT32 flagRunning; }; #else typedef VOID *CIF_TIMER_BASE; #endif /* ifndef ESDACC_USE_NO_HW_TIMER */ #endif /* #ifndef __ESDACCRC_H__ */
0
apollo_public_repos/apollo-contrib/esd
apollo_public_repos/apollo-contrib/esd/src/osif.c
/* -*- esdcan-c -*- * FILE NAME osif.c * * BRIEF MODULE DESCRIPTION * OSIF implementation for Linux * * * history: * * $Log$ * Revision 1.133 2015/04/30 15:21:36 hauke * Added OSIF_DIV64_SFT_FIXUP in osif_attach(). * * Revision 1.132 2015/01/09 14:36:26 stefanm * Use vprintk() on kernels > 2.6.18 to avoid formatting the message * myself by OSIF_VSNPRINTF(). * Fixed missing format string with printk(). * * Revision 1.131 2014/10/31 13:12:18 manuel * Improved including of linux/sched/rt.h - needed for newer kernels, where MAX_USER_RT_PRIO isn't found in linux/sched.h any more. * * Revision 1.130 2014/08/12 06:01:04 matthias * need linux/sched/rt.h for RT_MAX_USER_PRIO (kernel 3.12+) * * Revision 1.129 2014/07/07 14:36:21 matthias * check fo CONFIG_OF_DEVICE or (!) CONFIG_OF_FLATTREE * * Revision 1.128 2014/07/04 10:02:54 hauke * Removed <canio.h> which is included in <osif.h> * * Revision 1.127 2014/06/16 12:23:12 manuel * Fixed osif_dprint * * Revision 1.126 2014/05/20 12:40:06 andreas * Fixed a bunch of violations of esd's coding style * * Revision 1.125 2014/02/27 16:51:46 stefanm * osif_pci_alloc_consisten() will now request only 32-bit DMA addresses * from the kernel and check for usable addresses. * * Revision 1.124 2014/01/16 13:40:37 frank * removed "#include spi.h". No longer needed ... * * Revision 1.123 2013/12/30 16:51:53 frank * Made adaptions needed for directly accessing the SPI controller via esdcan-of-spi-connector and esd-omap2-mcspi * * Revision 1.122 2013/12/09 17:04:52 manuel * From now on all (not any) debug bits of a dprint must be set in verbose flags * * Revision 1.121 2013/11/20 14:14:37 frank * Fixed quandary with spi_sync() [...] * * Revision 1.120 2013/11/19 15:32:35 frank * Added SPI support (BOARD_SPI) * * Revision 1.119 2013/09/16 12:56:12 matthias * use <read|write><b|w|l> for ARM * * with kernel 3.8.13 on arm IO_SPACE_LIMIT is 0. so all * addresses passed to in/outb/w/l are truncated to 0. * * Perhaps this will work on other architectures, too. * * Revision 1.118 2013/08/19 14:20:32 manuel * Added workaround to use CONFIG_DEBUG_MUTEXES * Fix for kernel 3.4 and newer: do not call daemonize * * Revision 1.117 2013/08/08 13:09:27 matthias * use software timestamps on ARM * * Revision 1.116 2013/07/16 14:16:36 andreas * TODO reminder comment added * * Revision 1.115 2013/04/26 14:27:26 andreas * Added osif_div64_sft * * Revision 1.114 2013/01/18 16:56:46 andreas * Changed OSIF_TIMER implementation * - added CAN_NODE parameter to OSIF_TIMER_CREATE * - OSIF_TIMER structure is defined in osif.h and in osifi.h there's only a static extension OSIF_TIMER_SYS_PART * * Revision 1.113 2012/02/17 18:40:11 andreas * Fixed OSIF_CALLTYPE position * * Revision 1.112 2011/11/04 14:44:05 andreas * Small comment changes (AB -> BL) * * Revision 1.111 2011/11/01 15:27:41 andreas * Merged with preempt_rt branch * With OSIF_USE_PREEMPT_RT_IMPLEMENTATION the new implementation is used for * all kernels > 2.6.20 * Some cleanup * * Revision 1.110 2011/09/06 17:20:36 manuel * Fixed rcsid (for newer gcc) * * Revision 1.109 2011/04/05 11:34:32 andreas * Small change to use of OSIF_CALLTYPE on function pointers * Changed to make use of new CHAR8 datatype * Deleted loads of empty lines * * Revision 1.108 2010/12/15 15:45:35 manuel * Use spin_lock_init to initialize spinlocks (to allow lockdep checker to work) * Fix SCHED_FIFO code (though it remains disabled by default) * * Revision 1.107 2010/06/16 13:20:47 manuel * Added linux/sched.h include unconditionally. * Needed for kernel 2.6.33 but shouldn't harm for older kernels. * * Revision 1.106 2010/06/01 09:56:53 tkoerper * - including linux/sched.h with kernel >= 2.6.34 * * Revision 1.105 2010/04/16 17:03:58 andreas * Added osif_callbacks * Fixed or at least unified OSIF_CALLTYPE declarations on dpc and timer create * * Revision 1.104 2010/03/09 13:32:23 matthias * include asm/time.h when using tb_ticks_per_sec for osif_tick_frequency * * Revision 1.103 2010/03/09 10:35:19 matthias * Cleanup osif_tick_frequency for powerpc * - use tb_ticks_per_sec when possible * * Revision 1.102 2010/03/09 10:14:23 matthias * Beginning with 2.6.33 linux/autoconf.h moved to generated/autoconf.h. Also there is no need to include it. The kernel's build system passes it via -include option to gcc. * * Revision 1.101 2009/07/31 14:14:05 andreas * Untabbified * * Revision 1.100 2009/07/03 10:42:49 tkoerper * - Added #ifdefs for arm * * Revision 1.99 2009/04/01 14:33:03 andreas * Quickfix for CBX-CPU5200, need to rework function for timer tick frequency * * Revision 1.98 2009/02/25 16:16:54 andreas * Removed osif_sema_-calls * Removed osif_busy_mutex_-calls * * Revision 1.97 2009/02/11 16:38:46 manuel * Changed type of irqsave flags from UINT32 to UINTPTR * * Revision 1.96 2009/01/29 10:11:05 andreas * Removed osif_in_irq_lock()/-unlock() functions * * Revision 1.95 2008/12/10 10:54:19 manuel * Now osif_io_xxx are only implemented here if OSIF_USE_IO_FUNCTIONS is defined (otherwise they are in the header). * * Revision 1.94 2008/11/18 11:38:21 matthias * include linux/semaphore.h instead of asm/semaphore.h beginning with kernel 2.6.27 * * Revision 1.93 2008/08/27 14:30:34 andreas * Added BOARD_pmc440 * * Revision 1.92 2008/06/03 16:32:25 manuel * Added debug output to osif_pci_malloc * Fixed osif_in_irq_mutex_lock and _unlock (hopefully fixing all hangings) * Changed osif_dpc_thread to use down_interruptible instead of down * * Revision 1.91 2008/03/20 11:34:32 andreas * Moved rt-prio for backend into 2.4 branch. * * Revision 1.90 2008/03/20 10:15:44 andreas * Changed optimization osif_timer_set(), the old optimization * didn't work for different kernel versions (2.4.19-x86 (to name one)) * * Revision 1.89 2008/02/15 16:14:21 michael * OSIF dpc's now running at rt prio 98. * * Revision 1.88 2008/02/12 12:51:55 andreas * Including linux/fs.h for kernels > 2.6.22 * * Revision 1.87 2008/01/21 14:11:41 michael * Osif threads now scheduled in fifo mode at prio max. * * Revision 1.86 2007/12/11 08:34:46 andreas * Removed osif_load_from_file (doesn't compile under Linux 2.6.23 anymore) * * Revision 1.85 2007/06/05 08:57:42 andreas * Add osif_usleep() * Some cleanup * * Revision 1.84 2007/05/24 12:34:54 michael * osif_div64_32 renamed to _osif_div64_32_ * * Revision 1.83 2007/05/07 13:53:24 andreas * Added #ifdefs to disable "config space access functions", * if no PCI driver is compiled * * Revision 1.82 2007/01/24 07:39:53 andreas * Changed #ifdef's around osif_tick_frequency() in order to release PPC host * driver for PMC331 * * Revision 1.81 2006/12/22 09:57:36 andreas * Fixed for kernels 2.6.19 * Exchanged include order of version.h and config.h/autoconf.h * Including autoconf.h instead of config.h for kernels >= 2.6.19 * * Revision 1.80 2006/10/12 13:31:55 manuel * Fixed compiler warning * * Revision 1.79 2006/10/11 10:12:17 andreas * Fixed compilation problem with SuSE > 10.0 * * Revision 1.78 2006/08/17 13:26:59 michael * Rebirth of OSIF_ errorcodes * * Revision 1.77 2006/08/03 07:46:19 andreas * Removed old debug code, which was #if 0 for quite a while, now * * Revision 1.76 2006/06/29 15:18:40 andreas * CANIO_EINTR got replaced by OSIF_OPERATION_ABORTED * * Revision 1.75 2006/06/29 14:45:06 andreas * Exchanged error codes from osif.h (OSIF_xxx) with error codes from canio.h (CANIO_xxx) * * Revision 1.74 2006/06/27 13:13:44 andreas * Exchanged OSIF_errors with CANIO_errors * * Revision 1.73 2006/06/27 09:52:03 andreas * TODO comment added (regarding timestamps on baudrate change events) * * Revision 1.72 2006/04/28 07:54:27 andreas * osif_ticks() must not be used with mecp52 (or generally mpc5200 based boards) * * Revision 1.71 2006/02/14 09:18:37 matthias * -board info structure has change to 2.6 kernels * -check if _MSC_VER is defined be fore using it * * Revision 1.70 2005/12/06 13:24:10 andreas * No functional changes, only cleanup, while looking through the * code in search for an error * * Revision 1.69 2005/10/06 07:43:23 matthias * added osif_make_ntcan_serial * * Revision 1.68 2005/08/30 12:25:09 andreas * Fixed osif_memcmp() !!! * This one was really nice (great copy'n'paste work), comparison was done, * result was piped to NIL. * Instead the result was always ok :( * * Revision 1.67 2005/07/27 15:50:14 andreas * Corrected calltype of func-parameter of osif_timer_create * * Revision 1.66 2005/04/20 13:04:16 andreas * Changes for 64-Bit Linux (exchanged C-standard types with OSIF-types, use of UINTPTR) * Added osif_ser_out() * * Revision 1.65 2004/11/15 17:35:54 matthias * fixed frequency of PPC750 performance counter frequency * * Revision 1.64 2004/11/15 17:25:14 matthias * added temporary osif_tick_frequency() for cpci750 * * Revision 1.63 2004/11/08 11:13:46 michael * Missing OSIF_CALLTYPE added * * Revision 1.62 2004/10/29 14:56:05 matthias * -added osif_div64_64 * -fixed osif_timer_set rounding * * Revision 1.61 2004/10/11 09:23:44 andreas * Added io-functions (for kernel 2.6) * Added some debug zones * Sorted history * * 13.05.04 - corrected SMP-bug in OSIF_SLEEP for kernel < 2.6 * new OSIF_SLEEP branch for kernel > 2.6.5 * timer functions needed OSIF_CALLTYPE, too * changed dpc_thread kernel2.6-style (daemonize()...) ab * 11.05.04 - Changed OSIF_EXTERN into OSIF_CALLTYPE * Added rcsid ab * 07.05.04 - Removed gcc3-warning (LVALUE-casts) * Including linux/version.h * Changed prototype of osif_irq_attach a bit to cope * with the needs of kernel 2.6 ab * 06.05.04 - Include of modversions changed for kernel 2.6.x * Added OSIF_EXTERN to nearly all functions (problem * with release-archive for kernel 2.6.x) ab * 01.12.03 - OSIF doesn't use OSIF-macros for mutex/sema anymore mt * 26.11.03 - Corrected OSIF_VSNPRINTF for kernel < 2.4.0 * Removed osif_pci_malloc-warning for non-pci405-cards * Exchanged init_MUTEX with sema_init() ab * 13.11.03 - Corrected debug-info in mutexes ab * 13.11.03 - OSIF_MUTEX do not busy wait, Old OSIF_MUTEX now * OSIF_BUSY_MUTEX mt * 12.11.03 - OSIF_TIMER as DPC mt * 05.11.03 - Saving of IRQ-flags was wrong! Removed again! ab * 29.10.03 - changed IRQ-spinlocks (IRQ-flags get saved, now) ab * 27.10.03 - New output function osif_dprint (with verbose mask) ab * 18.09.03 - Only one thread for all DPC's mt * 02.01.03 - added SA_INTERRUPT flag for atomic interrupt handler mf * 24.05.02 - first version mf * */ /************************************************************************ * * Copyright (c) 1996 - 2015 by electronic system design gmbh * * This software is copyrighted by and is the sole property of * esd gmbh. All rights, title, ownership, or other interests * in the software remain the property of esd gmbh. This * software may only be used in accordance with the corresponding * license agreement. Any unauthorized use, duplication, transmission, * distribution, or disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of esd gmbh. * * esd gmbh, reserves the right to modify this software without notice. * * electronic system design gmbh Tel. +49-511-37298-0 * Vahrenwalder Str 207 Fax. +49-511-37298-68 * 30165 Hannover http://www.esd.eu * Germany support@esd.eu * *************************************************************************/ /*! \file osif.c \brief OSIF implementation This file contains the implementation of all osif functions. */ /*---------------------------------------------------------------------------*/ /* INCLUDES */ /*---------------------------------------------------------------------------*/ #include <linux/version.h> #if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32)) # if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,19)) # include <linux/autoconf.h> # else # include <linux/config.h> # endif #endif #ifdef DISTR_SUSE # undef CONFIG_MODVERSIONS #endif #ifdef CONFIG_MODVERSIONS # if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # include <config/modversions.h> # else # include <linux/modversions.h> # endif # ifndef MODVERSIONS # define MODVERSIONS # endif #endif #include <linux/kernel.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/init.h> #include <asm/uaccess.h> #include <asm/io.h> #include <linux/interrupt.h> #include <linux/time.h> #include <linux/pci.h> #include <linux/types.h> #include <linux/timer.h> #include <linux/delay.h> #ifdef LTT # include <linux/trace.h> #endif #include <linux/errno.h> #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # include <linux/interrupt.h> #endif #if ( (LINUX_VERSION_CODE < KERNEL_VERSION(2,4,8)) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)) ) # if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,22) # include <linux/fs.h> # endif /* needed for vsnprintf */ # include <asm/div64.h> # include <linux/ctype.h> #endif #ifdef BOARD_mcp2515 /* Unfortunately we don't have defined BOARD_SPI in osif.c, */ /* so we temporarily introduce an OSIF_BOARD_SPI define here ... */ # define OSIF_BOARD_SPI 1 #endif #include <linux/sched.h> #ifndef MAX_USER_RT_PRIO #include <linux/sched/rt.h> /* maybe it's hidden here now (newer kernels...) */ #endif #include <osif.h> #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION # include <linux/kthread.h> #endif /*---------------------------------------------------------------------------*/ /* DEFINES */ /*---------------------------------------------------------------------------*/ #ifdef ESDDBG # define OSIF_DEBUG /*!< enables debug output for osif functions */ #endif #ifdef OSIF_DEBUG # define OSIF_DBG(fmt) OSIF_DPRINT(fmt) /*!< Macro for debug prints */ #else # define OSIF_DBG(fmt) #endif #ifdef KBUILD_MODNAME # define K_DPC_NAME "k" KBUILD_MODNAME #else # define K_DPC_NAME "dpc thread" #endif /*---------------------------------------------------------------------------*/ /* TYPEDEFS */ /*---------------------------------------------------------------------------*/ #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION struct __OSIF_MUTEX { struct mutex lock; }; #ifdef CONFIG_DEBUG_MUTEXES #include <linux/atomic.h> #define OSIF_MAX_DEBUG_MUTEXES 128 static atomic_t osif_debug_mutexes_cnt; static struct lock_class_key osif_debug_mutexes_keys[OSIF_MAX_DEBUG_MUTEXES]; #endif #else struct __OSIF_MUTEX { struct semaphore sema; }; #endif /* #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION */ struct __OSIF_SPINLOCK { spinlock_t spinlock; UINTPTR flags; UINT32 magic; }; struct _OSIF_LINUX_TIMER { struct timer_list timer; OSIF_DPC dpc; }; struct __OSIF_PCI_PADDR { UINT32 addr32; dma_addr_t sys_dma_addr; }; static struct { OSIF_DPC first; spinlock_t spinlock; INT32 thread_running; INT32 destroy; #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION wait_queue_head_t wqDpcNotify; atomic_t trig; struct task_struct *tsk; #else struct semaphore sema_notify; struct semaphore sema_trigger; #endif } dpc_root; OSIF_CALLBACKS osif_callbacks = { osif_timer_create, osif_timer_destroy, osif_timer_set, osif_timer_get, }; #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) DECLARE_COMPLETION(dpcThreadCompletion); #endif /*---------------------------------------------------------------------------*/ /* DEFINITION OF LOCAL DATA */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /* DECLARATION OF LOCAL FUNCTIONS */ /*---------------------------------------------------------------------------*/ static INT32 osif_dpc_root_create(VOID); static INT32 osif_dpc_root_destroy(VOID); /*---------------------------------------------------------------------------*/ /* DEFINITION OF GLOBAL DATA */ /*---------------------------------------------------------------------------*/ extern UINT32 verbose; /* has to be declared in OS-level-sources (esdcan.c), should be set by module-parameter */ INT32 osif_div64_sft = 0; /* see extern declaration osif.h */ /*---------------------------------------------------------------------------*/ /* DEFINITION OF EXPORTED FUNCTIONS */ /*---------------------------------------------------------------------------*/ #if defined(OSIF_BOARD_SPI) int osif_spi_xfer(OSIF_SPIDEV *pDev, OSIF_SPIMSG *pMsg) { int ret; #if 0 { int i; printk("%s:l=%d in=", __FUNCTION__, pMsg->nBytes); for(i =0; i < pMsg->nBytes; i++) { printk("%02x ", pMsg->io[i]); } printk("\n"); } #endif ret = pDev->scdev->pdsd->sync_xfer(pDev->scdev, pMsg); if (ret) { osif_print("%s: spi transfer failed: ret=%d\n", __FUNCTION__, ret); return ret; } #if 0 { int i; printk("%s:l=%d out=", __FUNCTION__, pMsg->nBytes); for(i =0; i < pMsg->nBytes; i++) { printk("%02x ", pMsg->io[i]); } printk("\n"); } #endif return(OSIF_SUCCESS); } #endif /* OSIF_BOARD_SPI */ INT32 OSIF_CALLTYPE osif_attach() { INT32 result; OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); result = osif_dpc_root_create(); OSIF_DIV64_SFT_FIXUP(); OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return result; } INT32 OSIF_CALLTYPE osif_detach() { INT32 result; OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); result = osif_dpc_root_destroy(); OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return result; } /*! Allocate \a size bytes of memory. A pointer to the new allocated memory is returned through \a **p. */ #define OSIF_MEM_IS_NOTUSED 0x00000000 #define OSIF_MEM_IS_KMEM 0x11111111 #define OSIF_MEM_IS_VMEM 0x22222222 INT32 OSIF_CALLTYPE osif_malloc(UINT32 size, VOID **p) { VOID *ptr; OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter, size=%08x\n", OSIF_FUNCTION,size)); ptr = kmalloc(size + sizeof(UINT32), GFP_KERNEL); if (!ptr) { OSIF_DBG((OSIF_ZONE_OSIF, "%s: kmalloc for %d bytes failed, using vmalloc\n", OSIF_FUNCTION, size)); ptr = vmalloc(size + sizeof(UINT32)); if (!ptr) { *p = NULL; OSIF_DBG((OSIF_ZONE_OSIF, "%s: OSIF_MALLOC failed !!!!\n", OSIF_FUNCTION)); return OSIF_INSUFFICIENT_RESOURCES; } else { *(UINT32*)ptr = OSIF_MEM_IS_VMEM; } } else { *(UINT32*)ptr = OSIF_MEM_IS_KMEM; } *p = (VOID*)((UINT8*)ptr + sizeof(UINT32)); OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } /*! Free memory that has been allocated by osif_malloc. \a ptr points to the pointer returned by osif_malloc(). */ INT32 OSIF_CALLTYPE osif_free(VOID *ptr) { UINT32 *pFree = (UINT32*)((UINT8*)ptr - sizeof(UINT32)); if (ptr) { if (*pFree == OSIF_MEM_IS_KMEM) { OSIF_DBG((OSIF_ZONE_OSIF, "%s: using kfree\n", OSIF_FUNCTION)); *pFree = OSIF_MEM_IS_NOTUSED; kfree(pFree); } else if (*pFree == OSIF_MEM_IS_VMEM) { OSIF_DBG((OSIF_ZONE_OSIF, "%s: using vfree\n", OSIF_FUNCTION)); *pFree = OSIF_MEM_IS_NOTUSED; vfree(pFree); } else { OSIF_DBG((OSIF_ZONE_OSIF, "%s: Either unknown mem type or forbidden free!!!\n", OSIF_FUNCTION)); } } return OSIF_SUCCESS; } /*! Initialize a memory region pointed by \a ptr to a constant value \a val. \a size is the size of the region. */ INT32 OSIF_CALLTYPE osif_memset(VOID *ptr, UINT32 val, UINT32 size) { if (ptr) { memset(ptr, (char)val, size); } return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_memcpy(VOID *dst, VOID *src, UINT32 size) { memcpy(dst, src, size); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_memcmp(VOID *dst, VOID *src, UINT32 size) { return memcmp(dst, src, size); } INT32 OSIF_CALLTYPE osif_pci_read_config_byte(OSIF_PCIDEV pcidev, INT32 offs, UINT8 *ptr) { #ifdef CONFIG_PCI pci_read_config_byte(pcidev, offs, ptr); #endif return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_pci_read_config_word(OSIF_PCIDEV pcidev, INT32 offs, UINT16 *ptr) { #ifdef CONFIG_PCI pci_read_config_word(pcidev, offs, ptr); #endif return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_pci_read_config_long(OSIF_PCIDEV pcidev, INT32 offs, UINT32 *ptr) { #ifdef CONFIG_PCI pci_read_config_dword(pcidev, offs, (u32 *)ptr); #endif return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_pci_write_config_byte(OSIF_PCIDEV pcidev, INT32 offs, UINT8 val) { #ifdef CONFIG_PCI pci_write_config_byte(pcidev, offs, val); #endif return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_pci_write_config_word(OSIF_PCIDEV pcidev, INT32 offs, UINT16 val) { #ifdef CONFIG_PCI pci_write_config_word(pcidev, offs, val); #endif return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_pci_write_config_long(OSIF_PCIDEV pcidev, INT32 offs, UINT32 val) { #ifdef CONFIG_PCI pci_write_config_dword(pcidev, offs, val); #endif return OSIF_SUCCESS; } #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,0) static inline void *pci_alloc_consistent(struct pci_dev *hwdev, size_t size, dma_addr_t *dma_handle) { void *virt_ptr; virt_ptr = kmalloc(size, GFP_KERNEL); *dma_handle = virt_to_bus(virt_ptr); return virt_ptr; } #define pci_free_consistent(cookie, size, ptr, dma_ptr) kfree(ptr) #endif INT32 OSIF_CALLTYPE osif_pci_malloc(OSIF_PCIDEV pcidev, OSIF_PCI_VADDR *vaddr, OSIF_PCI_PADDR *paddr, OSIF_PCI_MADDR *maddr, UINT32 size) { OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); *paddr = vmalloc( sizeof( **paddr ) ); if ( NULL == *paddr) { return OSIF_INSUFFICIENT_RESOURCES; } #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,33)) /* LXR is currently out of order, in 2.6.33 this function was available for sure, probably way earlier */ if (pci_set_consistent_dma_mask(pcidev, DMA_BIT_MASK(32))) { OSIF_PRINT(("esd CAN driver: No 32-Bit bus master buffer available.\n")); return OSIF_INSUFFICIENT_RESOURCES; } #endif *vaddr = pci_alloc_consistent( pcidev, size, &((*paddr)->sys_dma_addr) ); if ( NULL == *vaddr ) { vfree( *paddr ); return OSIF_INSUFFICIENT_RESOURCES; } (*paddr)->addr32 = (UINT32)((*paddr)->sys_dma_addr); if ((dma_addr_t)((*paddr)->addr32) != (*paddr)->sys_dma_addr) { OSIF_PRINT(("esd CAN driver: Bus master addr conflict: dma 0x%llx(%u), addr32 0x%lx(%u)\n", (unsigned long long)((*paddr)->sys_dma_addr), sizeof (*paddr)->sys_dma_addr, (*paddr)->addr32, sizeof (*paddr)->addr32)); } OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_pci_free(OSIF_PCIDEV pcidev, OSIF_PCI_VADDR vaddr, OSIF_PCI_PADDR *paddr, OSIF_PCI_MADDR maddr, UINT32 size) { OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); pci_free_consistent(pcidev, size, vaddr, (*paddr)->sys_dma_addr ); vfree( *paddr ); OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } UINT32 OSIF_CALLTYPE osif_pci_get_phy_addr(OSIF_PCI_PADDR paddr) { return paddr->addr32; } #ifdef OSIF_PROVIDES_VSNPRINTF #warning "vsnprintf not implemented in kernels pre 2.4.8" #define ZEROPAD 1 /* pad with zero */ #define SIGN 2 /* unsigned/signed long */ #define PLUS 4 /* show plus */ #define SPACE 8 /* space if plus */ #define LEFT 16 /* left justified */ #define SPECIAL 32 /* 0x */ #define LARGE 64 /* use 'ABCDEF' instead of 'abcdef' */ /*! * \brief Needed for vsnprintf() */ static INT32 skip_atoi(const CHAR8 **s) { INT32 i = 0; while (isdigit(**s)) i = i*10 + *((*s)++) - '0'; return i; } /*! * \brief Needed for vsnprintf() */ static CHAR8* number(CHAR8* buf, CHAR8* end, INT64 num, INT32 base, INT32 size, INT32 precision, INT32 type) { CHAR8 c, sign, tmp[66]; const CHAR8 *digits; const CHAR8 small_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; const CHAR8 large_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; INT32 i; digits = (type & LARGE) ? large_digits : small_digits; if (type & LEFT) { type &= ~ZEROPAD; } if (base < 2 || base > 36) { return 0; } c = (type & ZEROPAD) ? '0' : ' '; sign = 0; if (type & SIGN) { if (num < 0) { sign = '-'; num = -num; size--; } else if (type & PLUS) { sign = '+'; size--; } else if (type & SPACE) { sign = ' '; size--; } } if (type & SPECIAL) { if (base == 16) size -= 2; else if (base == 8) size--; } i = 0; if (num == 0) { tmp[i++]='0'; } else { while (num != 0) { tmp[i++] = digits[do_div(num,base)]; } } if (i > precision) { precision = i; } size -= precision; if (!(type&(ZEROPAD+LEFT))) { while(size-->0) { if (buf <= end) { *buf = ' '; } ++buf; } } if (sign) { if (buf <= end) { *buf = sign; } ++buf; } if (type & SPECIAL) { if (base==8) { if (buf <= end) { *buf = '0'; } ++buf; } else if (base==16) { if (buf <= end) { *buf = '0'; } ++buf; if (buf <= end) { *buf = digits[33]; } ++buf; } } if (!(type & LEFT)) { while (size-- > 0) { if (buf <= end) { *buf = c; } ++buf; } } while (i < precision--) { if (buf <= end) { *buf = '0'; } ++buf; } while (i-- > 0) { if (buf <= end) { *buf = tmp[i]; } ++buf; } while (size-- > 0) { if (buf <= end) { *buf = ' '; } ++buf; } return buf; } /*! * \brief Format a string and place it in a buffer * * \param buf The buffer to place the result into * \param size The size of the buffer, including the trailing null space * \param fmt The format string to use * \param args Arguments for the format string * * This function was copied directly out of the 2.4.18.SuSE-kernel. * Since kernels pre 2.4.6 don't support this function, we need to * provide it on our own. */ INT32 OSIF_CALLTYPE osif_vsnprintf(CHAR8 *buf, size_t size, const CHAR8 *fmt, va_list args) { INT32 len; UINT64 num; INT32 i, base; CHAR8 *str, *end, c; const CHAR8 *s; INT32 flags; /* flags to number() */ INT32 field_width; /* width of output field */ INT32 precision; /* min. # of digits for integers; max number of chars for from string */ INT32 qualifier; /* 'h', 'l', or 'L' for integer fields */ /* 'z' support added 23/7/1999 S.H. */ /* 'z' changed to 'Z' --davidm 1/25/99 */ str = buf; end = buf + size - 1; if (end < buf - 1) { end = ((void *) (-1)); size = end - buf + 1; } for (; *fmt ; ++fmt) { if (*fmt != '%') { if (str <= end) { *str = *fmt; } ++str; continue; } /* process flags */ flags = 0; repeat: ++fmt; /* this also skips first '%' */ switch (*fmt) { case '-': flags |= LEFT; goto repeat; case '+': flags |= PLUS; goto repeat; case ' ': flags |= SPACE; goto repeat; case '#': flags |= SPECIAL; goto repeat; case '0': flags |= ZEROPAD; goto repeat; } /* get field width */ field_width = -1; if (isdigit(*fmt)) { field_width = skip_atoi(&fmt); } else if (*fmt == '*') { ++fmt; /* it's the next argument */ field_width = va_arg(args, INT32); if (field_width < 0) { field_width = -field_width; flags |= LEFT; } } /* get the precision */ precision = -1; if (*fmt == '.') { ++fmt; if (isdigit(*fmt)) { precision = skip_atoi(&fmt); } else if (*fmt == '*') { ++fmt; /* it's the next argument */ precision = va_arg(args, INT32); } if (precision < 0) { precision = 0; } } /* get the conversion qualifier */ qualifier = -1; if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L' || *fmt =='Z') { qualifier = *fmt; ++fmt; if (qualifier == 'l' && *fmt == 'l') { qualifier = 'L'; ++fmt; } } /* default base */ base = 10; switch (*fmt) { case 'c': if (!(flags & LEFT)) { while (--field_width > 0) { if (str <= end) { *str = ' '; } ++str; } } c = (CHAR8)va_arg(args, INT32); if (str <= end) { *str = c; } ++str; while (--field_width > 0) { if (str <= end) { *str = ' '; } ++str; } continue; case 's': s = va_arg(args, CHAR*); if (!s) s = "<NULL>"; len = strnlen(s, precision); if (!(flags & LEFT)) { while (len < field_width--) { if (str <= end) { *str = ' '; } ++str; } } for (i = 0; i < len; ++i) { if (str <= end) { *str = *s; } ++str; ++s; } while (len < field_width--) { if (str <= end) { *str = ' '; } ++str; } continue; case 'p': if (field_width == -1) { field_width = 2*sizeof(void*); flags |= ZEROPAD; } str = number(str, end, (INT32)va_arg(args, void*), 16, field_width, precision, flags); continue; case 'n': /* FIXME: * What does C99 say about the overflow case here? */ if (qualifier == 'l') { INT32 *ip = va_arg(args, INT32*); *ip = (str - buf); } else if (qualifier == 'Z') { size_t *ip = va_arg(args, size_t*); *ip = (str - buf); } else { INT32 *ip = va_arg(args, INT32*); *ip = (str - buf); } continue; case '%': if (str <= end) { *str = '%'; } ++str; continue; /* integer number formats - set up the flags and "break" */ case 'o': base = 8; break; case 'X': flags |= LARGE; case 'x': base = 16; break; case 'd': case 'i': flags |= SIGN; case 'u': break; default: if (str <= end) { *str = '%'; } ++str; if (*fmt) { if (str <= end) { *str = *fmt; } ++str; } else { --fmt; } continue; } if (qualifier == 'L') num = va_arg(args, INT64); else if (qualifier == 'l') { num = va_arg(args, UINT32); if (flags & SIGN) { num = (INT32) num; } } else if (qualifier == 'Z') { num = va_arg(args, size_t); } else if (qualifier == 'h') { num = (UINT16)va_arg(args, INT32); if (flags & SIGN) { num = (INT16) num; } } else { num = va_arg(args, UINT32); if (flags & SIGN) { num = (INT32) num; } } str = number(str, end, num, base, field_width, precision, flags); } if (str <= end) { *str = '\0'; } else if (size > 0) { /* don't write out a null byte if the buf size is zero */ *end = '\0'; } /* the trailing null byte doesn't count towards the total * ++str; */ return str-buf; } #endif /* ifdef OSIF_PROVIDES_VSNPRINTF */ /*! This function prints a formated text string. */ INT32 OSIF_CALLTYPE osif_print(const CHAR8 *fmt, ...) { va_list arglist; INT32 len; #ifdef OSIF_USE_VPRINTK va_start(arglist, fmt); len = vprintk(fmt, arglist); va_end(arglist); #else CHAR8 output[400]; va_start(arglist, fmt); len = OSIF_VSNPRINTF(output, 400, fmt, arglist); va_end(arglist); printk("%s", output); #endif return len; } /*! This function prints a formated text string, only, if one of the bits * specified in output_mask was set at module-load-time (global variable verbose). */ INT32 OSIF_CALLTYPE osif_dprint(UINT32 output_mask, const CHAR8 *fmt, ...) { va_list arglist; INT32 len = 0; UINT32 verbose_flags = verbose; #ifndef ESDDBG verbose_flags &= 0x000000FF; #endif if ( (verbose_flags & output_mask) == output_mask ) { #ifdef OSIF_USE_VPRINTK va_start(arglist, fmt); len = vprintk(fmt, arglist); va_end(arglist); #else CHAR8 output[400]; va_start(arglist, fmt); len = OSIF_VSNPRINTF(output, 400, fmt, arglist); va_end(arglist); printk("%s", output); #endif } return len; } INT32 OSIF_CALLTYPE osif_snprintf(CHAR8 *str, INT32 size, const CHAR8 *format, ...) { va_list arglist; INT32 len; va_start(arglist, format); len = OSIF_VSNPRINTF(str, size, format, arglist); va_end(arglist); return len; } /*! Sleep for a given number (\a ms) of milli seconds. */ INT32 OSIF_CALLTYPE osif_sleep( INT32 ms ) { # if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) wait_queue_head_t wq; INT32 result = OSIF_SUCCESS; UINT32 timeout = ((ms*HZ)+999)/1000; init_waitqueue_head(&wq); result = wait_event_interruptible_timeout(wq, (timeout == 0), timeout); if (result == -ERESTARTSYS) { OSIF_DBG((OSIF_ZONE_OSIF, "%s: Sleep cancelled by SIGTERM!", OSIF_FUNCTION)); } #else OSIF_DECL_WAIT_QUEUE(p); interruptible_sleep_on_timeout( &p, ((ms*HZ)+999)/1000); #endif return OSIF_SUCCESS; } /*! (Possibly busy-) sleep for a given number (\a us) of microseconds. */ INT32 OSIF_CALLTYPE osif_usleep( INT32 us ) { udelay(us); return OSIF_SUCCESS; } /* ** mutex entries */ INT32 OSIF_CALLTYPE osif_mutex_create(OSIF_MUTEX *m) { *m = vmalloc(sizeof(**m)); if(NULL == *m) { return OSIF_INSUFFICIENT_RESOURCES; } memset(*m, 0x00, sizeof(**m)); #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION #ifdef CONFIG_DEBUG_MUTEXES { int nr = atomic_inc_return(&osif_debug_mutexes_cnt)-1; if (nr >= OSIF_MAX_DEBUG_MUTEXES) { vfree(*m); *m = NULL; return OSIF_INSUFFICIENT_RESOURCES; } __mutex_init(&((*m)->lock), "osif_mutex", &osif_debug_mutexes_keys[nr]); } #else mutex_init(&((*m)->lock)); #endif #else sema_init(&((*m)->sema), 1); #endif return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_mutex_destroy(OSIF_MUTEX *m) { vfree(*m); *m = NULL; return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_mutex_lock(OSIF_MUTEX *m) { #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION mutex_lock(&((*m)->lock)); #else down(&((*m)->sema)); #endif return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_mutex_unlock(OSIF_MUTEX *m) { #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION mutex_unlock(&((*m)->lock)); #else up(&((*m)->sema)); #endif return OSIF_SUCCESS; } /* * mutexes for synchronisation against the irq-level */ INT32 OSIF_CALLTYPE osif_irq_mutex_create(OSIF_IRQ_MUTEX *im) { *im = vmalloc(sizeof(**im)); if(NULL == *im) { return OSIF_INSUFFICIENT_RESOURCES; } #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,18) spin_lock_init(&(((*im)->spinlock))); #else (*im)->spinlock = SPIN_LOCK_UNLOCKED; #endif #ifdef OSIF_DEBUG (*im)->magic = 0x0; #endif return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_irq_mutex_destroy(OSIF_IRQ_MUTEX *im) { vfree(*im); *im = NULL; return OSIF_SUCCESS; } /* * Call this entry, if you are not inside in an irq handler */ INT32 OSIF_CALLTYPE osif_irq_mutex_lock(OSIF_IRQ_MUTEX *im) { #ifdef OSIF_DEBUG struct task_struct *tsk = current; #endif UINTPTR flags; spin_lock_irqsave(&((*im)->spinlock), flags); (*im)->flags = flags; #ifdef OSIF_DEBUG (*im)->magic = tsk->pid | 0x80000000; /* MSB=1 marks entry */ #endif return OSIF_SUCCESS; } /* * Call this entry, if you are not inside an irq handler */ INT32 OSIF_CALLTYPE osif_irq_mutex_unlock(OSIF_IRQ_MUTEX *im) { UINTPTR flags = (*im)->flags; #ifdef OSIF_DEBUG struct task_struct *tsk = current; (*im)->magic = tsk->pid; /* MSB=0 marks exit (assuming pid's smaller than 0x7FFFFFFF) */ #endif spin_unlock_irqrestore(&((*im)->spinlock), flags); return OSIF_SUCCESS; } /* -------------------------------------------------------------------------------- * kernel thread that handles all our OSIF_DPC jobs */ static int osif_dpc_thread( void *context ) { #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0) struct task_struct *tsk = current; #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) /* Code for Linux version range: 2.4.0 <= LXV < 2.6.0 */ OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); #if LINUX_VERSION_CODE < KERNEL_VERSION(3,4,0) daemonize(K_DPC_NAME); /* Call wasn't really needed but didn't harm before 3.4. */ #endif #ifdef OSIF_BOARD_SPI { extern int esdcan_spi_connector_set_cur_tsk_sched(int policy, const unsigned int prio); esdcan_spi_connector_set_cur_tsk_sched(SCHED_FIFO, MAX_USER_RT_PRIO-1); } #endif /* ifdef OSIF_BOARD_SPI */ # if 0 /* BL TODO: set affinity to CPU, which executes interrupts (to get accurate timestamps...) long sched_setaffinity(pid_t pid, cpumask_t new_mask) long sched_getaffinity(pid_t pid, cpumask_t *mask) */ /* Rescheduling of this kernel thread could be done with the following call * if we were allowed to use that GPL only function. Therefore the user has * to use 'chrt' or 'renice' to set a scheduling policy and priority suitable * for his setup. */ { struct sched_param param = { .sched_priority = MAX_USER_RT_PRIO/2, }; sched_setscheduler(current, SCHED_FIFO, &param); } # endif #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) /* Code for Linux version range: 2.4.0 <= LXV < 2.6.0 */ OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter tsk=%p\n", OSIF_FUNCTION, tsk)); daemonize(); /* todo: do we need this ? */ /* tsk->pgrp = 1; */ sigfillset(&tsk->blocked); /* block all signals */ strcpy(tsk->comm, K_DPC_NAME); /* mf test-only */ tsk->policy = 1; /* SCHED_FIFO */ tsk->rt_priority = 98; /* max */ tsk->need_resched = 1; #else /* Code for Linux version range: LXV < 2.4.0 */ OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter tsk=%p\n", OSIF_FUNCTION, tsk)); tsk->session = 1; tsk->pgrp = 1; strcpy(tsk->comm, K_DPC_NAME); spin_lock_irq(&tsk->sigmask_lock); sigfillset(&tsk->blocked); /* block all signals */ recalc_sigpending(tsk); spin_unlock_irq(&tsk->sigmask_lock); /* BL TODO: check if realtime priorities can be realized with kernels below 2.4.0 */ #endif OSIF_DBG((OSIF_ZONE_OSIF, "%s: can dpc running\n", OSIF_FUNCTION)); /* notify that backend thread is running */ dpc_root.thread_running = 1; #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION wake_up(&dpc_root.wqDpcNotify); __set_current_state(TASK_RUNNING); #else up(&dpc_root.sema_notify); #endif while (!dpc_root.destroy) { #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION atomic_add_unless(&dpc_root.trig, -1, 0); /* BL: In with 2.6.15 */ smp_mb(); #else if (down_interruptible(&dpc_root.sema_trigger)<0) { continue; } if (dpc_root.destroy) { break; } #endif /* call dpc function */ OSIF_DBG((OSIF_ZONE_OSIF, "%s: dpc triggered\n", OSIF_FUNCTION)); spin_lock_irq( &dpc_root.spinlock ); while( NULL != dpc_root.first ) { OSIF_DPC dpc; dpc = dpc_root.first; dpc_root.first = dpc->next; /* link out */ dpc->linked = 0; /* mark: linked out */ dpc->running = 1; /* mark: running */ spin_unlock_irq( &dpc_root.spinlock ); dpc->func(dpc->arg); spin_lock_irq( &dpc_root.spinlock ); dpc->running = 0; /* mark: not running */ } #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION set_current_state(TASK_INTERRUPTIBLE); if (!atomic_read(&dpc_root.trig)) { spin_unlock_irq( &dpc_root.spinlock ); schedule(); } else { spin_unlock_irq( &dpc_root.spinlock ); } __set_current_state(TASK_RUNNING); #else spin_unlock_irq( &dpc_root.spinlock ); #endif } /* notify that backend thread is exiting */ dpc_root.thread_running = 0; #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION wake_up(&dpc_root.wqDpcNotify); #else up(&dpc_root.sema_notify); #endif OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) complete_and_exit(&dpcThreadCompletion, 0); #endif return 0; /* This will never reached, if kernel >= 2.4.0 */ } static INT32 osif_dpc_root_create( VOID ) { #ifndef OSIF_USE_PREEMPT_RT_IMPLEMENTATION INT32 threadId; #endif OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); dpc_root.thread_running = 0; #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,18) spin_lock_init(&dpc_root.spinlock); #else dpc_root.spinlock = SPIN_LOCK_UNLOCKED; #endif #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION init_waitqueue_head(&dpc_root.wqDpcNotify); dpc_root.tsk = kthread_run(osif_dpc_thread, NULL, K_DPC_NAME); if (IS_ERR(dpc_root.tsk)) { return OSIF_EIO; } if (!wait_event_timeout(dpc_root.wqDpcNotify, (1 == dpc_root.thread_running), 100)) { /* wait for DPC thread to start */ return OSIF_INSUFFICIENT_RESOURCES; } #else sema_init( &dpc_root.sema_trigger, 0 ); sema_init( &dpc_root.sema_notify, 0 ); threadId = kernel_thread(osif_dpc_thread, 0, 0); if ( 0 == threadId ) { return CANIO_EIO; } down( &dpc_root.sema_notify ); if ( 0 == dpc_root.thread_running ) { return OSIF_INSUFFICIENT_RESOURCES; } #endif OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } static INT32 osif_dpc_root_destroy( VOID ) { OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); dpc_root.destroy = 1; #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION wake_up_process(dpc_root.tsk); wait_event_timeout(dpc_root.wqDpcNotify, (0 == dpc_root.thread_running), 100); #else up(&dpc_root.sema_trigger); down(&dpc_root.sema_notify); #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) wait_for_completion(&dpcThreadCompletion); #endif dpc_root.destroy = 0; return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_dpc_create( OSIF_DPC *dpc, VOID (OSIF_CALLTYPE *func)(VOID *), VOID *arg ) { INT32 result; OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); result = OSIF_MALLOC( sizeof(**dpc), (VOID*)dpc ); if ( OSIF_SUCCESS != result ) { return result; } OSIF_MEMSET( *dpc, 0, sizeof(**dpc) ); (*dpc)->func = func; (*dpc)->arg = arg; OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_dpc_destroy( OSIF_DPC *dpc ) { OSIF_DPC dpc2; UINTPTR flags; OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); if (NULL == *dpc) { return CANIO_EFAULT; } spin_lock_irqsave( &dpc_root.spinlock, flags ); (*dpc)->destroy = 1; /* now triggers will ret ENOENT */ if(*dpc == dpc_root.first) { dpc_root.first = (*dpc)->next; /* link out */ (*dpc)->next = NULL; /* mark: linked out */ } else { dpc2 = dpc_root.first; while( NULL != dpc2 ) { if(*dpc == dpc2->next) { dpc2->next = (*dpc)->next; /* link out */ (*dpc)->next = NULL; /* mark: linked out */ break; } dpc2 = dpc2->next; /* move up */ } } /* if it was linked, it is now unlinked and ready for removal */ /* if it was unlinked, it could just run... */ while( 0 != (*dpc)->running ) { spin_unlock_irqrestore( &dpc_root.spinlock, flags ); OSIF_SLEEP(300); spin_lock_irqsave( &dpc_root.spinlock, flags ); } spin_unlock_irqrestore( &dpc_root.spinlock, flags ); OSIF_FREE(*dpc); *dpc = NULL; OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_dpc_trigger( OSIF_DPC *dpc ) { UINTPTR flags; OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter, dpc=%p\n", OSIF_FUNCTION,(UINTPTR)dpc )); if (NULL == *dpc) { return CANIO_EFAULT; } spin_lock_irqsave( &dpc_root.spinlock, flags ); if( 0 != (*dpc)->destroy ) { spin_unlock_irqrestore( &dpc_root.spinlock, flags ); return CANIO_ENOENT; } if( 0 == (*dpc)->linked ) { if( NULL == dpc_root.first) { dpc_root.first = *dpc; } else { OSIF_DPC dpc2; dpc2 = dpc_root.first; while( NULL != dpc2->next ) { dpc2 = dpc2->next; } dpc2->next = *dpc; } (*dpc)->next = NULL; /* mark end of chain */ (*dpc)->linked = 1; /* mark linked */ spin_unlock_irqrestore( &dpc_root.spinlock, flags ); #ifdef OSIF_USE_PREEMPT_RT_IMPLEMENTATION atomic_inc(&dpc_root.trig); /* BL TODO: check, if usable with all kernel.org kernels...!!! */ smp_mb(); wake_up_process(dpc_root.tsk); #else up(&dpc_root.sema_trigger); #endif } else { spin_unlock_irqrestore( &dpc_root.spinlock, flags ); } OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } /* ** this timer stub runs on soft-irq-level and triggers a dpc for the user timer handler */ static void timer_stub( OSIF_LINUX_TIMER *pLxTimer) { OSIF_DPC_TRIGGER( &pLxTimer->dpc ); } /*! \fn osif_timer_create( OSIF_TIMER **timer, VOID(OSIF_CALLTYPE *func)(VOID *), VOID *arg, VOID *pCanNode ); * \brief Create a timer object. * \param timer a pointer to the created timer structure is returned through this parameter. * \param func func(arg) will be called when timer expires. * \param arg is passed as argument to the timer handler \a func. * The created timer is initially disabled after creation. */ INT32 OSIF_CALLTYPE osif_timer_create( OSIF_TIMER *t, VOID (OSIF_CALLTYPE *func)(VOID *), VOID *arg, VOID *pCanNode ) { OSIF_LINUX_TIMER *pLxTimer; INT32 result; OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); result = OSIF_MALLOC(sizeof(*pLxTimer), &pLxTimer); if (result != OSIF_SUCCESS) { return result; } t->pTimerExt = (VOID*)pLxTimer; init_timer(&(pLxTimer->timer)); pLxTimer->timer.function = (VOID*)timer_stub; pLxTimer->timer.data = (UINTPTR)pLxTimer; pLxTimer->timer.expires = 0; OSIF_DPC_CREATE(&pLxTimer->dpc, func, arg); OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } /*! \fn osif_timer_destroy( OSIF_TIMER *timer ); * \brief Destroy a timer object. * \param timer a pointer to the timer structure. */ INT32 OSIF_CALLTYPE osif_timer_destroy( OSIF_TIMER *t ) { OSIF_LINUX_TIMER *pLxTimer; OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); if (NULL == t->pTimerExt) { return CANIO_ERROR; } pLxTimer = (OSIF_LINUX_TIMER*)t->pTimerExt; t->pTimerExt = NULL; del_timer(&pLxTimer->timer); OSIF_DPC_DESTROY(&pLxTimer->dpc); OSIF_FREE(pLxTimer); OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } /*! \fn osif_timer_set( OSIF_TIMER *timer, UINT32 ms ); * \brief Set the expiration time for a timer. * \param timer is a pointer to the timer that should be modified * \param ms new expiration time for this timer in ms. A value of 0 * disables the timer. */ INT32 OSIF_CALLTYPE osif_timer_set( OSIF_TIMER *t, UINT32 ms ) { OSIF_LINUX_TIMER *pLxTimer = (OSIF_LINUX_TIMER*)t->pTimerExt; OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter (ms = %d)\n", OSIF_FUNCTION, ms)); if (ms) { if (HZ == 1000) { mod_timer(&(pLxTimer->timer), jiffies + ms); } else { mod_timer(&(pLxTimer->timer), jiffies + (((ms * HZ) + 500) / 1000)); /* round correctly */ } } else { del_timer(&(pLxTimer->timer)); } OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave\n", OSIF_FUNCTION)); return OSIF_SUCCESS; } INT32 OSIF_CALLTYPE osif_timer_get( OSIF_TIMER *t, UINT32 *ms ) { OSIF_DBG((OSIF_ZONE_OSIF, "%s: enter\n", OSIF_FUNCTION)); if (ms) { *ms = jiffies * 1000 / HZ; } OSIF_DBG((OSIF_ZONE_OSIF, "%s: leave (ms=%d)\n", OSIF_FUNCTION, *ms)); return OSIF_SUCCESS; } /* Defined in "board".cfg, * if the driver is running in a Linux host system * (is not an embedded driver) */ #if defined(HOST_DRIVER) || defined(OSIF_ARCH_ARM) UINT64 OSIF_CALLTYPE osif_ticks( VOID ) { struct timeval tv; do_gettimeofday(&tv); return ((UINT64)tv.tv_sec * 1000000LL) + (UINT64)tv.tv_usec; } #else # ifdef OSIF_ARCH_PPC UINT64 __attribute__((__unused__)) osif_ticks( VOID ) { unsigned __lo; unsigned __hi; unsigned __tmp; __asm__ __volatile__( "1:;" " mftbu %0;" " mftb %1;" " mftbu %2;" " cmplw %0,%2;" "bne- 1b;" : "=r" (__hi), "=r" (__lo), "=r" (__tmp) ); return (UINT64) __hi << 32 | (UINT64) __lo; } # if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) # if (defined(BOARD_mecp52)) # include <asm-ppc/ppcboot.h> /* AB: needed for mpc5200 ports? */ # endif /*extern bd_t __res;*/ # endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ #if defined(CONFIG_OF_DEVICE) || defined(CONFIG_OF_FLATTREE) # include <asm/time.h> #endif UINT64 OSIF_CALLTYPE osif_tick_frequency() { #if defined(CONFIG_OF_DEVICE) || defined(CONFIG_OF_FLATTREE) return tb_ticks_per_sec; #elif defined (BOARD_pmc440) || defined (BOARD_pmc440fw) return (UINT64)(533334400); /* TODO: get CPU frequency from somewhere in kernel */ #elif defined (BOARD_mecp52) || defined (BOARD_mecp512x) /* BL TODO: dirty!!! fix it fix it fix it!!! */ return (UINT64)(33000000); /* TODO: get CPU frequency from somewhere in kernel */ #elif defined(BOARD_cpci750) return (UINT64)(33333000); /* TODO: get CPU frequency from somewhere in kernel */ #else # if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) bd_t *bd = (bd_t *)&__res; # else bd_t *bd = (bd_t *)__res; /* we find 'unsigned char __res[]' in old kernels */ # endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0) */ OSIF_DBG((OSIF_ZONE_OSIF, "%s: cpu freq = %d\n", OSIF_FUNCTION, bd->bi_procfreq)); return (UINT64)(bd->bi_procfreq); #endif } # endif /* #ifdef OSIF_ARCH_PPC */ #if 0 # ifdef OSIF_ARCH_ARM UINT64 OSIF_CALLTYPE osif_ticks( VOID ) { return 1; } UINT64 OSIF_CALLTYPE osif_tick_frequency( VOID ) { return 1; } # endif #endif #endif /* #ifdef HOST_DRIVER */ UINT32 OSIF_CALLTYPE _osif_div64_32_(UINT64 *n, UINT32 base) { UINT64 rem = *n; UINT64 b = base; UINT64 res, d = 1; UINT32 high = rem >> 32; /* Reduce the thing a bit first */ res = 0; if (high >= base) { high /= base; res = (UINT64) high << 32; rem -= (UINT64) (high*base) << 32; } while ((INT64)b > 0 && b < rem) { b <<= 1; d <<= 1; } do { if (rem >= b) { rem -= b; res += d; } b >>= 1; d >>= 1; } while (d); *n = res; return rem; } VOID OSIF_CALLTYPE osif_ser_out( CHAR8 *str ) { UINT32 i; /* disable serial interrupt */ outb( (unsigned char)0, 0x3F9 ); /* output of string */ for (i = 0; i < strlen(str); i++) { while ( !(inb(0x3F8+5) & 0x20) ); outb( str[i], 0x3F8 ); } while ( !(inb(0x3F8+5) & 0x20) ); /* reenable serial interrupt */ /* outb(0x3F9, 0x??); */ /* AB TODO */ return; } #ifdef OSIF_USE_IO_FUNCTIONS /*! \fn osif_io_out8(void *addr, UINT8 data); * \brief Write access to I/O-space (8 bit wide) * \param addr target address * \param data this data is written to target address */ void OSIF_CALLTYPE osif_io_out8(UINT8 *addr, UINT8 data) { #if defined(OSIF_ARCH_ARM) writeb((UINT8)data, (void *)(addr)); #else outb((UINT8)data, (UINTPTR)(addr)); #endif } /*! \fn osif_io_in8(void *addr); * \brief Read access to I/O-space (8 bit wide) * \param addr target address * \return data from target address */ UINT8 OSIF_CALLTYPE osif_io_in8(UINT8 *addr) { #if defined(OSIF_ARCH_ARM) return readb((void *)addr); #else return inb((UINTPTR)addr); #endif } /*! \fn osif_io_out16(void *addr, UINT16 data); * \brief Write access to I/O-space (16 bit wide) * \param addr target address * \param data this data is written to target address */ void OSIF_CALLTYPE osif_io_out16(UINT16 *addr, UINT16 data) { #if defined(OSIF_ARCH_ARM) writew((UINT16)data, (void *)(addr)); #else outw((UINT16)data, (UINTPTR)(addr)); #endif } /*! \fn osif_io_in16(void *addr); * \brief Read access to I/O-space (16 bit wide) * \param addr target address * \return data from target address */ UINT16 OSIF_CALLTYPE osif_io_in16(UINT16 *addr) { #if defined(OSIF_ARCH_ARM) return readw((void *)addr); #else return inw((UINTPTR)addr); #endif } /*! \fn osif_io_out32(void *addr, UINT32 data); * \brief Write access to I/O-space (32 bit wide) * \param addr target address * \param data this data is written to target address */ void OSIF_CALLTYPE osif_io_out32(UINT32 *addr, UINT32 data) { #if defined(OSIF_ARCH_ARM) writel((UINT32)data, (void *)(addr)); #else outl((UINT32)data, (UINTPTR)(addr)); #endif } /*! \fn osif_io_in32(void *addr); * \brief Read access to I/O-space (32 bit wide) * \param addr target address * \return data from target address */ UINT32 OSIF_CALLTYPE osif_io_in32(UINT32 *addr) { #if defined(OSIF_ARCH_ARM) return readl((void *)addr); #else return inl((UINTPTR)addr); #endif } #endif /************************************************************************/ /* UTILITY CODE */ /************************************************************************/ INT32 OSIF_CALLTYPE osif_make_ntcan_serial(const CHAR8* pszSerial, UINT32 *pulSerial) { INT32 lTemp; *pulSerial = 0; if(pszSerial[0] >= 'A' && pszSerial[0] <= 'P' && pszSerial[1] >= 'A' && pszSerial[1] <= 'P') { lTemp = ((pszSerial[0] - 'A') << 28) | ((pszSerial[1] - 'A') << 24); *pulSerial = simple_strtoul(&pszSerial[2], NULL, 10); *pulSerial |= (UINT32)lTemp; } return OSIF_SUCCESS; } /* * RCS/CVS id and build tag with support to prevent compiler warnings about * unused vars for different compiler */ #if defined(_MSC_VER) && (_MSC_VER >= 800) /* VC++ 32 Bit compiler */ static char* rcsid = "$Id: osif.c 14792 2015-07-13 19:01:09Z stefanm $"; #elif defined (__ghs__) /* Green Hills compiler */ # pragma ident "$Id: osif.c 14792 2015-07-13 19:01:09Z stefanm $" #elif ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >=1)) /* GCC >= 3.1 */ static char* rcsid __attribute__((unused,used)) = "$Id: osif.c 14792 2015-07-13 19:01:09Z stefanm $"; #elif ((__GNUC__ > 2) || (__GNUC__ == 2 && __GNUC_MINOR__ >=7)) /* GCC >= 2.7 */ static char* rcsid __attribute__((unused)) = "$Id: osif.c 14792 2015-07-13 19:01:09Z stefanm $"; #else /* No or old GNU compiler */ # define USE(var) static void use_##var(void *x) {if(x) use_##var((void *)var);} static char* rcsid = "$Id: osif.c 14792 2015-07-13 19:01:09Z stefanm $"; USE(rcsid); #endif /* of _MSC_VER >= 800 */
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/smartereye/install.sh
#!/usr/bin/env bash ############################################################################### # Copyright 2020 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### # Fail on first error. set -e cd "$(dirname "${BASH_SOURCE[0]}")" DEST_DIR="/usr/local/apollo/third_party/smartereye" if [ $# -ge 1 ]; then DEST_DIR="$1" fi function create_symlinks() { local mylib_dir="lib" local orig_libs orig_libs=$(find ${mylib_dir} -name "lib*.so.*" -type f) for mylib in ${orig_libs}; do mylib=$(basename $mylib) ver="${mylib##*.so.}" if [ -z "$ver" ]; then continue fi libname="${mylib%%.so*}" IFS='.' read -ra arr <<< "${ver}" IFS=" " # restore IFS num=${#arr[@]} if [[ num -gt 2 ]]; then ln -s "./${mylib}" "${mylib_dir}/${libname}.so.${arr[0]}.${arr[1]}" fi ln -s "./${mylib}" "${mylib_dir}/${libname}.so.${arr[0]}" ln -s "./${mylib}" "${mylib_dir}/${libname}.so" echo "Done symlinking ${mylib}" done } function clean_symlinks() { local dest_dir="${DEST_DIR}" pushd ${dest_dir} local mylib_dir="lib" find ${mylib_dir} -name lib*.so* -type l | xargs rm -rf popd } function install_smartereye() { local dest_dir="${DEST_DIR}" [ -d "${dest_dir}" ] || mkdir -p "${dest_dir}" [ -d "${dest_dir}/lib" ] && rm -rf "${dest_dir}/lib" [ -d "${dest_dir}/include" ] && rm -rf "${dest_dir}/include" cp -rf include "${dest_dir}" cp -rf lib "${dest_dir}" cp -f README.md License.txt "${dest_dir}" pushd $dest_dir create_symlinks popd } install_smartereye ### QAsioSocket was provided by https://github.com/dushibaiyu/QAsioSocket
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/smartereye/README.md
# SmarterEye SDK ## installer.sh By default, SmarterEye SDK will be installed to `/usr/local/apollo/third_party/smartereye`. You can change this by specifying your custom installation directory, E.g., `./install.sh /opt/smartereye` ## Others - The QAsioSocket lib was built w/ srcs from https://github.com/dushibaiyu/QAsioSocket, according to some SmarterEye author. ## For more, please refere to... -Repo: https://github.com/SmarterEye/SmarterEyeSdk -Doc: https://smartereye.github.io/SmarterEyeSdk
0
apollo_public_repos/apollo-contrib
apollo_public_repos/apollo-contrib/smartereye/License.txt
/************************************************************************ * * Copyright (c) 2018 - 2024 by Beijing Smarter Eye Technology Co.Ltd * * This software is copyrighted by and is the sole property of * Beijing Smarter Eye Technology Co.Ltd. All rights, title, * ownership, or other interests in the software remain the property * of Beijing Smarter Eye Technology Co.Ltd. This software may only be * used in accordance with the corresponding license agreement. Any * unauthorized use, duplication, transmission, distribution, or * disclosure of this software is expressly forbidden. * * This Copyright notice may not be removed or modified without prior * written consent of Beijing Smarter Eye Technology Co.Ltd. * * Beijing Smarter Eye Technology Co.Ltd, reserves the right to modify * this software without notice. * * Beijing Smarter Eye Technology Co.Ltd Tel. 010-59231480 * Beijing http://www.smartereye.com * Beijing ran.meng@smartereye.com * *************************************************************************/ Distributed with Apollo with permission from Beijing Smarter Eye Technology Co.Ltd. For any copyright & licensing agreement of using Beijing Smarter Eye Technology Co.Ltd contributed code/programs, please contact Beijing Smarter Eye Technology Co.Ltd directly.
0