tst_file_transferrer.c 30.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
/*****************************************************************************
*  Copyright Statement:
*  --------------------
*  This software is protected by Copyright and the information contained
*  herein is confidential. The software may not be copied and the information
*  contained herein may not be used or disclosed except with the written
*  permission of MediaTek Inc. (C) 2005
*
*  BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
*  THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
*  RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
*  AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
*  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
*  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
*  NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
*  SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
*  SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
*  THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
*  NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
*  SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
*  BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
*  LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
*  AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
*  OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
*  MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. 
*
*  THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
*  WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
*  LAWS PRINCIPLES.  ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
*  RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
*  THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/

/*****************************************************************************
 *
 * Filename:
 * ---------
 * tst_file_transfer.c
 *
 * Project:
 * --------
 *   Maui_Software
 *
 * Description:
 * ------------
 *   This file implements the tasks to transfer TST logs to File
 *
 * Author:
 * -------
 * -------
 *
 *==============================================================================
 *             HISTORY
 * Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *------------------------------------------------------------------------------
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 * removed!
 * removed!
 * removed!
 *
 *
 *------------------------------------------------------------------------------
 * Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *============================================================================
 ****************************************************************************/

#include "kal_release.h"      /* Basic data type */

#include "stack_common.h"
#include "stack_msgs.h"
#include "app_ltlcom.h"       /* Task message communiction */

#include "syscomp_config.h"
#include "task_config.h"      /* Task creation */

#include "kal_public_api.h"   /* Buffer management */

#include "gv.h"
#include "tst_def.h"
#include "tst_ext.h"          /* Dump info*/
#include "fat_fs.h"
#include "dcl.h" // For HAL RTC Interface

#pragma arm section code= "PRIMARY_ROCODE" rwdata = "PRIMARY_RW" , rodata = "PRIMARY_RODATA" , zidata = "PRIMARY_ZI" 
/*************************************************************************
* Definitions
 *************************************************************************/
#ifdef __TST_WRITE_TO_FILE__
  #if defined(__TST_WRITE_EX_MEM_ONLY__)
    kal_uint8   write2file_temp_buf[ASSERT_MEM_DISK_DUMP_BUF_LEN];
    #define ASSERT_MEM_DISK_DUMP_BUF_LEN         (1024)
  #else
    #define write2file_temp_buf (tst_dump_info.buffer)
    #define ASSERT_MEM_DISK_DUMP_BUF_LEN (TST_FSWRITE_BUFFER_SIZE)
  #endif 
#endif  //#ifdef __TST_WRITE_TO_FILE__

#define BIN_FILE_HEADER (0x2454ABCD)
#define BIN_FILE_VERSION (0x00000001)
#define TST_FILE_DISK_CHECK_PERIOD (128)

/*************************************************************************
* Global variable declaration
 *************************************************************************/

#ifdef __TST_WRITE_TO_FILE__    
  tst_dump_info_struct tst_dump_info;
  
  #ifdef __SMART_PHONE_MODEM__ 
    kal_uint32 tst_check_sd_avail_tick=0;
  #endif  //#ifdef __SMART_PHONE_MODEM__ 
    
  #if defined(__TST_WRITE_EX_MEM_ONLY__)
    kal_uint8   write2file_temp_buf[ASSERT_MEM_DISK_DUMP_BUF_LEN];
  #else
    #define write2file_temp_buf (tst_dump_info.buffer)
    #define ASSERT_MEM_DISK_DUMP_BUF_LEN (TST_FSWRITE_BUFFER_SIZE)
  #endif 
#elif defined(__AT_ETSTLP_SUPPORT__) || !defined(__MMI_FMI__)
    #define ASSERT_MEM_DISK_DUMP_BUF_LEN (1024)  // for dual talk logging memory dump
    kal_uint8 write2file_temp_buf[ASSERT_MEM_DISK_DUMP_BUF_LEN];
#else
    #define write2file_temp_buf NULL
    #define ASSERT_MEM_DISK_DUMP_BUF_LEN (0)
#endif  //#ifdef __TST_WRITE_TO_FILE__

tst_log_to_file_err_enum tst_err_log_to_file = NO_LOG_ERROR;  //the error code
kal_uint8* tst_file_ex_tmp_buf = write2file_temp_buf;
kal_uint32 tst_file_ex_tmp_buf_size = ASSERT_MEM_DISK_DUMP_BUF_LEN;
kal_eventgrpid  tft_event_group;


