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