DcTrackerBase.java revision 1f2a2323572b2f3ab18234726cc1b048c670fbab
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    public DctConstants.Activity getActivity() {
522        return mActivity;
523    }
524
525    public boolean isApnTypeActive(String type) {
526        // TODO: support simultaneous with List instead
527        if (PhoneConstants.APN_TYPE_DUN.equals(type)) {
528            ApnSetting dunApn = fetchDunApn();
529            if (dunApn != null) {
530                return ((mActiveApn != null) && (dunApn.toString().equals(mActiveApn.toString())));
531            }
532        }
533        return mActiveApn != null && mActiveApn.canHandleType(type);
534    }
535
536    protected ApnSetting fetchDunApn() {
537        if (SystemProperties.getBoolean("net.tethering.noprovisioning", false)) {
538            log("fetchDunApn: net.tethering.noprovisioning=true ret: null");
539            return null;
540        }
541        Context c = mPhone.getContext();
542        String apnData = Settings.Global.getString(c.getContentResolver(),
543                Settings.Global.TETHER_DUN_APN);
544        ApnSetting dunSetting = ApnSetting.fromString(apnData);
545        if (dunSetting != null) {
546            if (VDBG) log("fetchDunApn: global TETHER_DUN_APN dunSetting=" + dunSetting);
547            return dunSetting;
548        }
549
550        apnData = c.getResources().getString(R.string.config_tether_apndata);
551        dunSetting = ApnSetting.fromString(apnData);
552        if (VDBG) log("fetchDunApn: config_tether_apndata dunSetting=" + dunSetting);
553        return dunSetting;
554    }
555
556    public String[] getActiveApnTypes() {
557        String[] result;
558        if (mActiveApn != null) {
559            result = mActiveApn.types;
560        } else {
561            result = new String[1];
562            result[0] = PhoneConstants.APN_TYPE_DEFAULT;
563        }
564        return result;
565    }
566
567    /** TODO: See if we can remove */
568    public String getActiveApnString(String apnType) {
569        String result = null;
570        if (mActiveApn != null) {
571            result = mActiveApn.apn;
572        }
573        return result;
574    }
575
576    /**
577     * Modify {@link android.provider.Settings.Global#DATA_ROAMING} value.
578     */
579    public void setDataOnRoamingEnabled(boolean enabled) {
580        if (getDataOnRoamingEnabled() != enabled) {
581            final ContentResolver resolver = mPhone.getContext().getContentResolver();
582            Settings.Global.putInt(resolver, Settings.Global.DATA_ROAMING, enabled ? 1 : 0);
583            // will trigger handleDataOnRoamingChange() through observer
584        }
585    }
586
587    /**
588     * Return current {@link android.provider.Settings.Global#DATA_ROAMING} value.
589     */
590    public boolean getDataOnRoamingEnabled() {
591        try {
592            final ContentResolver resolver = mPhone.getContext().getContentResolver();
593            return Settings.Global.getInt(resolver, Settings.Global.DATA_ROAMING) != 0;
594        } catch (SettingNotFoundException snfe) {
595            return false;
596        }
597    }
598
599    // abstract methods
600    protected abstract void restartRadio();
601    protected abstract void log(String s);
602    protected abstract void loge(String s);
603    protected abstract boolean isDataAllowed();
604    protected abstract boolean isApnTypeAvailable(String type);
605    public    abstract DctConstants.State getState(String apnType);
606    protected abstract void setState(DctConstants.State s);
607    protected abstract void gotoIdleAndNotifyDataConnection(String reason);
608
609    protected abstract boolean onTrySetupData(String reason);
610    protected abstract void onRoamingOff();
611    protected abstract void onRoamingOn();
612    protected abstract void onRadioAvailable();
613    protected abstract void onRadioOffOrNotAvailable();
614    protected abstract void onDataSetupComplete(AsyncResult ar);
615    protected abstract void onDataSetupCompleteError(AsyncResult ar);
616    protected abstract void onDisconnectDone(int connId, AsyncResult ar);
617    protected abstract void onDisconnectDcRetrying(int connId, AsyncResult ar);
618    protected abstract void onVoiceCallStarted();
619    protected abstract void onVoiceCallEnded();
620    protected abstract void onCleanUpConnection(boolean tearDown, int apnId, String reason);
621    protected abstract void onCleanUpAllConnections(String cause);
622    public abstract boolean isDataPossible(String apnType);
623    protected abstract void onUpdateIcc();
624
625    @Override
626    public void handleMessage(Message msg) {
627        switch (msg.what) {
628            case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
629                log("DISCONNECTED_CONNECTED: msg=" + msg);
630                DcAsyncChannel dcac = (DcAsyncChannel) msg.obj;
631                mDataConnectionAcHashMap.remove(dcac.getDataConnectionIdSync());
632                dcac.disconnected();
633                break;
634            }
635            case DctConstants.EVENT_ENABLE_NEW_APN:
636                onEnableApn(msg.arg1, msg.arg2);
637                break;
638
639            case DctConstants.EVENT_TRY_SETUP_DATA:
640                String reason = null;
641                if (msg.obj instanceof String) {
642                    reason = (String) msg.obj;
643                }
644                onTrySetupData(reason);
645                break;
646
647            case DctConstants.EVENT_DATA_STALL_ALARM:
648                onDataStallAlarm(msg.arg1);
649                break;
650
651            case DctConstants.EVENT_ROAMING_OFF:
652                onRoamingOff();
653                break;
654
655            case DctConstants.EVENT_ROAMING_ON:
656                onRoamingOn();
657                break;
658
659            case DctConstants.EVENT_RADIO_AVAILABLE:
660                onRadioAvailable();
661                break;
662
663            case DctConstants.EVENT_RADIO_OFF_OR_NOT_AVAILABLE:
664                onRadioOffOrNotAvailable();
665                break;
666
667            case DctConstants.EVENT_DATA_SETUP_COMPLETE:
668                mCidActive = msg.arg1;
669                onDataSetupComplete((AsyncResult) msg.obj);
670                break;
671
672            case DctConstants.EVENT_DATA_SETUP_COMPLETE_ERROR:
673                onDataSetupCompleteError((AsyncResult) msg.obj);
674                break;
675
676            case DctConstants.EVENT_DISCONNECT_DONE:
677                log("DataConnectoinTracker.handleMessage: EVENT_DISCONNECT_DONE msg=" + msg);
678                onDisconnectDone(msg.arg1, (AsyncResult) msg.obj);
679                break;
680
681            case DctConstants.EVENT_DISCONNECT_DC_RETRYING:
682                log("DataConnectoinTracker.handleMessage: EVENT_DISCONNECT_DC_RETRYING msg=" + msg);
683                onDisconnectDcRetrying(msg.arg1, (AsyncResult) msg.obj);
684                break;
685
686            case DctConstants.EVENT_VOICE_CALL_STARTED:
687                onVoiceCallStarted();
688                break;
689
690            case DctConstants.EVENT_VOICE_CALL_ENDED:
691                onVoiceCallEnded();
692                break;
693
694            case DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS: {
695                onCleanUpAllConnections((String) msg.obj);
696                break;
697            }
698            case DctConstants.EVENT_CLEAN_UP_CONNECTION: {
699                boolean tearDown = (msg.arg1 == 0) ? false : true;
700                onCleanUpConnection(tearDown, msg.arg2, (String) msg.obj);
701                break;
702            }
703            case DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE: {
704                boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
705                onSetInternalDataEnabled(enabled);
706                break;
707            }
708            case DctConstants.EVENT_RESET_DONE: {
709                if (DBG) log("EVENT_RESET_DONE");
710                onResetDone((AsyncResult) msg.obj);
711                break;
712            }
713            case DctConstants.CMD_SET_USER_DATA_ENABLE: {
714                final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
715                if (DBG) log("CMD_SET_USER_DATA_ENABLE enabled=" + enabled);
716                onSetUserDataEnabled(enabled);
717                break;
718            }
719            case DctConstants.CMD_SET_DEPENDENCY_MET: {
720                boolean met = (msg.arg1 == DctConstants.ENABLED) ? true : false;
721                if (DBG) log("CMD_SET_DEPENDENCY_MET met=" + met);
722                Bundle bundle = msg.getData();
723                if (bundle != null) {
724                    String apnType = (String)bundle.get(DctConstants.APN_TYPE_KEY);
725                    if (apnType != null) {
726                        onSetDependencyMet(apnType, met);
727                    }
728                }
729                break;
730            }
731            case DctConstants.CMD_SET_POLICY_DATA_ENABLE: {
732                final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
733                onSetPolicyDataEnabled(enabled);
734                break;
735            }
736            case DctConstants.EVENT_ICC_CHANGED: {
737                onUpdateIcc();
738                break;
739            }
740            default:
741                Rlog.e("DATA", "Unidentified event msg=" + msg);
742                break;
743        }
744    }
745
746    /**
747     * Report on whether data connectivity is enabled
748     *
749     * @return {@code false} if data connectivity has been explicitly disabled,
750     *         {@code true} otherwise.
751     */
752    public boolean getAnyDataEnabled() {
753        final boolean result;
754        synchronized (mDataEnabledLock) {
755            result = (mInternalDataEnabled && mUserDataEnabled && sPolicyDataEnabled
756                    && (mEnabledCount != 0));
757        }
758        if (!result && DBG) log("getAnyDataEnabled " + result);
759        return result;
760    }
761
762    protected boolean isEmergency() {
763        final boolean result;
764        synchronized (mDataEnabledLock) {
765            result = mPhone.isInEcm() || mPhone.isInEmergencyCall();
766        }
767        log("isEmergency: result=" + result);
768        return result;
769    }
770
771    protected int apnTypeToId(String type) {
772        if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DEFAULT)) {
773            return DctConstants.APN_DEFAULT_ID;
774        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_MMS)) {
775            return DctConstants.APN_MMS_ID;
776        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_SUPL)) {
777            return DctConstants.APN_SUPL_ID;
778        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DUN)) {
779            return DctConstants.APN_DUN_ID;
780        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_HIPRI)) {
781            return DctConstants.APN_HIPRI_ID;
782        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_IMS)) {
783            return DctConstants.APN_IMS_ID;
784        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_FOTA)) {
785            return DctConstants.APN_FOTA_ID;
786        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_CBS)) {
787            return DctConstants.APN_CBS_ID;
788        } else {
789            return DctConstants.APN_INVALID_ID;
790        }
791    }
792
793    protected String apnIdToType(int id) {
794        switch (id) {
795        case DctConstants.APN_DEFAULT_ID:
796            return PhoneConstants.APN_TYPE_DEFAULT;
797        case DctConstants.APN_MMS_ID:
798            return PhoneConstants.APN_TYPE_MMS;
799        case DctConstants.APN_SUPL_ID:
800            return PhoneConstants.APN_TYPE_SUPL;
801        case DctConstants.APN_DUN_ID:
802            return PhoneConstants.APN_TYPE_DUN;
803        case DctConstants.APN_HIPRI_ID:
804            return PhoneConstants.APN_TYPE_HIPRI;
805        case DctConstants.APN_IMS_ID:
806            return PhoneConstants.APN_TYPE_IMS;
807        case DctConstants.APN_FOTA_ID:
808            return PhoneConstants.APN_TYPE_FOTA;
809        case DctConstants.APN_CBS_ID:
810            return PhoneConstants.APN_TYPE_CBS;
811        default:
812            log("Unknown id (" + id + ") in apnIdToType");
813            return PhoneConstants.APN_TYPE_DEFAULT;
814        }
815    }
816
817    public LinkProperties getLinkProperties(String apnType) {
818        int id = apnTypeToId(apnType);
819
820        if (isApnIdEnabled(id)) {
821            DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0);
822            return dcac.getLinkPropertiesSync();
823        } else {
824            return new LinkProperties();
825        }
826    }
827
828    public LinkCapabilities getLinkCapabilities(String apnType) {
829        int id = apnTypeToId(apnType);
830        if (isApnIdEnabled(id)) {
831            DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0);
832            return dcac.getLinkCapabilitiesSync();
833        } else {
834            return new LinkCapabilities();
835        }
836    }
837
838    // tell all active apns of the current condition
839    protected void notifyDataConnection(String reason) {
840        for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) {
841            if (mDataEnabled[id]) {
842                mPhone.notifyDataConnection(reason, apnIdToType(id));
843            }
844        }
845        notifyOffApnsOfAvailability(reason);
846    }
847
848    // a new APN has gone active and needs to send events to catch up with the
849    // current condition
850    private void notifyApnIdUpToCurrent(String reason, int apnId) {
851        switch (mState) {
852            case IDLE:
853                break;
854            case RETRYING:
855            case CONNECTING:
856            case SCANNING:
857                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
858                        PhoneConstants.DataState.CONNECTING);
859                break;
860            case CONNECTED:
861            case DISCONNECTING:
862                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
863                        PhoneConstants.DataState.CONNECTING);
864                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
865                        PhoneConstants.DataState.CONNECTED);
866                break;
867            default:
868                // Ignore
869                break;
870        }
871    }
872
873    // since we normally don't send info to a disconnected APN, we need to do this specially
874    private void notifyApnIdDisconnected(String reason, int apnId) {
875        mPhone.notifyDataConnection(reason, apnIdToType(apnId),
876                PhoneConstants.DataState.DISCONNECTED);
877    }
878
879    // disabled apn's still need avail/unavail notificiations - send them out
880    protected void notifyOffApnsOfAvailability(String reason) {
881        if (DBG) log("notifyOffApnsOfAvailability - reason= " + reason);
882        for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) {
883            if (!isApnIdEnabled(id)) {
884                notifyApnIdDisconnected(reason, id);
885            }
886        }
887    }
888
889    public boolean isApnTypeEnabled(String apnType) {
890        if (apnType == null) {
891            return false;
892        } else {
893            return isApnIdEnabled(apnTypeToId(apnType));
894        }
895    }
896
897    protected synchronized boolean isApnIdEnabled(int id) {
898        if (id != DctConstants.APN_INVALID_ID) {
899            return mDataEnabled[id];
900        }
901        return false;
902    }
903
904    /**
905     * Ensure that we are connected to an APN of the specified type.
906     *
907     * @param type the APN type (currently the only valid values are
908     *            {@link PhoneConstants#APN_TYPE_MMS} and {@link PhoneConstants#APN_TYPE_SUPL})
909     * @return Success is indicated by {@code Phone.APN_ALREADY_ACTIVE} or
910     *         {@code Phone.APN_REQUEST_STARTED}. In the latter case, a
911     *         broadcast will be sent by the ConnectivityManager when a
912     *         connection to the APN has been established.
913     */
914    public synchronized int enableApnType(String type) {
915        int id = apnTypeToId(type);
916        if (id == DctConstants.APN_INVALID_ID) {
917            return PhoneConstants.APN_REQUEST_FAILED;
918        }
919
920        if (DBG) {
921            log("enableApnType(" + type + "), isApnTypeActive = " + isApnTypeActive(type)
922                    + ", isApnIdEnabled =" + isApnIdEnabled(id) + " and state = " + mState);
923        }
924
925        if (!isApnTypeAvailable(type)) {
926            if (DBG) log("type not available");
927            return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
928        }
929
930        if (isApnIdEnabled(id)) {
931            return PhoneConstants.APN_ALREADY_ACTIVE;
932        } else {
933            setEnabled(id, true);
934        }
935        return PhoneConstants.APN_REQUEST_STARTED;
936    }
937
938    /**
939     * The APN of the specified type is no longer needed. Ensure that if use of
940     * the default APN has not been explicitly disabled, we are connected to the
941     * default APN.
942     *
943     * @param type the APN type. The only valid values are currently
944     *            {@link PhoneConstants#APN_TYPE_MMS} and {@link PhoneConstants#APN_TYPE_SUPL}.
945     * @return Success is indicated by {@code PhoneConstants.APN_ALREADY_ACTIVE} or
946     *         {@code PhoneConstants.APN_REQUEST_STARTED}. In the latter case, a
947     *         broadcast will be sent by the ConnectivityManager when a
948     *         connection to the APN has been disconnected. A {@code
949     *         PhoneConstants.APN_REQUEST_FAILED} is returned if the type parameter is
950     *         invalid or if the apn wasn't enabled.
951     */
952    public synchronized int disableApnType(String type) {
953        if (DBG) log("disableApnType(" + type + ")");
954        int id = apnTypeToId(type);
955        if (id == DctConstants.APN_INVALID_ID) {
956            return PhoneConstants.APN_REQUEST_FAILED;
957        }
958        if (isApnIdEnabled(id)) {
959            setEnabled(id, false);
960            if (isApnTypeActive(PhoneConstants.APN_TYPE_DEFAULT)) {
961                if (mDataEnabled[DctConstants.APN_DEFAULT_ID]) {
962                    return PhoneConstants.APN_ALREADY_ACTIVE;
963                } else {
964                    return PhoneConstants.APN_REQUEST_STARTED;
965                }
966            } else {
967                return PhoneConstants.APN_REQUEST_STARTED;
968            }
969        } else {
970            return PhoneConstants.APN_REQUEST_FAILED;
971        }
972    }
973
974    protected void setEnabled(int id, boolean enable) {
975        if (DBG) {
976            log("setEnabled(" + id + ", " + enable + ") with old state = " + mDataEnabled[id]
977                    + " and enabledCount = " + mEnabledCount);
978        }
979        Message msg = obtainMessage(DctConstants.EVENT_ENABLE_NEW_APN);
980        msg.arg1 = id;
981        msg.arg2 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
982        sendMessage(msg);
983    }
984
985    protected void onEnableApn(int apnId, int enabled) {
986        if (DBG) {
987            log("EVENT_APN_ENABLE_REQUEST apnId=" + apnId + ", apnType=" + apnIdToType(apnId) +
988                    ", enabled=" + enabled + ", dataEnabled = " + mDataEnabled[apnId] +
989                    ", enabledCount = " + mEnabledCount + ", isApnTypeActive = " +
990                    isApnTypeActive(apnIdToType(apnId)));
991        }
992        if (enabled == DctConstants.ENABLED) {
993            synchronized (this) {
994                if (!mDataEnabled[apnId]) {
995                    mDataEnabled[apnId] = true;
996                    mEnabledCount++;
997                }
998            }
999            String type = apnIdToType(apnId);
1000            if (!isApnTypeActive(type)) {
1001                mRequestedApnType = type;
1002                onEnableNewApn();
1003            } else {
1004                notifyApnIdUpToCurrent(Phone.REASON_APN_SWITCHED, apnId);
1005            }
1006        } else {
1007            // disable
1008            boolean didDisable = false;
1009            synchronized (this) {
1010                if (mDataEnabled[apnId]) {
1011                    mDataEnabled[apnId] = false;
1012                    mEnabledCount--;
1013                    didDisable = true;
1014                }
1015            }
1016            if (didDisable) {
1017                if ((mEnabledCount == 0) || (apnId == DctConstants.APN_DUN_ID)) {
1018                    mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
1019                    onCleanUpConnection(true, apnId, Phone.REASON_DATA_DISABLED);
1020                }
1021
1022                // send the disconnect msg manually, since the normal route wont send
1023                // it (it's not enabled)
1024                notifyApnIdDisconnected(Phone.REASON_DATA_DISABLED, apnId);
1025                if (mDataEnabled[DctConstants.APN_DEFAULT_ID] == true
1026                        && !isApnTypeActive(PhoneConstants.APN_TYPE_DEFAULT)) {
1027                    // TODO - this is an ugly way to restore the default conn - should be done
1028                    // by a real contention manager and policy that disconnects the lower pri
1029                    // stuff as enable requests come in and pops them back on as we disable back
1030                    // down to the lower pri stuff
1031                    mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
1032                    onEnableNewApn();
1033                }
1034            }
1035        }
1036    }
1037
1038    /**
1039     * Called when we switch APNs.
1040     *
1041     * mRequestedApnType is set prior to call
1042     * To be overridden.
1043     */
1044    protected void onEnableNewApn() {
1045    }
1046
1047    /**
1048     * Called when EVENT_RESET_DONE is received so goto
1049     * IDLE state and send notifications to those interested.
1050     *
1051     * TODO - currently unused.  Needs to be hooked into DataConnection cleanup
1052     * TODO - needs to pass some notion of which connection is reset..
1053     */
1054    protected void onResetDone(AsyncResult ar) {
1055        if (DBG) log("EVENT_RESET_DONE");
1056        String reason = null;
1057        if (ar.userObj instanceof String) {
1058            reason = (String) ar.userObj;
1059        }
1060        gotoIdleAndNotifyDataConnection(reason);
1061    }
1062
1063    /**
1064     * Prevent mobile data connections from being established, or once again
1065     * allow mobile data connections. If the state toggles, then either tear
1066     * down or set up data, as appropriate to match the new state.
1067     *
1068     * @param enable indicates whether to enable ({@code true}) or disable (
1069     *            {@code false}) data
1070     * @return {@code true} if the operation succeeded
1071     */
1072    public boolean setInternalDataEnabled(boolean enable) {
1073        if (DBG)
1074            log("setInternalDataEnabled(" + enable + ")");
1075
1076        Message msg = obtainMessage(DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE);
1077        msg.arg1 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
1078        sendMessage(msg);
1079        return true;
1080    }
1081
1082    protected void onSetInternalDataEnabled(boolean enabled) {
1083        synchronized (mDataEnabledLock) {
1084            mInternalDataEnabled = enabled;
1085            if (enabled) {
1086                log("onSetInternalDataEnabled: changed to enabled, try to setup data call");
1087                onTrySetupData(Phone.REASON_DATA_ENABLED);
1088            } else {
1089                log("onSetInternalDataEnabled: changed to disabled, cleanUpAllConnections");
1090                cleanUpAllConnections(null);
1091            }
1092        }
1093    }
1094
1095    public void cleanUpAllConnections(String cause) {
1096        Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS);
1097        msg.obj = cause;
1098        sendMessage(msg);
1099    }
1100
1101    public abstract boolean isDisconnected();
1102
1103    protected void onSetUserDataEnabled(boolean enabled) {
1104        synchronized (mDataEnabledLock) {
1105            final boolean prevEnabled = getAnyDataEnabled();
1106            if (mUserDataEnabled != enabled) {
1107                mUserDataEnabled = enabled;
1108                Settings.Global.putInt(mPhone.getContext().getContentResolver(),
1109                        Settings.Global.MOBILE_DATA, enabled ? 1 : 0);
1110                if (getDataOnRoamingEnabled() == false &&
1111                        mPhone.getServiceState().getRoaming() == true) {
1112                    if (enabled) {
1113                        notifyOffApnsOfAvailability(Phone.REASON_ROAMING_ON);
1114                    } else {
1115                        notifyOffApnsOfAvailability(Phone.REASON_DATA_DISABLED);
1116                    }
1117                }
1118                if (prevEnabled != getAnyDataEnabled()) {
1119                    if (!prevEnabled) {
1120                        onTrySetupData(Phone.REASON_DATA_ENABLED);
1121                    } else {
1122                        onCleanUpAllConnections(Phone.REASON_DATA_DISABLED);
1123                    }
1124                }
1125            }
1126        }
1127    }
1128
1129    protected void onSetDependencyMet(String apnType, boolean met) {
1130    }
1131
1132    protected void onSetPolicyDataEnabled(boolean enabled) {
1133        synchronized (mDataEnabledLock) {
1134            final boolean prevEnabled = getAnyDataEnabled();
1135            if (sPolicyDataEnabled != enabled) {
1136                sPolicyDataEnabled = enabled;
1137                if (prevEnabled != getAnyDataEnabled()) {
1138                    if (!prevEnabled) {
1139                        onTrySetupData(Phone.REASON_DATA_ENABLED);
1140                    } else {
1141                        onCleanUpAllConnections(Phone.REASON_DATA_DISABLED);
1142                    }
1143                }
1144            }
1145        }
1146    }
1147
1148    protected String getReryConfig(boolean forDefault) {
1149        int nt = mPhone.getServiceState().getNetworkType();
1150
1151        if ((nt == TelephonyManager.NETWORK_TYPE_CDMA) ||
1152            (nt == TelephonyManager.NETWORK_TYPE_1xRTT) ||
1153            (nt == TelephonyManager.NETWORK_TYPE_EVDO_0) ||
1154            (nt == TelephonyManager.NETWORK_TYPE_EVDO_A) ||
1155            (nt == TelephonyManager.NETWORK_TYPE_EVDO_B) ||
1156            (nt == TelephonyManager.NETWORK_TYPE_EHRPD)) {
1157            // CDMA variant
1158            return SystemProperties.get("ro.cdma.data_retry_config");
1159        } else {
1160            // Use GSM varient for all others.
1161            if (forDefault) {
1162                return SystemProperties.get("ro.gsm.data_retry_config");
1163            } else {
1164                return SystemProperties.get("ro.gsm.2nd_data_retry_config");
1165            }
1166        }
1167    }
1168
1169    protected void resetPollStats() {
1170        mTxPkts = -1;
1171        mRxPkts = -1;
1172        mNetStatPollPeriod = POLL_NETSTAT_MILLIS;
1173    }
1174
1175    protected abstract DctConstants.State getOverallState();
1176
1177    protected void startNetStatPoll() {
1178        if (getOverallState() == DctConstants.State.CONNECTED && mNetStatPollEnabled == false) {
1179            if (DBG) log("startNetStatPoll");
1180            resetPollStats();
1181            mNetStatPollEnabled = true;
1182            mPollNetStat.run();
1183        }
1184    }
1185
1186    protected void stopNetStatPoll() {
1187        mNetStatPollEnabled = false;
1188        removeCallbacks(mPollNetStat);
1189        if (DBG) log("stopNetStatPoll");
1190    }
1191
1192    public void updateDataActivity() {
1193        long sent, received;
1194
1195        DctConstants.Activity newActivity;
1196
1197        TxRxSum preTxRxSum = new TxRxSum(mTxPkts, mRxPkts);
1198        TxRxSum curTxRxSum = new TxRxSum();
1199        curTxRxSum.updateTxRxSum();
1200        mTxPkts = curTxRxSum.txPkts;
1201        mRxPkts = curTxRxSum.rxPkts;
1202
1203        if (VDBG) {
1204            log("updateDataActivity: curTxRxSum=" + curTxRxSum + " preTxRxSum=" + preTxRxSum);
1205        }
1206
1207        if (mNetStatPollEnabled && (preTxRxSum.txPkts > 0 || preTxRxSum.rxPkts > 0)) {
1208            sent = mTxPkts - preTxRxSum.txPkts;
1209            received = mRxPkts - preTxRxSum.rxPkts;
1210
1211            if (VDBG)
1212                log("updateDataActivity: sent=" + sent + " received=" + received);
1213            if (sent > 0 && received > 0) {
1214                newActivity = DctConstants.Activity.DATAINANDOUT;
1215            } else if (sent > 0 && received == 0) {
1216                newActivity = DctConstants.Activity.DATAOUT;
1217            } else if (sent == 0 && received > 0) {
1218                newActivity = DctConstants.Activity.DATAIN;
1219            } else {
1220                newActivity = (mActivity == DctConstants.Activity.DORMANT) ?
1221                        mActivity : DctConstants.Activity.NONE;
1222            }
1223
1224            if (mActivity != newActivity && mIsScreenOn) {
1225                if (VDBG)
1226                    log("updateDataActivity: newActivity=" + newActivity);
1227                mActivity = newActivity;
1228                mPhone.notifyDataActivity();
1229            }
1230        }
1231    }
1232
1233    // Recovery action taken in case of data stall
1234    protected static class RecoveryAction {
1235        public static final int GET_DATA_CALL_LIST      = 0;
1236        public static final int CLEANUP                 = 1;
1237        public static final int REREGISTER              = 2;
1238        public static final int RADIO_RESTART           = 3;
1239        public static final int RADIO_RESTART_WITH_PROP = 4;
1240
1241        private static boolean isAggressiveRecovery(int value) {
1242            return ((value == RecoveryAction.CLEANUP) ||
1243                    (value == RecoveryAction.REREGISTER) ||
1244                    (value == RecoveryAction.RADIO_RESTART) ||
1245                    (value == RecoveryAction.RADIO_RESTART_WITH_PROP));
1246        }
1247    }
1248
1249    public int getRecoveryAction() {
1250        int action = Settings.System.getInt(mPhone.getContext().getContentResolver(),
1251                "radio.data.stall.recovery.action", RecoveryAction.GET_DATA_CALL_LIST);
1252        if (VDBG_STALL) log("getRecoveryAction: " + action);
1253        return action;
1254    }
1255    public void putRecoveryAction(int action) {
1256        Settings.System.putInt(mPhone.getContext().getContentResolver(),
1257                "radio.data.stall.recovery.action", action);
1258        if (VDBG_STALL) log("putRecoveryAction: " + action);
1259    }
1260
1261    protected boolean isConnected() {
1262        return false;
1263    }
1264
1265    protected void doRecovery() {
1266        if (getOverallState() == DctConstants.State.CONNECTED) {
1267            // Go through a series of recovery steps, each action transitions to the next action
1268            int recoveryAction = getRecoveryAction();
1269            switch (recoveryAction) {
1270            case RecoveryAction.GET_DATA_CALL_LIST:
1271                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_GET_DATA_CALL_LIST,
1272                        mSentSinceLastRecv);
1273                if (DBG) log("doRecovery() get data call list");
1274                mPhone.mCi.getDataCallList(obtainMessage(DctConstants.EVENT_DATA_STATE_CHANGED));
1275                putRecoveryAction(RecoveryAction.CLEANUP);
1276                break;
1277            case RecoveryAction.CLEANUP:
1278                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_CLEANUP, mSentSinceLastRecv);
1279                if (DBG) log("doRecovery() cleanup all connections");
1280                cleanUpAllConnections(Phone.REASON_PDP_RESET);
1281                putRecoveryAction(RecoveryAction.REREGISTER);
1282                break;
1283            case RecoveryAction.REREGISTER:
1284                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_REREGISTER,
1285                        mSentSinceLastRecv);
1286                if (DBG) log("doRecovery() re-register");
1287                mPhone.getServiceStateTracker().reRegisterNetwork(null);
1288                putRecoveryAction(RecoveryAction.RADIO_RESTART);
1289                break;
1290            case RecoveryAction.RADIO_RESTART:
1291                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART,
1292                        mSentSinceLastRecv);
1293                if (DBG) log("restarting radio");
1294                putRecoveryAction(RecoveryAction.RADIO_RESTART_WITH_PROP);
1295                restartRadio();
1296                break;
1297            case RecoveryAction.RADIO_RESTART_WITH_PROP:
1298                // This is in case radio restart has not recovered the data.
1299                // It will set an additional "gsm.radioreset" property to tell
1300                // RIL or system to take further action.
1301                // The implementation of hard reset recovery action is up to OEM product.
1302                // Once RADIO_RESET property is consumed, it is expected to set back
1303                // to false by RIL.
1304                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART_WITH_PROP, -1);
1305                if (DBG) log("restarting radio with gsm.radioreset to true");
1306                SystemProperties.set(RADIO_RESET_PROPERTY, "true");
1307                // give 1 sec so property change can be notified.
1308                try {
1309                    Thread.sleep(1000);
1310                } catch (InterruptedException e) {}
1311                restartRadio();
1312                putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1313                break;
1314            default:
1315                throw new RuntimeException("doRecovery: Invalid recoveryAction=" +
1316                    recoveryAction);
1317            }
1318            mSentSinceLastRecv = 0;
1319        }
1320    }
1321
1322    private void updateDataStallInfo() {
1323        long sent, received;
1324
1325        TxRxSum preTxRxSum = new TxRxSum(mDataStallTxRxSum);
1326        mDataStallTxRxSum.updateTxRxSum();
1327
1328        if (VDBG_STALL) {
1329            log("updateDataStallInfo: mDataStallTxRxSum=" + mDataStallTxRxSum +
1330                    " preTxRxSum=" + preTxRxSum);
1331        }
1332
1333        sent = mDataStallTxRxSum.txPkts - preTxRxSum.txPkts;
1334        received = mDataStallTxRxSum.rxPkts - preTxRxSum.rxPkts;
1335
1336        if (RADIO_TESTS) {
1337            if (SystemProperties.getBoolean("radio.test.data.stall", false)) {
1338                log("updateDataStallInfo: radio.test.data.stall true received = 0;");
1339                received = 0;
1340            }
1341        }
1342        if ( sent > 0 && received > 0 ) {
1343            if (VDBG_STALL) log("updateDataStallInfo: IN/OUT");
1344            mSentSinceLastRecv = 0;
1345            putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1346        } else if (sent > 0 && received == 0) {
1347            if (mPhone.getState() == PhoneConstants.State.IDLE) {
1348                mSentSinceLastRecv += sent;
1349            } else {
1350                mSentSinceLastRecv = 0;
1351            }
1352            if (DBG) {
1353                log("updateDataStallInfo: OUT sent=" + sent +
1354                        " mSentSinceLastRecv=" + mSentSinceLastRecv);
1355            }
1356        } else if (sent == 0 && received > 0) {
1357            if (VDBG_STALL) log("updateDataStallInfo: IN");
1358            mSentSinceLastRecv = 0;
1359            putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1360        } else {
1361            if (VDBG_STALL) log("updateDataStallInfo: NONE");
1362        }
1363    }
1364
1365    protected void onDataStallAlarm(int tag) {
1366        if (mDataStallAlarmTag != tag) {
1367            if (DBG) {
1368                log("onDataStallAlarm: ignore, tag=" + tag + " expecting " + mDataStallAlarmTag);
1369            }
1370            return;
1371        }
1372        updateDataStallInfo();
1373
1374        int hangWatchdogTrigger = Settings.Global.getInt(mResolver,
1375                Settings.Global.PDP_WATCHDOG_TRIGGER_PACKET_COUNT,
1376                NUMBER_SENT_PACKETS_OF_HANG);
1377
1378        boolean suspectedStall = DATA_STALL_NOT_SUSPECTED;
1379        if (mSentSinceLastRecv >= hangWatchdogTrigger) {
1380            if (DBG) {
1381                log("onDataStallAlarm: tag=" + tag + " do recovery action=" + getRecoveryAction());
1382            }
1383            suspectedStall = DATA_STALL_SUSPECTED;
1384            sendMessage(obtainMessage(DctConstants.EVENT_DO_RECOVERY));
1385        } else {
1386            if (VDBG_STALL) {
1387                log("onDataStallAlarm: tag=" + tag + " Sent " + String.valueOf(mSentSinceLastRecv) +
1388                    " pkts since last received, < watchdogTrigger=" + hangWatchdogTrigger);
1389            }
1390        }
1391        startDataStallAlarm(suspectedStall);
1392    }
1393
1394    protected void startDataStallAlarm(boolean suspectedStall) {
1395        int nextAction = getRecoveryAction();
1396        int delayInMs;
1397
1398        if (getOverallState() == DctConstants.State.CONNECTED) {
1399            // If screen is on or data stall is currently suspected, set the alarm
1400            // with an aggresive timeout.
1401            if (mIsScreenOn || suspectedStall || RecoveryAction.isAggressiveRecovery(nextAction)) {
1402                delayInMs = Settings.Global.getInt(mResolver,
1403                        Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS,
1404                        DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS_DEFAULT);
1405            } else {
1406                delayInMs = Settings.Global.getInt(mResolver,
1407                        Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS,
1408                        DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS_DEFAULT);
1409            }
1410
1411            mDataStallAlarmTag += 1;
1412            if (VDBG_STALL) {
1413                log("startDataStallAlarm: tag=" + mDataStallAlarmTag +
1414                        " delay=" + (delayInMs / 1000) + "s");
1415            }
1416            Intent intent = new Intent(INTENT_DATA_STALL_ALARM);
1417            intent.putExtra(DATA_STALL_ALARM_TAG_EXTRA, mDataStallAlarmTag);
1418            mDataStallAlarmIntent = PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
1419                    PendingIntent.FLAG_UPDATE_CURRENT);
1420            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1421                    SystemClock.elapsedRealtime() + delayInMs, mDataStallAlarmIntent);
1422        } else {
1423            if (VDBG_STALL) {
1424                log("startDataStallAlarm: NOT started, no connection tag=" + mDataStallAlarmTag);
1425            }
1426        }
1427    }
1428
1429    protected void stopDataStallAlarm() {
1430        if (VDBG_STALL) {
1431            log("stopDataStallAlarm: current tag=" + mDataStallAlarmTag +
1432                    " mDataStallAlarmIntent=" + mDataStallAlarmIntent);
1433        }
1434        mDataStallAlarmTag += 1;
1435        if (mDataStallAlarmIntent != null) {
1436            mAlarmManager.cancel(mDataStallAlarmIntent);
1437            mDataStallAlarmIntent = null;
1438        }
1439    }
1440
1441    protected void restartDataStallAlarm() {
1442        if (isConnected() == false) return;
1443        // To be called on screen status change.
1444        // Do not cancel the alarm if it is set with aggressive timeout.
1445        int nextAction = getRecoveryAction();
1446
1447        if (RecoveryAction.isAggressiveRecovery(nextAction)) {
1448            if (DBG) log("restartDataStallAlarm: action is pending. not resetting the alarm.");
1449            return;
1450        }
1451        if (VDBG_STALL) log("restartDataStallAlarm: stop then start.");
1452        stopDataStallAlarm();
1453        startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
1454    }
1455
1456    void sendCleanUpConnection(boolean tearDown, ApnContext apnContext) {
1457        if (DBG)log("sendCleanUpConnection: tearDown=" + tearDown + " apnContext=" + apnContext);
1458        Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_CONNECTION);
1459        msg.arg1 = tearDown ? 1 : 0;
1460        msg.arg2 = 0;
1461        msg.obj = apnContext;
1462        sendMessage(msg);
1463    }
1464
1465    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1466        pw.println("DataConnectionTrackerBase:");
1467        pw.println(" RADIO_TESTS=" + RADIO_TESTS);
1468        pw.println(" mInternalDataEnabled=" + mInternalDataEnabled);
1469        pw.println(" mUserDataEnabled=" + mUserDataEnabled);
1470        pw.println(" sPolicyDataEnabed=" + sPolicyDataEnabled);
1471        pw.println(" mDataEnabled:");
1472        for(int i=0; i < mDataEnabled.length; i++) {
1473            pw.printf("  mDataEnabled[%d]=%b\n", i, mDataEnabled[i]);
1474        }
1475        pw.flush();
1476        pw.println(" mEnabledCount=" + mEnabledCount);
1477        pw.println(" mRequestedApnType=" + mRequestedApnType);
1478        pw.println(" mPhone=" + mPhone.getPhoneName());
1479        pw.println(" mActivity=" + mActivity);
1480        pw.println(" mState=" + mState);
1481        pw.println(" mTxPkts=" + mTxPkts);
1482        pw.println(" mRxPkts=" + mRxPkts);
1483        pw.println(" mNetStatPollPeriod=" + mNetStatPollPeriod);
1484        pw.println(" mNetStatPollEnabled=" + mNetStatPollEnabled);
1485        pw.println(" mDataStallTxRxSum=" + mDataStallTxRxSum);
1486        pw.println(" mDataStallAlarmTag=" + mDataStallAlarmTag);
1487        pw.println(" mSentSinceLastRecv=" + mSentSinceLastRecv);
1488        pw.println(" mNoRecvPollCount=" + mNoRecvPollCount);
1489        pw.println(" mResolver=" + mResolver);
1490        pw.println(" mIsWifiConnected=" + mIsWifiConnected);
1491        pw.println(" mReconnectIntent=" + mReconnectIntent);
1492        pw.println(" mCidActive=" + mCidActive);
1493        pw.println(" mAutoAttachOnCreation=" + mAutoAttachOnCreation);
1494        pw.println(" mIsScreenOn=" + mIsScreenOn);
1495        pw.println(" mUniqueIdGenerator=" + mUniqueIdGenerator);
1496        pw.flush();
1497        pw.println(" ***************************************");
1498        DcController dcc = mDcc;
1499        if (dcc != null) {
1500            dcc.dump(fd, pw, args);
1501        } else {
1502            pw.println(" mDcc=null");
1503        }
1504        pw.println(" ***************************************");
1505        HashMap<Integer, DataConnection> dcs = mDataConnections;
1506        if (dcs != null) {
1507            Set<Entry<Integer, DataConnection> > mDcSet = mDataConnections.entrySet();
1508            pw.println(" mDataConnections: count=" + mDcSet.size());
1509            for (Entry<Integer, DataConnection> entry : mDcSet) {
1510                pw.printf(" *** mDataConnection[%d] \n", entry.getKey());
1511                entry.getValue().dump(fd, pw, args);
1512            }
1513        } else {
1514            pw.println("mDataConnections=null");
1515        }
1516        pw.println(" ***************************************");
1517        pw.flush();
1518        HashMap<String, Integer> apnToDcId = mApnToDataConnectionId;
1519        if (apnToDcId != null) {
1520            Set<Entry<String, Integer>> apnToDcIdSet = apnToDcId.entrySet();
1521            pw.println(" mApnToDataConnectonId size=" + apnToDcIdSet.size());
1522            for (Entry<String, Integer> entry : apnToDcIdSet) {
1523                pw.printf(" mApnToDataConnectonId[%s]=%d\n", entry.getKey(), entry.getValue());
1524            }
1525        } else {
1526            pw.println("mApnToDataConnectionId=null");
1527        }
1528        pw.println(" ***************************************");
1529        pw.flush();
1530        ConcurrentHashMap<String, ApnContext> apnCtxs = mApnContexts;
1531        if (apnCtxs != null) {
1532            Set<Entry<String, ApnContext>> apnCtxsSet = apnCtxs.entrySet();
1533            pw.println(" mApnContexts size=" + apnCtxsSet.size());
1534            for (Entry<String, ApnContext> entry : apnCtxsSet) {
1535                entry.getValue().dump(fd, pw, args);
1536            }
1537            pw.println(" ***************************************");
1538        } else {
1539            pw.println(" mApnContexts=null");
1540        }
1541        pw.flush();
1542        pw.println(" mActiveApn=" + mActiveApn);
1543        ArrayList<ApnSetting> apnSettings = mAllApnSettings;
1544        if (apnSettings != null) {
1545            pw.println(" mAllApnSettings size=" + apnSettings.size());
1546            for (int i=0; i < apnSettings.size(); i++) {
1547                pw.printf(" mAllApnSettings[%d]: %s\n", i, apnSettings.get(i));
1548            }
1549            pw.flush();
1550        } else {
1551            pw.println(" mAllApnSettings=null");
1552        }
1553        pw.println(" mPreferredApn=" + mPreferredApn);
1554        pw.println(" mIsPsRestricted=" + mIsPsRestricted);
1555        pw.println(" mIsDisposed=" + mIsDisposed);
1556        pw.println(" mIntentReceiver=" + mIntentReceiver);
1557        pw.println(" mDataRoamingSettingObserver=" + mDataRoamingSettingObserver);
1558        pw.flush();
1559    }
1560}
1561