/*************************************************************************
* Extern variable declaration
 *************************************************************************/
#if defined(__SMART_PHONE_MODEM__) 
  extern kal_bool  tst_ft_mode; 
#endif  //#if defined(__SMART_PHONE_MODEM__) 
extern kal_bool  tst_is_PsTrc_open;
extern kal_bool  tst_ft_mode;
extern kal_uint8   TST_OUTPUT_MODE;
extern char base_release_hw_ver[];
extern char base_release_sw_ver[];
extern unsigned char  tst_module_filter_g[];
extern unsigned char  tst_sap_filter_g[];
extern unsigned char  tst_trace_filter_g[];
extern kal_bool    tst_l1trace_flag;
extern kal_bool    tst_pstrace_flag;

/*************************************************************************
* Function declaration
 *************************************************************************/
kal_bool tst_file_transferrer_create(comptask_handler_struct **handle);
kal_bool tst_file_transferrer_init(task_indx_type task_indx);
kal_bool tst_file_transferrer_configure(task_indx_type task_indx);
void tst_file_transferrer_main( task_entry_struct * task_entry_ptr );
kal_bool tst_file_transferrer_end(task_indx_type task_indx);
kal_bool tst_file_transferrer_reset(task_indx_type task_indx);
void tst_file_open_file_to_write(void);
void tst_file_dump_create_file(void);
FS_HANDLE tst_file_create_file(void);
void tst_file_dump_file(void);
kal_bool tst_file_write_file(kal_uint8 *buffer, kal_uint32 length);
extern kal_bool tst_check_filter_enabled(void);
extern void trc_setfilter(unsigned char *setting, unsigned int len);
extern kal_bool if_buffer_all_zero(kal_uint8 *ptr, kal_uint16 length);
extern void tst_file_update_predefined_filters(void);
extern kal_uint32 tst_get_ring_buffer_usage();
extern void tst_file_write_logacc_logs(void);
extern void tst_nvram_statistic_handler(nvram_actions act);
kal_uint32 tst_file_wait_data_card_for_ready(void);
kal_bool tst_file_get_disk_phy_space(kal_char driveLetter);

/*************************************************************************
* Function body
 *************************************************************************/

#ifdef __TST_WRITE_TO_FILE__  //this function is only avaialable when __TST_WRITE_TO_FILE__ is enabled

void tst_file_write_verno_to_file(void)
{
  FS_HANDLE  fHandle;
  WCHAR strFSName[54];//i.e. X:\PSLog\00000.dmp
  kal_uint32 written_bytes;
  
  #if !defined(__SMART_PHONE_MODEM__)
  {
    RTC_CTRL_GET_TIME_T rtc_time;
    DCL_HANDLE rtc_handler;
    
    rtc_handler = DclRTC_Open(DCL_RTC,FLAGS_NONE);
    DclRTC_Control(rtc_handler, RTC_CMD_GET_TIME, (DCL_CTRL_DATA_T *)&rtc_time); // New API with CMD & DATA 

    //create/open the file
    kal_wsprintf(strFSName, "%c:\\PSLog\\%d-%d-%d_%d-%d-%d_version.txt", tst_dump_info.cDriveLetter,
               rtc_time.u1Year + 2000,
               rtc_time.u1Mon,
               rtc_time.u1Day,
               rtc_time.u1Hour,
               rtc_time.u1Min,
               rtc_time.u1Sec
               );
  }
  #else //#if !define(__SMART_PHONE_MODEM__)   
  {     
    kal_uint32 tick;     
    
    kal_get_time(&tick);
    //create/open the file
    kal_wsprintf(strFSName, "%c:\\PSLog\\%d_version.txt", tst_dump_info.cDriveLetter,tick);  
  }
  #endif  //#if !define(__SMART_PHONE_MODEM__)

  fHandle = FS_Open(strFSName, FS_CREATE_ALWAYS); //overwrite it if if has existed  
  
  if (fHandle < 0)
    return;
    
  FS_Write(fHandle, "MTK HW Version = ", 17, &written_bytes);
  FS_Write(fHandle, base_release_hw_ver, strlen(base_release_hw_ver), &written_bytes);
  FS_Write(fHandle, "\n", 1, &written_bytes);
  FS_Write(fHandle, "MTK SW Version = ", 17, &written_bytes);
  FS_Write(fHandle, base_release_sw_ver, strlen(base_release_sw_ver), &written_bytes);
  FS_Write(fHandle, "\n", 1, &written_bytes);  
  FS_Close(fHandle);
}

