DcTrackerBase.java revision 876763e93ad0fa8006d290cc122f12d5e614efa2
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.internal.telephony.dataconnection; 18 19import android.app.AlarmManager; 20import android.app.PendingIntent; 21import android.content.BroadcastReceiver; 22import android.content.ContentResolver; 23import android.content.Context; 24import android.content.Intent; 25import android.content.IntentFilter; 26import android.content.SharedPreferences; 27import android.database.ContentObserver; 28import android.net.LinkCapabilities; 29import android.net.LinkProperties; 30import android.net.NetworkInfo; 31import android.net.TrafficStats; 32import android.net.wifi.WifiManager; 33import android.os.AsyncResult; 34import android.os.Build; 35import android.os.Bundle; 36import android.os.Handler; 37import android.os.HandlerThread; 38import android.os.Message; 39import android.os.Messenger; 40import android.os.SystemClock; 41import android.os.SystemProperties; 42import android.preference.PreferenceManager; 43import android.provider.Settings; 44import android.provider.Settings.SettingNotFoundException; 45import android.telephony.TelephonyManager; 46import android.text.TextUtils; 47import android.util.EventLog; 48import android.telephony.Rlog; 49 50import com.android.internal.R; 51import com.android.internal.telephony.DctConstants; 52import com.android.internal.telephony.EventLogTags; 53import com.android.internal.telephony.Phone; 54import com.android.internal.telephony.PhoneBase; 55import com.android.internal.telephony.PhoneConstants; 56import com.android.internal.telephony.uicc.IccRecords; 57import com.android.internal.telephony.uicc.UiccController; 58import com.android.internal.util.AsyncChannel; 59 60import java.io.FileDescriptor; 61import java.io.PrintWriter; 62import java.util.ArrayList; 63import java.util.HashMap; 64import java.util.Map.Entry; 65import java.util.Set; 66import java.util.concurrent.ConcurrentHashMap; 67import java.util.concurrent.atomic.AtomicInteger; 68import java.util.concurrent.atomic.AtomicReference; 69 70/** 71 * {@hide} 72 */ 73public abstract class DcTrackerBase extends Handler { 74 protected static final boolean DBG = true; 75 protected static final boolean VDBG = false; // STOPSHIP if true 76 protected static final boolean VDBG_STALL = true; // STOPSHIP if true 77 protected static final boolean RADIO_TESTS = false; 78 79 /** 80 * Constants for the data connection activity: 81 * physical link down/up 82 */ 83 protected static final int DATA_CONNECTION_ACTIVE_PH_LINK_INACTIVE = 0; 84 protected static final int DATA_CONNECTION_ACTIVE_PH_LINK_DOWN = 1; 85 protected static final int DATA_CONNECTION_ACTIVE_PH_LINK_UP = 2; 86 87 /** Delay between APN attempts. 88 Note the property override mechanism is there just for testing purpose only. */ 89 protected static final int APN_DELAY_DEFAULT_MILLIS = 20000; 90 91 /** Delay between APN attempts when in fail fast mode */ 92 protected static final int APN_FAIL_FAST_DELAY_DEFAULT_MILLIS = 3000; 93 94 AlarmManager mAlarmManager; 95 96 protected Object mDataEnabledLock = new Object(); 97 98 // responds to the setInternalDataEnabled call - used internally to turn off data 99 // for example during emergency calls 100 protected boolean mInternalDataEnabled = true; 101 102 // responds to public (user) API to enable/disable data use 103 // independent of mInternalDataEnabled and requests for APN access 104 // persisted 105 protected boolean mUserDataEnabled = true; 106 107 // TODO: move away from static state once 5587429 is fixed. 108 protected static boolean sPolicyDataEnabled = true; 109 110 private boolean[] mDataEnabled = new boolean[DctConstants.APN_NUM_TYPES]; 111 112 private int mEnabledCount = 0; 113 114 /* Currently requested APN type (TODO: This should probably be a parameter not a member) */ 115 protected String mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT; 116 117 /** Retry configuration: A doubling of retry times from 5secs to 30minutes */ 118 protected static final String DEFAULT_DATA_RETRY_CONFIG = "default_randomization=2000," 119 + "5000,10000,20000,40000,80000:5000,160000:5000," 120 + "320000:5000,640000:5000,1280000:5000,1800000:5000"; 121 122 /** Retry configuration for secondary networks: 4 tries in 20 sec */ 123 protected static final String SECONDARY_DATA_RETRY_CONFIG = 124 "max_retries=3, 5000, 5000, 5000"; 125 126 /** Slow poll when attempting connection recovery. */ 127 protected static final int POLL_NETSTAT_SLOW_MILLIS = 5000; 128 /** Default max failure count before attempting to network re-registration. */ 129 protected static final int DEFAULT_MAX_PDP_RESET_FAIL = 3; 130 131 /** 132 * After detecting a potential connection problem, this is the max number 133 * of subsequent polls before attempting recovery. 134 */ 135 protected static final int NO_RECV_POLL_LIMIT = 24; 136 // 1 sec. default polling interval when screen is on. 137 protected static final int POLL_NETSTAT_MILLIS = 1000; 138 // 10 min. default polling interval when screen is off. 139 protected static final int POLL_NETSTAT_SCREEN_OFF_MILLIS = 1000*60*10; 140 // 2 min for round trip time 141 protected static final int POLL_LONGEST_RTT = 120 * 1000; 142 // Default sent packets without ack which triggers initial recovery steps 143 protected static final int NUMBER_SENT_PACKETS_OF_HANG = 10; 144 // how long to wait before switching back to default APN 145 protected static final int RESTORE_DEFAULT_APN_DELAY = 1 * 60 * 1000; 146 // system property that can override the above value 147 protected static final String APN_RESTORE_DELAY_PROP_NAME = "android.telephony.apn-restore"; 148 // represents an invalid IP address 149 protected static final String NULL_IP = "0.0.0.0"; 150 151 // Default for the data stall alarm while non-aggressive stall detection 152 protected static final int DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS_DEFAULT = 1000 * 60 * 6; 153 // Default for the data stall alarm for aggressive stall detection 154 protected static final int DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS_DEFAULT = 1000 * 60; 155 // If attempt is less than this value we're doing first level recovery 156 protected static final int DATA_STALL_NO_RECV_POLL_LIMIT = 1; 157 // Tag for tracking stale alarms 158 protected static final String DATA_STALL_ALARM_TAG_EXTRA = "data.stall.alram.tag"; 159 160 protected static final boolean DATA_STALL_SUSPECTED = true; 161 protected static final boolean DATA_STALL_NOT_SUSPECTED = false; 162 163 protected String RADIO_RESET_PROPERTY = "gsm.radioreset"; 164 165 protected static final String INTENT_RECONNECT_ALARM = 166 "com.android.internal.telephony.data-reconnect"; 167 protected static final String INTENT_RECONNECT_ALARM_EXTRA_TYPE = "reconnect_alarm_extra_type"; 168 protected static final String INTENT_RECONNECT_ALARM_EXTRA_REASON = 169 "reconnect_alarm_extra_reason"; 170 171 protected static final String INTENT_RESTART_TRYSETUP_ALARM = 172 "com.android.internal.telephony.data-restart-trysetup"; 173 protected static final String INTENT_RESTART_TRYSETUP_ALARM_EXTRA_TYPE = 174 "restart_trysetup_alarm_extra_type"; 175 176 protected static final String INTENT_DATA_STALL_ALARM = 177 "com.android.internal.telephony.data-stall"; 178 179 180 181 protected static final String DEFALUT_DATA_ON_BOOT_PROP = "net.def_data_on_boot"; 182 183 protected DcTesterFailBringUpAll mDcTesterFailBringUpAll; 184 protected DcController mDcc; 185 186 // member variables 187 protected PhoneBase mPhone; 188 protected UiccController mUiccController; 189 protected AtomicReference<IccRecords> mIccRecords = new AtomicReference<IccRecords>(); 190 protected DctConstants.Activity mActivity = DctConstants.Activity.NONE; 191 protected DctConstants.State mState = DctConstants.State.IDLE; 192 protected Handler mDataConnectionTracker = null; 193 194 protected long mTxPkts; 195 protected long mRxPkts; 196 protected int mNetStatPollPeriod; 197 protected boolean mNetStatPollEnabled = false; 198 199 protected TxRxSum mDataStallTxRxSum = new TxRxSum(0, 0); 200 // Used to track stale data stall alarms. 201 protected int mDataStallAlarmTag = (int) SystemClock.elapsedRealtime(); 202 // The current data stall alarm intent 203 protected PendingIntent mDataStallAlarmIntent = null; 204 // Number of packets sent since the last received packet 205 protected long mSentSinceLastRecv; 206 // Controls when a simple recovery attempt it to be tried 207 protected int mNoRecvPollCount = 0; 208 // Refrence counter for enabling fail fast 209 protected static int sEnableFailFastRefCounter = 0; 210 // True if data stall detection is enabled 211 protected volatile boolean mDataStallDetectionEnabled = true; 212 213 protected volatile boolean mFailFast = false; 214 215 // True when in voice call 216 protected boolean mInVoiceCall = false; 217 218 // wifi connection status will be updated by sticky intent 219 protected boolean mIsWifiConnected = false; 220 221 /** Intent sent when the reconnect alarm fires. */ 222 protected PendingIntent mReconnectIntent = null; 223 224 /** CID of active data connection */ 225 protected int mCidActive; 226 227 // When false we will not auto attach and manually attaching is required. 228 protected boolean mAutoAttachOnCreation = false; 229 230 // State of screen 231 // (TODO: Reconsider tying directly to screen, maybe this is 232 // really a lower power mode") 233 protected boolean mIsScreenOn = true; 234 235 /** Allows the generation of unique Id's for DataConnection objects */ 236 protected AtomicInteger mUniqueIdGenerator = new AtomicInteger(0); 237 238 /** The data connections. */ 239 protected HashMap<Integer, DataConnection> mDataConnections = 240 new HashMap<Integer, DataConnection>(); 241 242 /** The data connection async channels */ 243 protected HashMap<Integer, DcAsyncChannel> mDataConnectionAcHashMap = 244 new HashMap<Integer, DcAsyncChannel>(); 245 246 /** Convert an ApnType string to Id (TODO: Use "enumeration" instead of String for ApnType) */ 247 protected HashMap<String, Integer> mApnToDataConnectionId = 248 new HashMap<String, Integer>(); 249 250 /** Phone.APN_TYPE_* ===> ApnContext */ 251 protected ConcurrentHashMap<String, ApnContext> mApnContexts = 252 new ConcurrentHashMap<String, ApnContext>(); 253 254 /* Currently active APN */ 255 protected ApnSetting mActiveApn; 256 257 /** allApns holds all apns */ 258 protected ArrayList<ApnSetting> mAllApnSettings = null; 259 260 /** preferred apn */ 261 protected ApnSetting mPreferredApn = null; 262 263 /** Is packet service restricted by network */ 264 protected boolean mIsPsRestricted = false; 265 266 /* Once disposed dont handle any messages */ 267 protected boolean mIsDisposed = false; 268 269 protected ContentResolver mResolver; 270 271 protected BroadcastReceiver mIntentReceiver = new BroadcastReceiver () 272 { 273 @Override 274 public void onReceive(Context context, Intent intent) 275 { 276 String action = intent.getAction(); 277 if (DBG) log("onReceive: action=" + action); 278 if (action.equals(Intent.ACTION_SCREEN_ON)) { 279 mIsScreenOn = true; 280 stopNetStatPoll(); 281 startNetStatPoll(); 282 restartDataStallAlarm(); 283 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { 284 mIsScreenOn = false; 285 stopNetStatPoll(); 286 startNetStatPoll(); 287 restartDataStallAlarm(); 288 } else if (action.startsWith(INTENT_RECONNECT_ALARM)) { 289 if (DBG) log("Reconnect alarm. Previous state was " + mState); 290 onActionIntentReconnectAlarm(intent); 291 } else if (action.startsWith(INTENT_RESTART_TRYSETUP_ALARM)) { 292 if (DBG) log("Restart trySetup alarm"); 293 onActionIntentRestartTrySetupAlarm(intent); 294 } else if (action.equals(INTENT_DATA_STALL_ALARM)) { 295 onActionIntentDataStallAlarm(intent); 296 } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { 297 final android.net.NetworkInfo networkInfo = (NetworkInfo) 298 intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); 299 mIsWifiConnected = (networkInfo != null && networkInfo.isConnected()); 300 if (DBG) log("NETWORK_STATE_CHANGED_ACTION: mIsWifiConnected=" + mIsWifiConnected); 301 } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { 302 final boolean enabled = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 303 WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_ENABLED; 304 305 if (!enabled) { 306 // when WiFi got disabled, the NETWORK_STATE_CHANGED_ACTION 307 // quit and won't report disconnected until next enabling. 308 mIsWifiConnected = false; 309 } 310 if (DBG) log("WIFI_STATE_CHANGED_ACTION: enabled=" + enabled 311 + " mIsWifiConnected=" + mIsWifiConnected); 312 } 313 } 314 }; 315 316 private Runnable mPollNetStat = new Runnable() 317 { 318 @Override 319 public void run() { 320 updateDataActivity(); 321 322 if (mIsScreenOn) { 323 mNetStatPollPeriod = Settings.Global.getInt(mResolver, 324 Settings.Global.PDP_WATCHDOG_POLL_INTERVAL_MS, POLL_NETSTAT_MILLIS); 325 } else { 326 mNetStatPollPeriod = Settings.Global.getInt(mResolver, 327 Settings.Global.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS, 328 POLL_NETSTAT_SCREEN_OFF_MILLIS); 329 } 330 331 if (mNetStatPollEnabled) { 332 mDataConnectionTracker.postDelayed(this, mNetStatPollPeriod); 333 } 334 } 335 }; 336 337 private class DataRoamingSettingObserver extends ContentObserver { 338 339 public DataRoamingSettingObserver(Handler handler, Context context) { 340 super(handler); 341 mResolver = context.getContentResolver(); 342 } 343 344 public void register() { 345 mResolver.registerContentObserver( 346 Settings.Global.getUriFor(Settings.Global.DATA_ROAMING), false, this); 347 } 348 349 public void unregister() { 350 mResolver.unregisterContentObserver(this); 351 } 352 353 @Override 354 public void onChange(boolean selfChange) { 355 // already running on mPhone handler thread 356 if (mPhone.getServiceState().getRoaming()) { 357 sendMessage(obtainMessage(DctConstants.EVENT_ROAMING_ON)); 358 } 359 } 360 } 361 private final DataRoamingSettingObserver mDataRoamingSettingObserver; 362 363 /** 364 * The Initial MaxRetry sent to a DataConnection as a parameter 365 * to DataConnectionAc.bringUp. This value can be defined at compile 366 * time using the SystemProperty Settings.Global.DCT_INITIAL_MAX_RETRY 367 * and at runtime using gservices to change Settings.Global.DCT_INITIAL_MAX_RETRY. 368 */ 369 private static final int DEFAULT_MDC_INITIAL_RETRY = 1; 370 protected int getInitialMaxRetry() { 371 if (mFailFast) { 372 return 0; 373 } 374 // Get default value from system property or use DEFAULT_MDC_INITIAL_RETRY 375 int value = SystemProperties.getInt( 376 Settings.Global.MDC_INITIAL_MAX_RETRY, DEFAULT_MDC_INITIAL_RETRY); 377 378 // Check if its been overridden 379 return Settings.Global.getInt(mResolver, 380 Settings.Global.MDC_INITIAL_MAX_RETRY, value); 381 } 382 383 /** 384 * Maintain the sum of transmit and receive packets. 385 * 386 * The packet counts are initialized and reset to -1 and 387 * remain -1 until they can be updated. 388 */ 389 public class TxRxSum { 390 public long txPkts; 391 public long rxPkts; 392 393 public TxRxSum() { 394 reset(); 395 } 396 397 public TxRxSum(long txPkts, long rxPkts) { 398 this.txPkts = txPkts; 399 this.rxPkts = rxPkts; 400 } 401 402 public TxRxSum(TxRxSum sum) { 403 txPkts = sum.txPkts; 404 rxPkts = sum.rxPkts; 405 } 406 407 public void reset() { 408 txPkts = -1; 409 rxPkts = -1; 410 } 411 412 @Override 413 public String toString() { 414 return "{txSum=" + txPkts + " rxSum=" + rxPkts + "}"; 415 } 416 417 public void updateTxRxSum() { 418 this.txPkts = TrafficStats.getMobileTcpTxPackets(); 419 this.rxPkts = TrafficStats.getMobileTcpRxPackets(); 420 } 421 } 422 423 protected void onActionIntentReconnectAlarm(Intent intent) { 424 String reason = intent.getStringExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON); 425 String apnType = intent.getStringExtra(INTENT_RECONNECT_ALARM_EXTRA_TYPE); 426 427 ApnContext apnContext = mApnContexts.get(apnType); 428 429 if (DBG) { 430 log("onActionIntentReconnectAlarm: mState=" + mState + " reason=" + reason + 431 " apnType=" + apnType + " apnContext=" + apnContext + 432 " mDataConnectionAsyncChannels=" + mDataConnectionAcHashMap); 433 } 434 435 if ((apnContext != null) && (apnContext.isEnabled())) { 436 apnContext.setReason(reason); 437 DctConstants.State apnContextState = apnContext.getState(); 438 if (DBG) { 439 log("onActionIntentReconnectAlarm: apnContext state=" + apnContextState); 440 } 441 if ((apnContextState == DctConstants.State.FAILED) 442 || (apnContextState == DctConstants.State.IDLE)) { 443 if (DBG) { 444 log("onActionIntentReconnectAlarm: state is FAILED|IDLE, disassociate"); 445 } 446 DcAsyncChannel dcac = apnContext.getDcAc(); 447 if (dcac != null) { 448 dcac.tearDown(apnContext, "", null); 449 } 450 apnContext.setDataConnectionAc(null); 451 apnContext.setState(DctConstants.State.IDLE); 452 } else { 453 if (DBG) log("onActionIntentReconnectAlarm: keep associated"); 454 } 455 // TODO: IF already associated should we send the EVENT_TRY_SETUP_DATA??? 456 sendMessage(obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, apnContext)); 457 458 apnContext.setReconnectIntent(null); 459 } 460 } 461 462 protected void onActionIntentRestartTrySetupAlarm(Intent intent) { 463 String apnType = intent.getStringExtra(INTENT_RESTART_TRYSETUP_ALARM_EXTRA_TYPE); 464 ApnContext apnContext = mApnContexts.get(apnType); 465 if (DBG) { 466 log("onActionIntentRestartTrySetupAlarm: mState=" + mState + 467 " apnType=" + apnType + " apnContext=" + apnContext + 468 " mDataConnectionAsyncChannels=" + mDataConnectionAcHashMap); 469 } 470 sendMessage(obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, apnContext)); 471 } 472 473 protected void onActionIntentDataStallAlarm(Intent intent) { 474 if (VDBG_STALL) log("onActionIntentDataStallAlarm: action=" + intent.getAction()); 475 Message msg = obtainMessage(DctConstants.EVENT_DATA_STALL_ALARM, 476 intent.getAction()); 477 msg.arg1 = intent.getIntExtra(DATA_STALL_ALARM_TAG_EXTRA, 0); 478 sendMessage(msg); 479 } 480 481 /** 482 * Default constructor 483 */ 484 protected DcTrackerBase(PhoneBase phone) { 485 super(); 486 if (DBG) log("DCT.constructor"); 487 mPhone = phone; 488 mResolver = mPhone.getContext().getContentResolver(); 489 mUiccController = UiccController.getInstance(); 490 mUiccController.registerForIccChanged(this, DctConstants.EVENT_ICC_CHANGED, null); 491 mAlarmManager = 492 (AlarmManager) mPhone.getContext().getSystemService(Context.ALARM_SERVICE); 493 494 495 IntentFilter filter = new IntentFilter(); 496 filter.addAction(Intent.ACTION_SCREEN_ON); 497 filter.addAction(Intent.ACTION_SCREEN_OFF); 498 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); 499 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); 500 filter.addAction(INTENT_DATA_STALL_ALARM); 501 502 mUserDataEnabled = Settings.Global.getInt( 503 mPhone.getContext().getContentResolver(), Settings.Global.MOBILE_DATA, 1) == 1; 504 505 mPhone.getContext().registerReceiver(mIntentReceiver, filter, null, mPhone); 506 507 // This preference tells us 1) initial condition for "dataEnabled", 508 // and 2) whether the RIL will setup the baseband to auto-PS attach. 509 510 mDataEnabled[DctConstants.APN_DEFAULT_ID] = 511 SystemProperties.getBoolean(DEFALUT_DATA_ON_BOOT_PROP,true); 512 if (mDataEnabled[DctConstants.APN_DEFAULT_ID]) { 513 mEnabledCount++; 514 } 515 516 SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mPhone.getContext()); 517 mAutoAttachOnCreation = sp.getBoolean(PhoneBase.DATA_DISABLED_ON_BOOT_KEY, false); 518 519 // Watch for changes to Settings.Global.DATA_ROAMING 520 mDataRoamingSettingObserver = new DataRoamingSettingObserver(mPhone, mPhone.getContext()); 521 mDataRoamingSettingObserver.register(); 522 523 HandlerThread dcHandlerThread = new HandlerThread("DcHandlerThread"); 524 dcHandlerThread.start(); 525 Handler dcHandler = new Handler(dcHandlerThread.getLooper()); 526 mDcc = DcController.makeDcc(mPhone, this, dcHandler); 527 mDcTesterFailBringUpAll = new DcTesterFailBringUpAll(mPhone, dcHandler); 528 } 529 530 public void dispose() { 531 if (DBG) log("DCT.dispose"); 532 for (DcAsyncChannel dcac : mDataConnectionAcHashMap.values()) { 533 dcac.disconnect(); 534 } 535 mDataConnectionAcHashMap.clear(); 536 mIsDisposed = true; 537 mPhone.getContext().unregisterReceiver(mIntentReceiver); 538 mUiccController.unregisterForIccChanged(this); 539 mDataRoamingSettingObserver.unregister(); 540 mDcc.dispose(); 541 mDcTesterFailBringUpAll.dispose(); 542 } 543 544 public DctConstants.Activity getActivity() { 545 return mActivity; 546 } 547 548 public boolean isApnTypeActive(String type) { 549 // TODO: support simultaneous with List instead 550 if (PhoneConstants.APN_TYPE_DUN.equals(type)) { 551 ApnSetting dunApn = fetchDunApn(); 552 if (dunApn != null) { 553 return ((mActiveApn != null) && (dunApn.toString().equals(mActiveApn.toString()))); 554 } 555 } 556 return mActiveApn != null && mActiveApn.canHandleType(type); 557 } 558 559 protected ApnSetting fetchDunApn() { 560 if (SystemProperties.getBoolean("net.tethering.noprovisioning", false)) { 561 log("fetchDunApn: net.tethering.noprovisioning=true ret: null"); 562 return null; 563 } 564 Context c = mPhone.getContext(); 565 String apnData = Settings.Global.getString(c.getContentResolver(), 566 Settings.Global.TETHER_DUN_APN); 567 ApnSetting dunSetting = ApnSetting.fromString(apnData); 568 if (dunSetting != null) { 569 if (VDBG) log("fetchDunApn: global TETHER_DUN_APN dunSetting=" + dunSetting); 570 return dunSetting; 571 } 572 573 apnData = c.getResources().getString(R.string.config_tether_apndata); 574 dunSetting = ApnSetting.fromString(apnData); 575 if (VDBG) log("fetchDunApn: config_tether_apndata dunSetting=" + dunSetting); 576 return dunSetting; 577 } 578 579 public String[] getActiveApnTypes() { 580 String[] result; 581 if (mActiveApn != null) { 582 result = mActiveApn.types; 583 } else { 584 result = new String[1]; 585 result[0] = PhoneConstants.APN_TYPE_DEFAULT; 586 } 587 return result; 588 } 589 590 /** TODO: See if we can remove */ 591 public String getActiveApnString(String apnType) { 592 String result = null; 593 if (mActiveApn != null) { 594 result = mActiveApn.apn; 595 } 596 return result; 597 } 598 599 /** 600 * Modify {@link android.provider.Settings.Global#DATA_ROAMING} value. 601 */ 602 public void setDataOnRoamingEnabled(boolean enabled) { 603 if (getDataOnRoamingEnabled() != enabled) { 604 final ContentResolver resolver = mPhone.getContext().getContentResolver(); 605 Settings.Global.putInt(resolver, Settings.Global.DATA_ROAMING, enabled ? 1 : 0); 606 // will trigger handleDataOnRoamingChange() through observer 607 } 608 } 609 610 /** 611 * Return current {@link android.provider.Settings.Global#DATA_ROAMING} value. 612 */ 613 public boolean getDataOnRoamingEnabled() { 614 try { 615 final ContentResolver resolver = mPhone.getContext().getContentResolver(); 616 return Settings.Global.getInt(resolver, Settings.Global.DATA_ROAMING) != 0; 617 } catch (SettingNotFoundException snfe) { 618 return false; 619 } 620 } 621 622 // abstract methods 623 protected abstract void restartRadio(); 624 protected abstract void log(String s); 625 protected abstract void loge(String s); 626 protected abstract boolean isDataAllowed(); 627 protected abstract boolean isApnTypeAvailable(String type); 628 public abstract DctConstants.State getState(String apnType); 629 protected abstract void setState(DctConstants.State s); 630 protected abstract void gotoIdleAndNotifyDataConnection(String reason); 631 632 protected abstract boolean onTrySetupData(String reason); 633 protected abstract void onRoamingOff(); 634 protected abstract void onRoamingOn(); 635 protected abstract void onRadioAvailable(); 636 protected abstract void onRadioOffOrNotAvailable(); 637 protected abstract void onDataSetupComplete(AsyncResult ar); 638 protected abstract void onDataSetupCompleteError(AsyncResult ar); 639 protected abstract void onDisconnectDone(int connId, AsyncResult ar); 640 protected abstract void onDisconnectDcRetrying(int connId, AsyncResult ar); 641 protected abstract void onVoiceCallStarted(); 642 protected abstract void onVoiceCallEnded(); 643 protected abstract void onCleanUpConnection(boolean tearDown, int apnId, String reason); 644 protected abstract void onCleanUpAllConnections(String cause); 645 public abstract boolean isDataPossible(String apnType); 646 protected abstract void onUpdateIcc(); 647 648 @Override 649 public void handleMessage(Message msg) { 650 switch (msg.what) { 651 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 652 log("DISCONNECTED_CONNECTED: msg=" + msg); 653 DcAsyncChannel dcac = (DcAsyncChannel) msg.obj; 654 mDataConnectionAcHashMap.remove(dcac.getDataConnectionIdSync()); 655 dcac.disconnected(); 656 break; 657 } 658 case DctConstants.EVENT_ENABLE_NEW_APN: 659 onEnableApn(msg.arg1, msg.arg2); 660 break; 661 662 case DctConstants.EVENT_TRY_SETUP_DATA: 663 String reason = null; 664 if (msg.obj instanceof String) { 665 reason = (String) msg.obj; 666 } 667 onTrySetupData(reason); 668 break; 669 670 case DctConstants.EVENT_DATA_STALL_ALARM: 671 onDataStallAlarm(msg.arg1); 672 break; 673 674 case DctConstants.EVENT_ROAMING_OFF: 675 onRoamingOff(); 676 break; 677 678 case DctConstants.EVENT_ROAMING_ON: 679 onRoamingOn(); 680 break; 681 682 case DctConstants.EVENT_RADIO_AVAILABLE: 683 onRadioAvailable(); 684 break; 685 686 case DctConstants.EVENT_RADIO_OFF_OR_NOT_AVAILABLE: 687 onRadioOffOrNotAvailable(); 688 break; 689 690 case DctConstants.EVENT_DATA_SETUP_COMPLETE: 691 mCidActive = msg.arg1; 692 onDataSetupComplete((AsyncResult) msg.obj); 693 break; 694 695 case DctConstants.EVENT_DATA_SETUP_COMPLETE_ERROR: 696 onDataSetupCompleteError((AsyncResult) msg.obj); 697 break; 698 699 case DctConstants.EVENT_DISCONNECT_DONE: 700 log("DataConnectionTracker.handleMessage: EVENT_DISCONNECT_DONE msg=" + msg); 701 onDisconnectDone(msg.arg1, (AsyncResult) msg.obj); 702 break; 703 704 case DctConstants.EVENT_DISCONNECT_DC_RETRYING: 705 log("DataConnectionTracker.handleMessage: EVENT_DISCONNECT_DC_RETRYING msg=" + msg); 706 onDisconnectDcRetrying(msg.arg1, (AsyncResult) msg.obj); 707 break; 708 709 case DctConstants.EVENT_VOICE_CALL_STARTED: 710 onVoiceCallStarted(); 711 break; 712 713 case DctConstants.EVENT_VOICE_CALL_ENDED: 714 onVoiceCallEnded(); 715 break; 716 717 case DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS: { 718 onCleanUpAllConnections((String) msg.obj); 719 break; 720 } 721 case DctConstants.EVENT_CLEAN_UP_CONNECTION: { 722 boolean tearDown = (msg.arg1 == 0) ? false : true; 723 onCleanUpConnection(tearDown, msg.arg2, (String) msg.obj); 724 break; 725 } 726 case DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE: { 727 boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false; 728 onSetInternalDataEnabled(enabled); 729 break; 730 } 731 case DctConstants.EVENT_RESET_DONE: { 732 if (DBG) log("EVENT_RESET_DONE"); 733 onResetDone((AsyncResult) msg.obj); 734 break; 735 } 736 case DctConstants.CMD_SET_USER_DATA_ENABLE: { 737 final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false; 738 if (DBG) log("CMD_SET_USER_DATA_ENABLE enabled=" + enabled); 739 onSetUserDataEnabled(enabled); 740 break; 741 } 742 case DctConstants.CMD_SET_DEPENDENCY_MET: { 743 boolean met = (msg.arg1 == DctConstants.ENABLED) ? true : false; 744 if (DBG) log("CMD_SET_DEPENDENCY_MET met=" + met); 745 Bundle bundle = msg.getData(); 746 if (bundle != null) { 747 String apnType = (String)bundle.get(DctConstants.APN_TYPE_KEY); 748 if (apnType != null) { 749 onSetDependencyMet(apnType, met); 750 } 751 } 752 break; 753 } 754 case DctConstants.CMD_SET_POLICY_DATA_ENABLE: { 755 final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false; 756 onSetPolicyDataEnabled(enabled); 757 break; 758 } 759 case DctConstants.CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: { 760 sEnableFailFastRefCounter += (msg.arg1 == DctConstants.ENABLED) ? 1 : -1; 761 if (DBG) { 762 log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: " 763 + " sEnableFailFastRefCounter=" + sEnableFailFastRefCounter); 764 } 765 if (sEnableFailFastRefCounter < 0) { 766 final String s = "CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: " 767 + "sEnableFailFastRefCounter:" + sEnableFailFastRefCounter + " < 0"; 768 loge(s); 769 sEnableFailFastRefCounter = 0; 770 if (Build.IS_DEBUGGABLE) { 771 throw new RuntimeException(s); 772 } 773 } 774 final boolean enabled = sEnableFailFastRefCounter > 0; 775 if (DBG) { 776 log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: enabled=" + enabled 777 + " sEnableFailFastRefCounter=" + sEnableFailFastRefCounter); 778 } 779 if (mFailFast != enabled) { 780 mFailFast = enabled; 781 mDataStallDetectionEnabled = !enabled; 782 if (mDataStallDetectionEnabled 783 && (getOverallState() == DctConstants.State.CONNECTED) 784 && (!mInVoiceCall || 785 mPhone.getServiceStateTracker() 786 .isConcurrentVoiceAndDataAllowed())) { 787 if (DBG) log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: start data stall"); 788 stopDataStallAlarm(); 789 startDataStallAlarm(DATA_STALL_NOT_SUSPECTED); 790 } else { 791 if (DBG) log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: stop data stall"); 792 stopDataStallAlarm(); 793 } 794 } 795 796 break; 797 } 798 case DctConstants.EVENT_ICC_CHANGED: { 799 onUpdateIcc(); 800 break; 801 } 802 case DctConstants.EVENT_RESTART_RADIO: { 803 restartRadio(); 804 break; 805 } 806 default: 807 Rlog.e("DATA", "Unidentified event msg=" + msg); 808 break; 809 } 810 } 811 812 /** 813 * Report on whether data connectivity is enabled 814 * 815 * @return {@code false} if data connectivity has been explicitly disabled, 816 * {@code true} otherwise. 817 */ 818 public boolean getAnyDataEnabled() { 819 final boolean result; 820 synchronized (mDataEnabledLock) { 821 result = (mInternalDataEnabled && mUserDataEnabled && sPolicyDataEnabled 822 && (mEnabledCount != 0)); 823 } 824 if (!result && DBG) log("getAnyDataEnabled " + result); 825 return result; 826 } 827 828 protected boolean isEmergency() { 829 final boolean result; 830 synchronized (mDataEnabledLock) { 831 result = mPhone.isInEcm() || mPhone.isInEmergencyCall(); 832 } 833 log("isEmergency: result=" + result); 834 return result; 835 } 836 837 protected int apnTypeToId(String type) { 838 if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DEFAULT)) { 839 return DctConstants.APN_DEFAULT_ID; 840 } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_MMS)) { 841 return DctConstants.APN_MMS_ID; 842 } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_SUPL)) { 843 return DctConstants.APN_SUPL_ID; 844 } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DUN)) { 845 return DctConstants.APN_DUN_ID; 846 } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_HIPRI)) { 847 return DctConstants.APN_HIPRI_ID; 848 } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_IMS)) { 849 return DctConstants.APN_IMS_ID; 850 } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_FOTA)) { 851 return DctConstants.APN_FOTA_ID; 852 } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_CBS)) { 853 return DctConstants.APN_CBS_ID; 854 } else { 855 return DctConstants.APN_INVALID_ID; 856 } 857 } 858 859 protected String apnIdToType(int id) { 860 switch (id) { 861 case DctConstants.APN_DEFAULT_ID: 862 return PhoneConstants.APN_TYPE_DEFAULT; 863 case DctConstants.APN_MMS_ID: 864 return PhoneConstants.APN_TYPE_MMS; 865 case DctConstants.APN_SUPL_ID: 866 return PhoneConstants.APN_TYPE_SUPL; 867 case DctConstants.APN_DUN_ID: 868 return PhoneConstants.APN_TYPE_DUN; 869 case DctConstants.APN_HIPRI_ID: 870 return PhoneConstants.APN_TYPE_HIPRI; 871 case DctConstants.APN_IMS_ID: 872 return PhoneConstants.APN_TYPE_IMS; 873 case DctConstants.APN_FOTA_ID: 874 return PhoneConstants.APN_TYPE_FOTA; 875 case DctConstants.APN_CBS_ID: 876 return PhoneConstants.APN_TYPE_CBS; 877 default: 878 log("Unknown id (" + id + ") in apnIdToType"); 879 return PhoneConstants.APN_TYPE_DEFAULT; 880 } 881 } 882 883 public LinkProperties getLinkProperties(String apnType) { 884 int id = apnTypeToId(apnType); 885 886 if (isApnIdEnabled(id)) { 887 DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0); 888 return dcac.getLinkPropertiesSync(); 889 } else { 890 return new LinkProperties(); 891 } 892 } 893 894 public LinkCapabilities getLinkCapabilities(String apnType) { 895 int id = apnTypeToId(apnType); 896 if (isApnIdEnabled(id)) { 897 DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0); 898 return dcac.getLinkCapabilitiesSync(); 899 } else { 900 return new LinkCapabilities(); 901 } 902 } 903 904 // tell all active apns of the current condition 905 protected void notifyDataConnection(String reason) { 906 for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) { 907 if (mDataEnabled[id]) { 908 mPhone.notifyDataConnection(reason, apnIdToType(id)); 909 } 910 } 911 notifyOffApnsOfAvailability(reason); 912 } 913 914 // a new APN has gone active and needs to send events to catch up with the 915 // current condition 916 private void notifyApnIdUpToCurrent(String reason, int apnId) { 917 switch (mState) { 918 case IDLE: 919 break; 920 case RETRYING: 921 case CONNECTING: 922 case SCANNING: 923 mPhone.notifyDataConnection(reason, apnIdToType(apnId), 924 PhoneConstants.DataState.CONNECTING); 925 break; 926 case CONNECTED: 927 case DISCONNECTING: 928 mPhone.notifyDataConnection(reason, apnIdToType(apnId), 929 PhoneConstants.DataState.CONNECTING); 930 mPhone.notifyDataConnection(reason, apnIdToType(apnId), 931 PhoneConstants.DataState.CONNECTED); 932 break; 933 default: 934 // Ignore 935 break; 936 } 937 } 938 939 // since we normally don't send info to a disconnected APN, we need to do this specially 940 private void notifyApnIdDisconnected(String reason, int apnId) { 941 mPhone.notifyDataConnection(reason, apnIdToType(apnId), 942 PhoneConstants.DataState.DISCONNECTED); 943 } 944 945 // disabled apn's still need avail/unavail notificiations - send them out 946 protected void notifyOffApnsOfAvailability(String reason) { 947 if (DBG) log("notifyOffApnsOfAvailability - reason= " + reason); 948 for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) { 949 if (!isApnIdEnabled(id)) { 950 notifyApnIdDisconnected(reason, id); 951 } 952 } 953 } 954 955 public boolean isApnTypeEnabled(String apnType) { 956 if (apnType == null) { 957 return false; 958 } else { 959 return isApnIdEnabled(apnTypeToId(apnType)); 960 } 961 } 962 963 protected synchronized boolean isApnIdEnabled(int id) { 964 if (id != DctConstants.APN_INVALID_ID) { 965 return mDataEnabled[id]; 966 } 967 return false; 968 } 969 970 /** 971 * Ensure that we are connected to an APN of the specified type. 972 * 973 * @param type the APN type (currently the only valid values are 974 * {@link PhoneConstants#APN_TYPE_MMS} and {@link PhoneConstants#APN_TYPE_SUPL}) 975 * @return Success is indicated by {@code Phone.APN_ALREADY_ACTIVE} or 976 * {@code Phone.APN_REQUEST_STARTED}. In the latter case, a 977 * broadcast will be sent by the ConnectivityManager when a 978 * connection to the APN has been established. 979 */ 980 public synchronized int enableApnType(String type) { 981 int id = apnTypeToId(type); 982 if (id == DctConstants.APN_INVALID_ID) { 983 return PhoneConstants.APN_REQUEST_FAILED; 984 } 985 986 if (DBG) { 987 log("enableApnType(" + type + "), isApnTypeActive = " + isApnTypeActive(type) 988 + ", isApnIdEnabled =" + isApnIdEnabled(id) + " and state = " + mState); 989 } 990 991 if (!isApnTypeAvailable(type)) { 992 if (DBG) log("type not available"); 993 return PhoneConstants.APN_TYPE_NOT_AVAILABLE; 994 } 995 996 if (isApnIdEnabled(id)) { 997 return PhoneConstants.APN_ALREADY_ACTIVE; 998 } else { 999 setEnabled(id, true); 1000 } 1001 return PhoneConstants.APN_REQUEST_STARTED; 1002 } 1003 1004 /** 1005 * The APN of the specified type is no longer needed. Ensure that if use of 1006 * the default APN has not been explicitly disabled, we are connected to the 1007 * default APN. 1008 * 1009 * @param type the APN type. The only valid values are currently 1010 * {@link PhoneConstants#APN_TYPE_MMS} and {@link PhoneConstants#APN_TYPE_SUPL}. 1011 * @return Success is indicated by {@code PhoneConstants.APN_ALREADY_ACTIVE} or 1012 * {@code PhoneConstants.APN_REQUEST_STARTED}. In the latter case, a 1013 * broadcast will be sent by the ConnectivityManager when a 1014 * connection to the APN has been disconnected. A {@code 1015 * PhoneConstants.APN_REQUEST_FAILED} is returned if the type parameter is 1016 * invalid or if the apn wasn't enabled. 1017 */ 1018 public synchronized int disableApnType(String type) { 1019 if (DBG) log("disableApnType(" + type + ")"); 1020 int id = apnTypeToId(type); 1021 if (id == DctConstants.APN_INVALID_ID) { 1022 return PhoneConstants.APN_REQUEST_FAILED; 1023 } 1024 if (isApnIdEnabled(id)) { 1025 setEnabled(id, false); 1026 if (isApnTypeActive(PhoneConstants.APN_TYPE_DEFAULT)) { 1027 if (mDataEnabled[DctConstants.APN_DEFAULT_ID]) { 1028 return PhoneConstants.APN_ALREADY_ACTIVE; 1029 } else { 1030 return PhoneConstants.APN_REQUEST_STARTED; 1031 } 1032 } else { 1033 return PhoneConstants.APN_REQUEST_STARTED; 1034 } 1035 } else { 1036 return PhoneConstants.APN_REQUEST_FAILED; 1037 } 1038 } 1039 1040 protected void setEnabled(int id, boolean enable) { 1041 if (DBG) { 1042 log("setEnabled(" + id + ", " + enable + ") with old state = " + mDataEnabled[id] 1043 + " and enabledCount = " + mEnabledCount); 1044 } 1045 Message msg = obtainMessage(DctConstants.EVENT_ENABLE_NEW_APN); 1046 msg.arg1 = id; 1047 msg.arg2 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED); 1048 sendMessage(msg); 1049 } 1050 1051 protected void onEnableApn(int apnId, int enabled) { 1052 if (DBG) { 1053 log("EVENT_APN_ENABLE_REQUEST apnId=" + apnId + ", apnType=" + apnIdToType(apnId) + 1054 ", enabled=" + enabled + ", dataEnabled = " + mDataEnabled[apnId] + 1055 ", enabledCount = " + mEnabledCount + ", isApnTypeActive = " + 1056 isApnTypeActive(apnIdToType(apnId))); 1057 } 1058 if (enabled == DctConstants.ENABLED) { 1059 synchronized (this) { 1060 if (!mDataEnabled[apnId]) { 1061 mDataEnabled[apnId] = true; 1062 mEnabledCount++; 1063 } 1064 } 1065 String type = apnIdToType(apnId); 1066 if (!isApnTypeActive(type)) { 1067 mRequestedApnType = type; 1068 onEnableNewApn(); 1069 } else { 1070 notifyApnIdUpToCurrent(Phone.REASON_APN_SWITCHED, apnId); 1071 } 1072 } else { 1073 // disable 1074 boolean didDisable = false; 1075 synchronized (this) { 1076 if (mDataEnabled[apnId]) { 1077 mDataEnabled[apnId] = false; 1078 mEnabledCount--; 1079 didDisable = true; 1080 } 1081 } 1082 if (didDisable) { 1083 if ((mEnabledCount == 0) || (apnId == DctConstants.APN_DUN_ID)) { 1084 mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT; 1085 onCleanUpConnection(true, apnId, Phone.REASON_DATA_DISABLED); 1086 } 1087 1088 // send the disconnect msg manually, since the normal route wont send 1089 // it (it's not enabled) 1090 notifyApnIdDisconnected(Phone.REASON_DATA_DISABLED, apnId); 1091 if (mDataEnabled[DctConstants.APN_DEFAULT_ID] == true 1092 && !isApnTypeActive(PhoneConstants.APN_TYPE_DEFAULT)) { 1093 // TODO - this is an ugly way to restore the default conn - should be done 1094 // by a real contention manager and policy that disconnects the lower pri 1095 // stuff as enable requests come in and pops them back on as we disable back 1096 // down to the lower pri stuff 1097 mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT; 1098 onEnableNewApn(); 1099 } 1100 } 1101 } 1102 } 1103 1104 /** 1105 * Called when we switch APNs. 1106 * 1107 * mRequestedApnType is set prior to call 1108 * To be overridden. 1109 */ 1110 protected void onEnableNewApn() { 1111 } 1112 1113 /** 1114 * Called when EVENT_RESET_DONE is received so goto 1115 * IDLE state and send notifications to those interested. 1116 * 1117 * TODO - currently unused. Needs to be hooked into DataConnection cleanup 1118 * TODO - needs to pass some notion of which connection is reset.. 1119 */ 1120 protected void onResetDone(AsyncResult ar) { 1121 if (DBG) log("EVENT_RESET_DONE"); 1122 String reason = null; 1123 if (ar.userObj instanceof String) { 1124 reason = (String) ar.userObj; 1125 } 1126 gotoIdleAndNotifyDataConnection(reason); 1127 } 1128 1129 /** 1130 * Prevent mobile data connections from being established, or once again 1131 * allow mobile data connections. If the state toggles, then either tear 1132 * down or set up data, as appropriate to match the new state. 1133 * 1134 * @param enable indicates whether to enable ({@code true}) or disable ( 1135 * {@code false}) data 1136 * @return {@code true} if the operation succeeded 1137 */ 1138 public boolean setInternalDataEnabled(boolean enable) { 1139 if (DBG) 1140 log("setInternalDataEnabled(" + enable + ")"); 1141 1142 Message msg = obtainMessage(DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE); 1143 msg.arg1 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED); 1144 sendMessage(msg); 1145 return true; 1146 } 1147 1148 protected void onSetInternalDataEnabled(boolean enabled) { 1149 synchronized (mDataEnabledLock) { 1150 mInternalDataEnabled = enabled; 1151 if (enabled) { 1152 log("onSetInternalDataEnabled: changed to enabled, try to setup data call"); 1153 onTrySetupData(Phone.REASON_DATA_ENABLED); 1154 } else { 1155 log("onSetInternalDataEnabled: changed to disabled, cleanUpAllConnections"); 1156 cleanUpAllConnections(null); 1157 } 1158 } 1159 } 1160 1161 public void cleanUpAllConnections(String cause) { 1162 Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS); 1163 msg.obj = cause; 1164 sendMessage(msg); 1165 } 1166 1167 public abstract boolean isDisconnected(); 1168 1169 protected void onSetUserDataEnabled(boolean enabled) { 1170 synchronized (mDataEnabledLock) { 1171 final boolean prevEnabled = getAnyDataEnabled(); 1172 if (mUserDataEnabled != enabled) { 1173 mUserDataEnabled = enabled; 1174 Settings.Global.putInt(mPhone.getContext().getContentResolver(), 1175 Settings.Global.MOBILE_DATA, enabled ? 1 : 0); 1176 if (getDataOnRoamingEnabled() == false && 1177 mPhone.getServiceState().getRoaming() == true) { 1178 if (enabled) { 1179 notifyOffApnsOfAvailability(Phone.REASON_ROAMING_ON); 1180 } else { 1181 notifyOffApnsOfAvailability(Phone.REASON_DATA_DISABLED); 1182 } 1183 } 1184 if (prevEnabled != getAnyDataEnabled()) { 1185 if (!prevEnabled) { 1186 onTrySetupData(Phone.REASON_DATA_ENABLED); 1187 } else { 1188 onCleanUpAllConnections(Phone.REASON_DATA_DISABLED); 1189 } 1190 } 1191 } 1192 } 1193 } 1194 1195 protected void onSetDependencyMet(String apnType, boolean met) { 1196 } 1197 1198 protected void onSetPolicyDataEnabled(boolean enabled) { 1199 synchronized (mDataEnabledLock) { 1200 final boolean prevEnabled = getAnyDataEnabled(); 1201 if (sPolicyDataEnabled != enabled) { 1202 sPolicyDataEnabled = enabled; 1203 if (prevEnabled != getAnyDataEnabled()) { 1204 if (!prevEnabled) { 1205 onTrySetupData(Phone.REASON_DATA_ENABLED); 1206 } else { 1207 onCleanUpAllConnections(Phone.REASON_DATA_DISABLED); 1208 } 1209 } 1210 } 1211 } 1212 } 1213 1214 protected String getReryConfig(boolean forDefault) { 1215 int nt = mPhone.getServiceState().getNetworkType(); 1216 1217 if ((nt == TelephonyManager.NETWORK_TYPE_CDMA) || 1218 (nt == TelephonyManager.NETWORK_TYPE_1xRTT) || 1219 (nt == TelephonyManager.NETWORK_TYPE_EVDO_0) || 1220 (nt == TelephonyManager.NETWORK_TYPE_EVDO_A) || 1221 (nt == TelephonyManager.NETWORK_TYPE_EVDO_B) || 1222 (nt == TelephonyManager.NETWORK_TYPE_EHRPD)) { 1223 // CDMA variant 1224 return SystemProperties.get("ro.cdma.data_retry_config"); 1225 } else { 1226 // Use GSM varient for all others. 1227 if (forDefault) { 1228 return SystemProperties.get("ro.gsm.data_retry_config"); 1229 } else { 1230 return SystemProperties.get("ro.gsm.2nd_data_retry_config"); 1231 } 1232 } 1233 } 1234 1235 protected void resetPollStats() { 1236 mTxPkts = -1; 1237 mRxPkts = -1; 1238 mNetStatPollPeriod = POLL_NETSTAT_MILLIS; 1239 } 1240 1241 protected abstract DctConstants.State getOverallState(); 1242 1243 protected void startNetStatPoll() { 1244 if (getOverallState() == DctConstants.State.CONNECTED 1245 && mNetStatPollEnabled == false) { 1246 if (DBG) log("startNetStatPoll"); 1247 resetPollStats(); 1248 mNetStatPollEnabled = true; 1249 mPollNetStat.run(); 1250 } 1251 } 1252 1253 protected void stopNetStatPoll() { 1254 mNetStatPollEnabled = false; 1255 removeCallbacks(mPollNetStat); 1256 if (DBG) log("stopNetStatPoll"); 1257 } 1258 1259 public void updateDataActivity() { 1260 long sent, received; 1261 1262 DctConstants.Activity newActivity; 1263 1264 TxRxSum preTxRxSum = new TxRxSum(mTxPkts, mRxPkts); 1265 TxRxSum curTxRxSum = new TxRxSum(); 1266 curTxRxSum.updateTxRxSum(); 1267 mTxPkts = curTxRxSum.txPkts; 1268 mRxPkts = curTxRxSum.rxPkts; 1269 1270 if (VDBG) { 1271 log("updateDataActivity: curTxRxSum=" + curTxRxSum + " preTxRxSum=" + preTxRxSum); 1272 } 1273 1274 if (mNetStatPollEnabled && (preTxRxSum.txPkts > 0 || preTxRxSum.rxPkts > 0)) { 1275 sent = mTxPkts - preTxRxSum.txPkts; 1276 received = mRxPkts - preTxRxSum.rxPkts; 1277 1278 if (VDBG) 1279 log("updateDataActivity: sent=" + sent + " received=" + received); 1280 if (sent > 0 && received > 0) { 1281 newActivity = DctConstants.Activity.DATAINANDOUT; 1282 } else if (sent > 0 && received == 0) { 1283 newActivity = DctConstants.Activity.DATAOUT; 1284 } else if (sent == 0 && received > 0) { 1285 newActivity = DctConstants.Activity.DATAIN; 1286 } else { 1287 newActivity = (mActivity == DctConstants.Activity.DORMANT) ? 1288 mActivity : DctConstants.Activity.NONE; 1289 } 1290 1291 if (mActivity != newActivity && mIsScreenOn) { 1292 if (VDBG) 1293 log("updateDataActivity: newActivity=" + newActivity); 1294 mActivity = newActivity; 1295 mPhone.notifyDataActivity(); 1296 } 1297 } 1298 } 1299 1300 // Recovery action taken in case of data stall 1301 protected static class RecoveryAction { 1302 public static final int GET_DATA_CALL_LIST = 0; 1303 public static final int CLEANUP = 1; 1304 public static final int REREGISTER = 2; 1305 public static final int RADIO_RESTART = 3; 1306 public static final int RADIO_RESTART_WITH_PROP = 4; 1307 1308 private static boolean isAggressiveRecovery(int value) { 1309 return ((value == RecoveryAction.CLEANUP) || 1310 (value == RecoveryAction.REREGISTER) || 1311 (value == RecoveryAction.RADIO_RESTART) || 1312 (value == RecoveryAction.RADIO_RESTART_WITH_PROP)); 1313 } 1314 } 1315 1316 public int getRecoveryAction() { 1317 int action = Settings.System.getInt(mPhone.getContext().getContentResolver(), 1318 "radio.data.stall.recovery.action", RecoveryAction.GET_DATA_CALL_LIST); 1319 if (VDBG_STALL) log("getRecoveryAction: " + action); 1320 return action; 1321 } 1322 public void putRecoveryAction(int action) { 1323 Settings.System.putInt(mPhone.getContext().getContentResolver(), 1324 "radio.data.stall.recovery.action", action); 1325 if (VDBG_STALL) log("putRecoveryAction: " + action); 1326 } 1327 1328 protected boolean isConnected() { 1329 return false; 1330 } 1331 1332 protected void doRecovery() { 1333 if (getOverallState() == DctConstants.State.CONNECTED) { 1334 // Go through a series of recovery steps, each action transitions to the next action 1335 int recoveryAction = getRecoveryAction(); 1336 switch (recoveryAction) { 1337 case RecoveryAction.GET_DATA_CALL_LIST: 1338 EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_GET_DATA_CALL_LIST, 1339 mSentSinceLastRecv); 1340 if (DBG) log("doRecovery() get data call list"); 1341 mPhone.mCi.getDataCallList(obtainMessage(DctConstants.EVENT_DATA_STATE_CHANGED)); 1342 putRecoveryAction(RecoveryAction.CLEANUP); 1343 break; 1344 case RecoveryAction.CLEANUP: 1345 EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_CLEANUP, mSentSinceLastRecv); 1346 if (DBG) log("doRecovery() cleanup all connections"); 1347 cleanUpAllConnections(Phone.REASON_PDP_RESET); 1348 putRecoveryAction(RecoveryAction.REREGISTER); 1349 break; 1350 case RecoveryAction.REREGISTER: 1351 EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_REREGISTER, 1352 mSentSinceLastRecv); 1353 if (DBG) log("doRecovery() re-register"); 1354 mPhone.getServiceStateTracker().reRegisterNetwork(null); 1355 putRecoveryAction(RecoveryAction.RADIO_RESTART); 1356 break; 1357 case RecoveryAction.RADIO_RESTART: 1358 EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART, 1359 mSentSinceLastRecv); 1360 if (DBG) log("restarting radio"); 1361 putRecoveryAction(RecoveryAction.RADIO_RESTART_WITH_PROP); 1362 restartRadio(); 1363 break; 1364 case RecoveryAction.RADIO_RESTART_WITH_PROP: 1365 // This is in case radio restart has not recovered the data. 1366 // It will set an additional "gsm.radioreset" property to tell 1367 // RIL or system to take further action. 1368 // The implementation of hard reset recovery action is up to OEM product. 1369 // Once RADIO_RESET property is consumed, it is expected to set back 1370 // to false by RIL. 1371 EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART_WITH_PROP, -1); 1372 if (DBG) log("restarting radio with gsm.radioreset to true"); 1373 SystemProperties.set(RADIO_RESET_PROPERTY, "true"); 1374 // give 1 sec so property change can be notified. 1375 try { 1376 Thread.sleep(1000); 1377 } catch (InterruptedException e) {} 1378 restartRadio(); 1379 putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST); 1380 break; 1381 default: 1382 throw new RuntimeException("doRecovery: Invalid recoveryAction=" + 1383 recoveryAction); 1384 } 1385 mSentSinceLastRecv = 0; 1386 } 1387 } 1388 1389 private void updateDataStallInfo() { 1390 long sent, received; 1391 1392 TxRxSum preTxRxSum = new TxRxSum(mDataStallTxRxSum); 1393 mDataStallTxRxSum.updateTxRxSum(); 1394 1395 if (VDBG_STALL) { 1396 log("updateDataStallInfo: mDataStallTxRxSum=" + mDataStallTxRxSum + 1397 " preTxRxSum=" + preTxRxSum); 1398 } 1399 1400 sent = mDataStallTxRxSum.txPkts - preTxRxSum.txPkts; 1401 received = mDataStallTxRxSum.rxPkts - preTxRxSum.rxPkts; 1402 1403 if (RADIO_TESTS) { 1404 if (SystemProperties.getBoolean("radio.test.data.stall", false)) { 1405 log("updateDataStallInfo: radio.test.data.stall true received = 0;"); 1406 received = 0; 1407 } 1408 } 1409 if ( sent > 0 && received > 0 ) { 1410 if (VDBG_STALL) log("updateDataStallInfo: IN/OUT"); 1411 mSentSinceLastRecv = 0; 1412 putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST); 1413 } else if (sent > 0 && received == 0) { 1414 if (mPhone.getState() == PhoneConstants.State.IDLE) { 1415 mSentSinceLastRecv += sent; 1416 } else { 1417 mSentSinceLastRecv = 0; 1418 } 1419 if (DBG) { 1420 log("updateDataStallInfo: OUT sent=" + sent + 1421 " mSentSinceLastRecv=" + mSentSinceLastRecv); 1422 } 1423 } else if (sent == 0 && received > 0) { 1424 if (VDBG_STALL) log("updateDataStallInfo: IN"); 1425 mSentSinceLastRecv = 0; 1426 putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST); 1427 } else { 1428 if (VDBG_STALL) log("updateDataStallInfo: NONE"); 1429 } 1430 } 1431 1432 protected void onDataStallAlarm(int tag) { 1433 if (mDataStallAlarmTag != tag) { 1434 if (DBG) { 1435 log("onDataStallAlarm: ignore, tag=" + tag + " expecting " + mDataStallAlarmTag); 1436 } 1437 return; 1438 } 1439 updateDataStallInfo(); 1440 1441 int hangWatchdogTrigger = Settings.Global.getInt(mResolver, 1442 Settings.Global.PDP_WATCHDOG_TRIGGER_PACKET_COUNT, 1443 NUMBER_SENT_PACKETS_OF_HANG); 1444 1445 boolean suspectedStall = DATA_STALL_NOT_SUSPECTED; 1446 if (mSentSinceLastRecv >= hangWatchdogTrigger) { 1447 if (DBG) { 1448 log("onDataStallAlarm: tag=" + tag + " do recovery action=" + getRecoveryAction()); 1449 } 1450 suspectedStall = DATA_STALL_SUSPECTED; 1451 sendMessage(obtainMessage(DctConstants.EVENT_DO_RECOVERY)); 1452 } else { 1453 if (VDBG_STALL) { 1454 log("onDataStallAlarm: tag=" + tag + " Sent " + String.valueOf(mSentSinceLastRecv) + 1455 " pkts since last received, < watchdogTrigger=" + hangWatchdogTrigger); 1456 } 1457 } 1458 startDataStallAlarm(suspectedStall); 1459 } 1460 1461 protected void startDataStallAlarm(boolean suspectedStall) { 1462 int nextAction = getRecoveryAction(); 1463 int delayInMs; 1464 1465 if (mDataStallDetectionEnabled && getOverallState() == DctConstants.State.CONNECTED) { 1466 // If screen is on or data stall is currently suspected, set the alarm 1467 // with an aggresive timeout. 1468 if (mIsScreenOn || suspectedStall || RecoveryAction.isAggressiveRecovery(nextAction)) { 1469 delayInMs = Settings.Global.getInt(mResolver, 1470 Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS, 1471 DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS_DEFAULT); 1472 } else { 1473 delayInMs = Settings.Global.getInt(mResolver, 1474 Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS, 1475 DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS_DEFAULT); 1476 } 1477 1478 mDataStallAlarmTag += 1; 1479 if (VDBG_STALL) { 1480 log("startDataStallAlarm: tag=" + mDataStallAlarmTag + 1481 " delay=" + (delayInMs / 1000) + "s"); 1482 } 1483 Intent intent = new Intent(INTENT_DATA_STALL_ALARM); 1484 intent.putExtra(DATA_STALL_ALARM_TAG_EXTRA, mDataStallAlarmTag); 1485 mDataStallAlarmIntent = PendingIntent.getBroadcast(mPhone.getContext(), 0, intent, 1486 PendingIntent.FLAG_UPDATE_CURRENT); 1487 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1488 SystemClock.elapsedRealtime() + delayInMs, mDataStallAlarmIntent); 1489 } else { 1490 if (VDBG_STALL) { 1491 log("startDataStallAlarm: NOT started, no connection tag=" + mDataStallAlarmTag); 1492 } 1493 } 1494 } 1495 1496 protected void stopDataStallAlarm() { 1497 if (VDBG_STALL) { 1498 log("stopDataStallAlarm: current tag=" + mDataStallAlarmTag + 1499 " mDataStallAlarmIntent=" + mDataStallAlarmIntent); 1500 } 1501 mDataStallAlarmTag += 1; 1502 if (mDataStallAlarmIntent != null) { 1503 mAlarmManager.cancel(mDataStallAlarmIntent); 1504 mDataStallAlarmIntent = null; 1505 } 1506 } 1507 1508 protected void restartDataStallAlarm() { 1509 if (isConnected() == false) return; 1510 // To be called on screen status change. 1511 // Do not cancel the alarm if it is set with aggressive timeout. 1512 int nextAction = getRecoveryAction(); 1513 1514 if (RecoveryAction.isAggressiveRecovery(nextAction)) { 1515 if (DBG) log("restartDataStallAlarm: action is pending. not resetting the alarm."); 1516 return; 1517 } 1518 if (VDBG_STALL) log("restartDataStallAlarm: stop then start."); 1519 stopDataStallAlarm(); 1520 startDataStallAlarm(DATA_STALL_NOT_SUSPECTED); 1521 } 1522 1523 void sendCleanUpConnection(boolean tearDown, ApnContext apnContext) { 1524 if (DBG)log("sendCleanUpConnection: tearDown=" + tearDown + " apnContext=" + apnContext); 1525 Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_CONNECTION); 1526 msg.arg1 = tearDown ? 1 : 0; 1527 msg.arg2 = 0; 1528 msg.obj = apnContext; 1529 sendMessage(msg); 1530 } 1531 1532 void sendRestartRadio() { 1533 if (DBG)log("sendRestartRadio:"); 1534 Message msg = obtainMessage(DctConstants.EVENT_RESTART_RADIO); 1535 sendMessage(msg); 1536 } 1537 1538 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1539 pw.println("DataConnectionTrackerBase:"); 1540 pw.println(" RADIO_TESTS=" + RADIO_TESTS); 1541 pw.println(" mInternalDataEnabled=" + mInternalDataEnabled); 1542 pw.println(" mUserDataEnabled=" + mUserDataEnabled); 1543 pw.println(" sPolicyDataEnabed=" + sPolicyDataEnabled); 1544 pw.println(" mDataEnabled:"); 1545 for(int i=0; i < mDataEnabled.length; i++) { 1546 pw.printf(" mDataEnabled[%d]=%b\n", i, mDataEnabled[i]); 1547 } 1548 pw.flush(); 1549 pw.println(" mEnabledCount=" + mEnabledCount); 1550 pw.println(" mRequestedApnType=" + mRequestedApnType); 1551 pw.println(" mPhone=" + mPhone.getPhoneName()); 1552 pw.println(" mActivity=" + mActivity); 1553 pw.println(" mState=" + mState); 1554 pw.println(" mTxPkts=" + mTxPkts); 1555 pw.println(" mRxPkts=" + mRxPkts); 1556 pw.println(" mNetStatPollPeriod=" + mNetStatPollPeriod); 1557 pw.println(" mNetStatPollEnabled=" + mNetStatPollEnabled); 1558 pw.println(" mDataStallTxRxSum=" + mDataStallTxRxSum); 1559 pw.println(" mDataStallAlarmTag=" + mDataStallAlarmTag); 1560 pw.println(" mDataStallDetectionEanbled=" + mDataStallDetectionEnabled); 1561 pw.println(" mSentSinceLastRecv=" + mSentSinceLastRecv); 1562 pw.println(" mNoRecvPollCount=" + mNoRecvPollCount); 1563 pw.println(" mResolver=" + mResolver); 1564 pw.println(" mIsWifiConnected=" + mIsWifiConnected); 1565 pw.println(" mReconnectIntent=" + mReconnectIntent); 1566 pw.println(" mCidActive=" + mCidActive); 1567 pw.println(" mAutoAttachOnCreation=" + mAutoAttachOnCreation); 1568 pw.println(" mIsScreenOn=" + mIsScreenOn); 1569 pw.println(" mUniqueIdGenerator=" + mUniqueIdGenerator); 1570 pw.flush(); 1571 pw.println(" ***************************************"); 1572 DcController dcc = mDcc; 1573 if (dcc != null) { 1574 dcc.dump(fd, pw, args); 1575 } else { 1576 pw.println(" mDcc=null"); 1577 } 1578 pw.println(" ***************************************"); 1579 HashMap<Integer, DataConnection> dcs = mDataConnections; 1580 if (dcs != null) { 1581 Set<Entry<Integer, DataConnection> > mDcSet = mDataConnections.entrySet(); 1582 pw.println(" mDataConnections: count=" + mDcSet.size()); 1583 for (Entry<Integer, DataConnection> entry : mDcSet) { 1584 pw.printf(" *** mDataConnection[%d] \n", entry.getKey()); 1585 entry.getValue().dump(fd, pw, args); 1586 } 1587 } else { 1588 pw.println("mDataConnections=null"); 1589 } 1590 pw.println(" ***************************************"); 1591 pw.flush(); 1592 HashMap<String, Integer> apnToDcId = mApnToDataConnectionId; 1593 if (apnToDcId != null) { 1594 Set<Entry<String, Integer>> apnToDcIdSet = apnToDcId.entrySet(); 1595 pw.println(" mApnToDataConnectonId size=" + apnToDcIdSet.size()); 1596 for (Entry<String, Integer> entry : apnToDcIdSet) { 1597 pw.printf(" mApnToDataConnectonId[%s]=%d\n", entry.getKey(), entry.getValue()); 1598 } 1599 } else { 1600 pw.println("mApnToDataConnectionId=null"); 1601 } 1602 pw.println(" ***************************************"); 1603 pw.flush(); 1604 ConcurrentHashMap<String, ApnContext> apnCtxs = mApnContexts; 1605 if (apnCtxs != null) { 1606 Set<Entry<String, ApnContext>> apnCtxsSet = apnCtxs.entrySet(); 1607 pw.println(" mApnContexts size=" + apnCtxsSet.size()); 1608 for (Entry<String, ApnContext> entry : apnCtxsSet) { 1609 entry.getValue().dump(fd, pw, args); 1610 } 1611 pw.println(" ***************************************"); 1612 } else { 1613 pw.println(" mApnContexts=null"); 1614 } 1615 pw.flush(); 1616 pw.println(" mActiveApn=" + mActiveApn); 1617 ArrayList<ApnSetting> apnSettings = mAllApnSettings; 1618 if (apnSettings != null) { 1619 pw.println(" mAllApnSettings size=" + apnSettings.size()); 1620 for (int i=0; i < apnSettings.size(); i++) { 1621 pw.printf(" mAllApnSettings[%d]: %s\n", i, apnSettings.get(i)); 1622 } 1623 pw.flush(); 1624 } else { 1625 pw.println(" mAllApnSettings=null"); 1626 } 1627 pw.println(" mPreferredApn=" + mPreferredApn); 1628 pw.println(" mIsPsRestricted=" + mIsPsRestricted); 1629 pw.println(" mIsDisposed=" + mIsDisposed); 1630 pw.println(" mIntentReceiver=" + mIntentReceiver); 1631 pw.println(" mDataRoamingSettingObserver=" + mDataRoamingSettingObserver); 1632 pw.flush(); 1633 } 1634} 1635