//Load the filter settings from SD:\\PSLog\\catcher_filter.bin
int tst_file_load_Catcher_filter_from_files()
{
  FS_HANDLE  fHandle;
  WCHAR strFSName[36];//i.e. X:\PSLog\00000.dmp
  kal_uint32 read_data;
  kal_uint32 read_len;
  int res = 0;
  
  kal_wsprintf(strFSName, "%c:\\PSLog\\catcher_filter.bin", tst_dump_info.cDriveLetter);
  fHandle = FS_Open(strFSName, FS_READ_ONLY); //overwrite it if if has existed  
  
  if (fHandle < 0)
  {
    tst_sys_trace("[TST] Can't find catcher_filter.bin from SD.");
    res = -1;
    goto LOAD_FILTER_EXIT;
  }
  
  //bin file content layout
  // header (4 bytes)
  // version (4 bytes)
  // l1 data length(4 bytes) 
  // l1 data ( (l1_n+3)/4*4 bytes )
  // ps module length (4 bytes) 
  // ps module data ( ps_m_n bytes )  
  // ps trace length (4 bytes) 
  // ps trace data ( ps_t_n bytes )
  // ps sap length (4 bytes) 
  // ps sap data ( ps_s_n bytes )
  
  //read header
  res = FS_Read(fHandle, &read_data, 4, &read_len);
  if (read_data != BIN_FILE_HEADER)
  {
    res = -2;
    goto LOAD_FILTER_EXIT;
  }
 
  //read version
  res = FS_Read(fHandle, &read_data, 4, &read_len);
  if (read_data == 0x00000001)
  { 
    kal_uint32 i;
    unsigned char* data_ptr;    
    
    for (i=0;i<4;++i)
    {    
      //read length
      res = FS_Read(fHandle, &read_data, 4, &read_len);
      data_ptr = (unsigned char*)get_ctrl_buffer(read_data);
      
      //read data
      res = FS_Read(fHandle, data_ptr, read_data, &read_len);      
      
      switch (i)
      {
        case 0: //l1        
          if(if_buffer_all_zero( data_ptr, read_data))
          {
            tst_l1trace_flag = KAL_FALSE;
          }
          else
          {
            tst_l1trace_flag = KAL_TRUE;                
          }
          trc_setfilter(data_ptr, read_data);
        break;
        case 1: //tst module
          memcpy(tst_module_filter_g, data_ptr, read_data);
        break;
        case 2: //tst trace
          memcpy(tst_trace_filter_g, data_ptr, read_data);
        break;
        case 3: //tst sap
          memcpy(tst_sap_filter_g, data_ptr, read_data);
        break;
        default:
        break;
      }
      
      free_ctrl_buffer(data_ptr);
    } //for (i=0;i<4;++i)
    
    res = 0;
  }
  else
  {
    FS_Close(fHandle);
    res = -3;
    goto LOAD_FILTER_EXIT;
  }
 
LOAD_FILTER_EXIT: 
  FS_Close(fHandle);
  return res; 
}

void tst_file_set_log2SD_option(void)
{
  // decide the tst output mode
  if ( (TST_OUTPUT_MODE == 0) || (tst_ft_mode == KAL_TRUE)) //UART only
  {  
    tst_dump_info.tst_write2_sd_option = TST_Write2File_None;
  }
  else if (TST_OUTPUT_MODE == 1) //FILE only
  {
    tst_dump_info.tst_write2_sd_option = TST_Write2File_Only;
  }
  else   //Both UART and File
  { 
    tst_dump_info.tst_write2_sd_option = TST_Write2File_Both;
  }
  
  #ifdef __USB_MODEM_CARD_SUPPORT__
    tst_file_wait_data_card_for_ready();
  #endif  //__USB_MODEM_CARD_SUPPORT__
  
  if (tst_dump_info.tst_write2_sd_option != TST_Write2File_None)
  {       
    //tst_open_file_to_write();
    tst_file_open_file_to_write();
    tst_is_PsTrc_open = KAL_TRUE;        
    tst_dump_info.bAlreadyAssertDump = KAL_FALSE;        
    
    //check the pre-defined filter files
    if (tst_file_load_Catcher_filter_from_files() != 0)
    {  
      //Use the default filters if no filters are set
      if (tst_check_filter_enabled() == KAL_FALSE)
      {
        tst_sys_trace("[TST] Use the pre-defined filters for logging");  
        tst_file_update_predefined_filters();
      }
      else
      {
        tst_sys_trace("[TST] Use the pre-defined filters from NVRAM for logging");  
      }
    }
    else
    {
      tst_sys_trace("[TST] Use the pre-defined filters from SD for logging");  
    }
    if (if_buffer_all_zero(tst_module_filter_g, TST_MODULE_FILTER_LEN))
      tst_pstrace_flag = KAL_FALSE;
    else
      tst_pstrace_flag = KAL_TRUE;  	
    
  }
}

void tst_file_sp_check_sd_ready()
{
#ifdef __SMART_PHONE_MODEM__    
  if (tst_err_log_to_file == NO_CARD)
  {
    kal_uint32 cur_time;
    extern kal_uint32 tst_check_sd_avail_tick;
    
    kal_get_time(&cur_time);
    
    //check it every two second
    if (kal_ticks_to_secs(cur_time-tst_check_sd_avail_tick) > 2)
    {
      tst_set_log2SD_option();
      tst_check_sd_avail_tick = cur_time;
    }
  }
#endif  //#ifdef __SMART_PHONE_MODEM__   
}

//Return
//0: nothing happen, 
//1: to start only log to file, 
//2: to stop only log to file
kal_uint32 tst_file_check_if_output2uart()
{
  kal_uint32 cWriteToFileInd=0;
    
  if (TST_OUTPUT_MODE == 2) //output to both UART and File
  {
    kal_uint32 ratio;
    cWriteToFileInd = 0;
    ratio = tst_get_ring_buffer_usage() * 100 / TST_RING_BUFFER_SIZE;
    
    if (tst_dump_info.tst_write2_sd_option == TST_Write2File_Both)
    {
      if (ratio > 70 ) // > 70%
      {
        tst_dump_info.tst_write2_sd_option = TST_Write2File_Only;

        cWriteToFileInd = 1; //1: to start  logging to file, 

        //reset the counter
        tst_dump_info.nOmitPacketCount = 1; //this will be reset at tst_indicate_write_to_file_status()
      }
    }
    else 
    {
      if (ratio < 10 ) // <10%
      {        
        tst_dump_info.tst_write2_sd_option = TST_Write2File_Both;
        cWriteToFileInd = 2;
      }else
      {
        tst_dump_info.nOmitPacketCount++; //this will be reset at tst_indicate_write_to_file_status()
      }
    }        
  }

  return cWriteToFileInd;
}

/*************************************************************************
* FUNCTION
*  tst_create
*
* DESCRIPTION
*  This function implements tst entity's create handler.
*
* PARAMETERS
*
* RETURNS
*  None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_bool
tst_file_transferrer_create(comptask_handler_struct **handle)
{
  static const comptask_handler_struct tst_file_transferrer_handler_info =
  {
    tst_file_transferrer_main,      /* task entry function */
    tst_file_transferrer_init,        /* task initialization function */
    tst_file_transferrer_configure,   /* task configuration function */
    tst_file_transferrer_reset,    /* task reset handler */
    tst_file_transferrer_end      /* task termination handler */
  };

  *handle = (comptask_handler_struct *)&tst_file_transferrer_handler_info;
  return KAL_TRUE;
}


/*************************************************************************
* FUNCTION
*  tst_file_transferrer_init
*
* DESCRIPTION
*  This function calls component task's initialization handler
*
* PARAMETERS
*  task_index  -  task's index
*
* RETURNS
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_bool tst_file_transferrer_init(task_indx_type task_indx)
{
  tst_dump_info.cDriveLetter = 0xFF;  // init it as a impossible char
  tft_event_group = kal_create_event_group("TFTEVT");
  return KAL_TRUE;  
}

/*************************************************************************
* FUNCTION
*  tst_file_transferrer_configure
*
* DESCRIPTION
*  This function implements component task's configuration handler
*
* PARAMETERS
*  cfg_ptr    -  pointer to configuration paraemters structure
*  task_index  -  task's index
*
* RETURNS
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_bool
tst_file_transferrer_configure(task_indx_type task_indx)
{

  return KAL_TRUE;
}

/*************************************************************************
* FUNCTION
*  tst_file_transferrer_reset
*
* DESCRIPTION
*  This function implements xyz's reset handler
*
* PARAMETERS
*  task_index  -  task's index
*
* RETURNS
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_bool
tst_file_transferrer_reset(task_indx_type task_indx)
{
  return KAL_TRUE;
}

/*************************************************************************
* FUNCTION
*  tst_file_transferrer_end
*
* DESCRIPTION
*  This function implements tst's termination handler
*
* PARAMETERS
*  task_index  -  task's index
*
* RETURNS
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_bool tst_file_transferrer_end(task_indx_type task_indx)
{

  return KAL_TRUE;
}

/*************************************************************************
* FUNCTION
*  tst_file_transferrer_main
*
* DESCRIPTION
*  This function implements tst task's entry function
*
* PARAMETERS
*
* RETURNS
*  None
*
* GLOBALS AFFECTED
*
*************************************************************************/

void tst_file_transferrer_main( task_entry_struct * task_entry_ptr )
{
  kal_uint32  event_group;
  kal_uint32 b_write_version = 0;
        
  // decide the tst output mode  
  #ifdef __SMART_PHONE_MODEM__
    TST_OUTPUT_MODE = 2;  //enhance QA's debug easiness
  #endif  //__SMART_PHONE_MODEM__
  
  tst_file_set_log2SD_option();   
  tst_nvram_statistic_handler(NVRAM_READ); //read statistic
  
  while (1){
    //wait for event to indicate if Transferrer needs to take the action
    kal_retrieve_eg_events(  tst_event_group,
                             TST_EVENT_OPEN_FILE | TST_EVENT_WRITE_CREATE_TO_FILE | TST_EVENT_WRITE_TO_FILE | TST_EVENT_LGA_LOG2FILE_REQ,
                             KAL_OR_CONSUME,
                             &event_group,
                             KAL_SUSPEND);
            
    //switch the event cases
    if (TST_EVENT_OPEN_FILE & event_group)
    {  //open file to write
      tst_file_open_file_to_write();
      
       //indicate the file has created and opened
      kal_set_eg_events(tst_event_group, TST_EVENT_OPEN_FILE_OK, KAL_OR);
    }
    else if (TST_EVENT_WRITE_CREATE_TO_FILE & event_group){  
      //write to file and create a new file      
      tst_file_dump_create_file();
      
      //indicate the actions complete
      kal_set_eg_events(tst_event_group, TST_EVENT_WRITE_CREATE_TO_FILE_OK, KAL_OR);      
    }
    else if (TST_EVENT_WRITE_TO_FILE & event_group){
      //write to file
      tst_file_dump_file();
      
      //indicate the action completes
      kal_set_eg_events(tst_event_group, TST_EVENT_WRITE_TO_FILE_OK, KAL_OR);      
    }
    #if defined(__LOGACC_ENABLE__) && !defined(UNIT_TEST) 
    else if (TST_EVENT_LGA_LOG2FILE_REQ & event_group)
    {
      tst_file_write_logacc_logs();
    }
    #endif  //#if defined(__LOGACC_ENABLE__) && !defined(UNIT_TEST) 
    
    //output the version info
    if (!b_write_version)
    {
      tst_file_write_verno_to_file();
      b_write_version = 1;
    }
    
    //Clean Up
		{
		  //Update the disk size
		  {
		    static kal_uint32 tst_file_disk_check_interval = 0;  
		    if (tst_file_disk_check_interval>TST_FILE_DISK_CHECK_PERIOD)
		    {
		      tst_file_get_disk_phy_space(tst_dump_info.cDriveLetter);
		      tst_file_disk_check_interval = 0;
		    }
		    else
		      ++tst_file_disk_check_interval;
		  }  
		}                                      
  }  //end of while(1)
}


/*************************************************************************
* FUNCTION                                                            
*  tst_file_open_file_to_write
*
* DESCRIPTION                                                           
*   open a file and prepare for writing
*
* PARAMETERS
*  None
* 
*
* RETURNS
*  None
*
*
*****************************************************************************/
#ifdef __SMART_PHONE_MODEM__
  kal_char error_msg_str[32]; //debug
#endif  //#ifdef __SMART_PHONE_MODEM__
void tst_file_open_file_to_write(void)
{
  kal_char driveLetter;  
  FS_HANDLE  fHandle;
 
   if (tst_dump_info.tst_write2_sd_option == TST_Write2File_None)  return;   
 
  tst_dump_info.bHeadOfOnePacket = KAL_FALSE;
  tst_dump_info.bAssertForFull = KAL_FALSE;
  tst_dump_info.nOmitPacketCount = 0;
        
  //if(stack_query_boot_mode() != NORMAL_BOOT) 
#if defined(__SMART_PHONE_MODEM__) 
  if (tst_ft_mode == KAL_TRUE)  
#else //#if defined(__SMART_PHONE_MODEM__) 
  if(stack_query_boot_mode() != NORMAL_BOOT) 
#endif  //#if defined(__SMART_PHONE_MODEM__) 
  {  
    #if defined(__SMART_PHONE_MODEM__)    
      //There is some unknow state while booting
      sprintf(error_msg_str, "Boot mode:%d", (kal_uint32)stack_query_boot_mode());    
      tst_sys_trace(error_msg_str);              
    #endif  //#if defined(__SMART_PHONE_MODEM__) 
      
    return;        
  }    
  
  if (tst_dump_info.buffer == NULL || tst_dump_info.L1Buffer == NULL)
  {  
    tst_err_log_to_file = ERR_ALLOC_MEM;
    goto FAIL_EXIT;
  }

  //1. check if removable dis exits
  driveLetter = FS_GetDrive(FS_DRIVE_V_REMOVABLE, 1, 0);
  if (driveLetter <67 || driveLetter > 72)
  { 
    #ifdef __SMART_PHONE_MODEM__       
      sprintf(error_msg_str, "Boot mode:%d", (kal_uint32)driveLetter);    
      tst_sys_trace(error_msg_str);   
    #endif  //#ifdef __SMART_PHONE_MODEM__
    return;
  }
  tst_dump_info.cDriveLetter = driveLetter;
  
  {//2. query the vacancy
    kal_bool res = tst_file_get_disk_phy_space(driveLetter);
    if (!res){goto FAIL_EXIT;}
  }//2. end of querying the vacancy
   
  //3. create the file X:\pslog\log??.dmp  
  fHandle = tst_file_create_file();  //create a new file
  
  if (fHandle < 0) {
    goto FAIL_EXIT;
  }//failed to open or create the file
      
  tst_dump_info.nDiskFreeSpace -= TST_MAX_LOG_SIZE_FOR_SINGLE_FILE;
  tst_dump_info.nFileFreeSpace = TST_MAX_LOG_SIZE_FOR_SINGLE_FILE - (1<<12); //4k for buffer
  tst_dump_info.nCommitCountDown = TST_COMMIT_BATCH;  
  tst_err_log_to_file = NO_LOG_ERROR;
  return;
  
FAIL_EXIT:  
  tst_dump_info.tst_write2_sd_option = TST_Write2File_None;
  return;
}


/*************************************************************************
* FUNCTION                                                            
*  tst_file_write_to_file
*
* DESCRIPTION                                                           
*   write data to the log file
*
* PARAMETERS
*  None
* 
*
* RETURNS
*  None
*
*
*****************************************************************************/
kal_bool tst_file_write_file(kal_uint8 *buffer, kal_uint32 length)
{
  kal_int32 res;
  kal_uint32 written_bytes;
  //write and commit
  
  if (length == 0) return KAL_TRUE;
  
  #if !defined(__SMART_PHONE_MODEM__)
  res = FS_Extend(tst_dump_info.fHandle, length);  
  
  if (FS_NO_ERROR != res)
  {
    tst_err_log_to_file = ERR_EXTEND;
    goto FAIL_EXIT;
  }
  #endif  //#if !defined(__SMART_PHONE_MODEM__)
    
  res = FS_Write(tst_dump_info.fHandle, tst_dump_info.buffer, length, &written_bytes);

  if (FS_NO_ERROR != res)
  {
    tst_err_log_to_file = ERR_WRITE;
    goto FAIL_EXIT;
  }
  
  tst_dump_info.nCommitCountDown--;
  if (tst_dump_info.nCommitCountDown == 0)
  {
    tst_dump_info.nCommitCountDown = TST_COMMIT_BATCH;

    #if !defined(__SMART_PHONE_MODEM__)
      // flush the FS buffer every nCommitCountDown times
      res = FS_Commit(tst_dump_info.fHandle);
      
      if (FS_NO_ERROR != res)
      {
        tst_err_log_to_file = ERR_COMMIT;
        goto FAIL_EXIT;
      }
    #endif  //#if !defined(__SMART_PHONE_MODEM__)
  }
  
  return KAL_TRUE;
  
FAIL_EXIT:    
  tst_dump_info.tst_write2_sd_option = TST_Write2File_None;
  return KAL_FALSE;
}

/*************************************************************************
* FUNCTION                                                            
*  tst_file_dump_create_file
*
* DESCRIPTION                                                           
*   write logs to the file. After the file is full, create a new file
*
* PARAMETERS
*  None
* 
*
* RETURNS
* 
*
*
*****************************************************************************/

void tst_file_dump_create_file(void)
{    
  FS_HANDLE fHandle;
  kal_int32 res;
  kal_bool  bRet;

  //move logs from the buffer to the file
  bRet = tst_file_write_file(tst_dump_info.buffer, tst_dump_info.nBufferPtr);    
  if (!bRet) goto FAIL_EXIT;

  tst_dump_info.nBufferPtr = 0;
  
  res = FS_Close(tst_dump_info.fHandle);
  if (res < 0)
  {
    tst_err_log_to_file = ERR_CLOSE;
    goto FAIL_EXIT;
  }
  
  if (tst_dump_info.nDiskFreeSpace < TST_FILE_MIN_DISK_SIZE ) //128kBytes as minimal size
  {
    tst_err_log_to_file = DISK_FULL;
    goto FAIL_EXIT;
  }
  tst_dump_info.fHandle = 0;
  
  fHandle = tst_file_create_file();  //create a new file
  if (fHandle < 0) //failed to open or create the file
  {
    goto FAIL_EXIT;
  }
     
  return;
  
FAIL_EXIT:

  return;
}

/*************************************************************************
* FUNCTION                                                            
*  tst_file_dump_file
*
* DESCRIPTION                                                           
*   write logs to the file.
*
* PARAMETERS
*  None
* 
*
* RETURNS
* 
*
*
*****************************************************************************/

void tst_file_dump_file(void)
{
  kal_bool bRet = tst_file_write_file(tst_dump_info.buffer, TST_FSWRITE_BUFFER_SIZE);
  
  if (!bRet)
  {
    tst_err_log_to_file   = ERR_WRITE;    
  }
  
}

/*************************************************************************
* FUNCTION                                                            
*  tst_file_create_file
*
* DESCRIPTION                                                           
*   create and open the new file according to the current time
*
* PARAMETERS
*  None
* 
*
* RETURNS
*  FS_HANDLE: the file handle of the created file
*
*
*****************************************************************************/

FS_HANDLE tst_file_create_file(void)
{
  WCHAR strFSName[36];//i.e. X:\PSLog\00000.dmp
  FS_HANDLE  fHandle;
       
  //create/open the folder "X:\PSLog\"   
  kal_wsprintf(strFSName, "%c:\\PSLog\\", tst_dump_info.cDriveLetter);
  FS_CreateDir(strFSName);
    
  #if !defined(__SMART_PHONE_MODEM__)
  {
    RTC_CTRL_GET_TIME_T rtc_time;
    DCL_HANDLE rtc_handler;
    
    rtc_handler = DclRTC_Open(DCL_RTC,FLAGS_NONE);
    DclRTC_Control(rtc_handler, RTC_CMD_GET_TIME, (DCL_CTRL_DATA_T *)&rtc_time); // New API with CMD & DATA 

    //create/open the file
    kal_wsprintf(strFSName, "%c:\\PSLog\\%d-%d-%d_%d-%d-%d.dmp", tst_dump_info.cDriveLetter,
               rtc_time.u1Year + 2000,
               rtc_time.u1Mon,
               rtc_time.u1Day,
               rtc_time.u1Hour,
               rtc_time.u1Min,
               rtc_time.u1Sec
             );
    kal_wsprintf(tst_dump_info.strAssertFolderName, 
             "%c:\\PSLog\\%d-%d-%d_%d-%d-%d.files\\", tst_dump_info.cDriveLetter,
               rtc_time.u1Year + 2000,
               rtc_time.u1Mon,
               rtc_time.u1Day,
               rtc_time.u1Hour,
               rtc_time.u1Min,
               rtc_time.u1Sec
             );
  }
  #else //#if !define(__SMART_PHONE_MODEM__)   
  {     
    kal_uint32 tick;     
    
    kal_get_time(&tick);
    //create/open the file
    kal_wsprintf(strFSName, "%c:\\PSLog\\%d.dmp", tst_dump_info.cDriveLetter,tick);
    kal_wsprintf(tst_dump_info.strAssertFolderName, 
               "%c:\\PSLog\\%d.files\\", tst_dump_info.cDriveLetter,tick);
  }
  #endif  //#if !define(__SMART_PHONE_MODEM__)

  fHandle = FS_Open(strFSName, FS_CREATE_ALWAYS); //overwrite it if if has existed
  
  if (fHandle < 0)
  {  //error openning the file
    goto FAIL_EXIT;
  }
  {
    //write the header 
    kal_uint32 version = 0x02;
    kal_mem_cpy(tst_dump_info.buffer, (kal_uint8*)&version, 4);
    tst_dump_info.nBufferPtr = 4;  
      
    tst_dump_info.fHandle = fHandle;
  }
  return fHandle;
  
FAIL_EXIT:  
  tst_err_log_to_file = ERR_OPEN;  
  tst_dump_info.tst_write2_sd_option = TST_Write2File_None;
  return -1;
}

//0: Not ready, 1:ok
kal_uint32 tst_file_wait_data_card_for_ready(void)
{
#ifdef __USB_MODEM_CARD_SUPPORT__  
  if (tst_dump_info.tst_write2_sd_option == TST_Write2File_None)
    return 0;
  else
  {
    kal_uint32 event_group;
    
    kal_retrieve_eg_events(  tft_event_group,
          TFT_EVENT_SD_CARD_READY,
          KAL_OR_CONSUME,
          &event_group,
          KAL_SUSPEND);
  }
#endif  //#ifdef __USB_MODEM_CARD_SUPPORT__  
  
  return 1;
}


kal_bool tst_file_get_disk_phy_space(kal_char driveLetter)
{
	FS_DiskInfo diskInfo;
	WCHAR strFSName[8];
	kal_uint32 totalFreeSpace;
	
	kal_wsprintf(strFSName, "%c:\\", driveLetter);
	//FAT document: only the first time calling for a drive is time-consuming.
	if (0 > FS_GetDiskInfo(strFSName, &diskInfo, FS_DI_BASIC_INFO|FS_DI_FREE_SPACE))
	{//Failed for this drive, take it not exist
  	 tst_err_log_to_file = NO_CARD;
  	 return KAL_FALSE;
	}  

  //calculate for the free space
  /*total disk size could be bigger than 2G (kal_int32) or 4G (kal_uint32)*/
  totalFreeSpace =  (diskInfo.BytesPerSector * 
                                diskInfo.SectorsPerCluster / 1024) *
                                diskInfo.FreeClusters; //in unit of KBytes, to prevent it exceed kal_int32

  if (totalFreeSpace > (1<<20))
  {//if the free size > 1GBytes, just bookkeep it as 1G
    	totalFreeSpace = (1<<30);
  }
  else
  {
    	totalFreeSpace *= 1024;
  }
 
  if (totalFreeSpace < TST_MAX_LOG_SIZE_FOR_SINGLE_FILE)
  {
    tst_err_log_to_file = DISK_FULL;
    return KAL_FALSE;
  }
  
  tst_dump_info.nDiskFreeSpace = totalFreeSpace;
  
  return KAL_TRUE;
}


#else //__TST_WRITE_TO_FILE__

#pragma arm section code= "PRIMARY_ROCODE" rwdata = "PRIMARY_RW" , rodata = "PRIMARY_RODATA" , zidata = "PRIMARY_ZI" 
kal_bool tst_file_transferrer_create(comptask_handler_struct **handle)
{
  return KAL_FALSE;  
}

#endif //__TST_WRITE_TO_FILE__