DcTrackerBase.java revision 86d2fb21cbf5d72fdae36dbe6566ebc6047081c7
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.ConnectivityManager;
29import android.net.LinkProperties;
30import android.net.NetworkCapabilities;
31import android.net.NetworkInfo;
32import android.net.TrafficStats;
33import android.net.wifi.WifiManager;
34import android.os.AsyncResult;
35import android.os.Build;
36import android.os.Bundle;
37import android.os.Handler;
38import android.os.HandlerThread;
39import android.os.Message;
40import android.os.SystemClock;
41import android.os.SystemProperties;
42import android.preference.PreferenceManager;
43import android.provider.Settings;
44import android.provider.Settings.SettingNotFoundException;
45import android.telephony.ServiceState;
46import android.telephony.SubscriptionManager;
47import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
48import android.telephony.TelephonyManager;
49import android.text.TextUtils;
50import android.util.EventLog;
51import android.util.LocalLog;
52import android.telephony.Rlog;
53
54import com.android.internal.R;
55import com.android.internal.telephony.DctConstants;
56import com.android.internal.telephony.EventLogTags;
57import com.android.internal.telephony.Phone;
58import com.android.internal.telephony.PhoneBase;
59import com.android.internal.telephony.PhoneConstants;
60import com.android.internal.telephony.uicc.IccRecords;
61import com.android.internal.telephony.uicc.UiccController;
62import com.android.internal.util.AsyncChannel;
63import com.android.internal.util.ArrayUtils;
64
65import java.io.FileDescriptor;
66import java.io.PrintWriter;
67import java.util.ArrayList;
68import java.util.Comparator;
69import java.util.HashMap;
70import java.util.List;
71import java.util.Map.Entry;
72import java.util.Set;
73import java.util.concurrent.ConcurrentHashMap;
74import java.util.concurrent.atomic.AtomicBoolean;
75import java.util.concurrent.atomic.AtomicInteger;
76import java.util.concurrent.atomic.AtomicReference;
77import java.util.PriorityQueue;
78
79/**
80 * {@hide}
81 */
82public abstract class DcTrackerBase extends Handler {
83    protected static final boolean DBG = true;
84    protected static final boolean VDBG = false; // STOPSHIP if true
85    protected static final boolean VDBG_STALL = false; // STOPSHIP if true
86    protected static final boolean RADIO_TESTS = false;
87
88    static boolean mIsCleanupRequired = false;
89    /**
90     * Constants for the data connection activity:
91     * physical link down/up
92     */
93    protected static final int DATA_CONNECTION_ACTIVE_PH_LINK_INACTIVE = 0;
94    protected static final int DATA_CONNECTION_ACTIVE_PH_LINK_DOWN = 1;
95    protected static final int DATA_CONNECTION_ACTIVE_PH_LINK_UP = 2;
96
97    /** Delay between APN attempts.
98        Note the property override mechanism is there just for testing purpose only. */
99    protected static final int APN_DELAY_DEFAULT_MILLIS = 20000;
100
101    /** Delay between APN attempts when in fail fast mode */
102    protected static final int APN_FAIL_FAST_DELAY_DEFAULT_MILLIS = 3000;
103
104    AlarmManager mAlarmManager;
105
106    protected Object mDataEnabledLock = new Object();
107
108    // responds to the setInternalDataEnabled call - used internally to turn off data
109    // for example during emergency calls
110    protected boolean mInternalDataEnabled = true;
111
112    // responds to public (user) API to enable/disable data use
113    // independent of mInternalDataEnabled and requests for APN access
114    // persisted
115    protected boolean mUserDataEnabled = true;
116
117    // TODO: move away from static state once 5587429 is fixed.
118    protected static boolean sPolicyDataEnabled = true;
119
120    private boolean[] mDataEnabled = new boolean[DctConstants.APN_NUM_TYPES];
121
122    private int mEnabledCount = 0;
123
124    /* Currently requested APN type (TODO: This should probably be a parameter not a member) */
125    protected String mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
126
127    /** Retry configuration: A doubling of retry times from 5secs to 30minutes */
128    protected static final String DEFAULT_DATA_RETRY_CONFIG = "default_randomization=2000,"
129        + "5000,10000,20000,40000,80000:5000,160000:5000,"
130        + "320000:5000,640000:5000,1280000:5000,1800000:5000";
131
132    /** Retry configuration for secondary networks: 4 tries in 20 sec */
133    protected static final String SECONDARY_DATA_RETRY_CONFIG =
134            "max_retries=3, 5000, 5000, 5000";
135
136    /** Slow poll when attempting connection recovery. */
137    protected static final int POLL_NETSTAT_SLOW_MILLIS = 5000;
138    /** Default max failure count before attempting to network re-registration. */
139    protected static final int DEFAULT_MAX_PDP_RESET_FAIL = 3;
140
141    /**
142     * After detecting a potential connection problem, this is the max number
143     * of subsequent polls before attempting recovery.
144     */
145    protected static final int NO_RECV_POLL_LIMIT = 24;
146    // 1 sec. default polling interval when screen is on.
147    protected static final int POLL_NETSTAT_MILLIS = 1000;
148    // 10 min. default polling interval when screen is off.
149    protected static final int POLL_NETSTAT_SCREEN_OFF_MILLIS = 1000*60*10;
150    // 2 min for round trip time
151    protected static final int POLL_LONGEST_RTT = 120 * 1000;
152    // Default sent packets without ack which triggers initial recovery steps
153    protected static final int NUMBER_SENT_PACKETS_OF_HANG = 10;
154    // how long to wait before switching back to default APN
155    protected static final int RESTORE_DEFAULT_APN_DELAY = 1 * 60 * 1000;
156    // system property that can override the above value
157    protected static final String APN_RESTORE_DELAY_PROP_NAME = "android.telephony.apn-restore";
158    // represents an invalid IP address
159    protected static final String NULL_IP = "0.0.0.0";
160
161    // Default for the data stall alarm while non-aggressive stall detection
162    protected static final int DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS_DEFAULT = 1000 * 60 * 6;
163    // Default for the data stall alarm for aggressive stall detection
164    protected static final int DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS_DEFAULT = 1000 * 60;
165    // If attempt is less than this value we're doing first level recovery
166    protected static final int DATA_STALL_NO_RECV_POLL_LIMIT = 1;
167    // Tag for tracking stale alarms
168    protected static final String DATA_STALL_ALARM_TAG_EXTRA = "data.stall.alram.tag";
169
170    protected static final boolean DATA_STALL_SUSPECTED = true;
171    protected static final boolean DATA_STALL_NOT_SUSPECTED = false;
172
173    protected String RADIO_RESET_PROPERTY = "gsm.radioreset";
174
175    protected static final String INTENT_RECONNECT_ALARM =
176            "com.android.internal.telephony.data-reconnect";
177    protected static final String INTENT_RECONNECT_ALARM_EXTRA_TYPE = "reconnect_alarm_extra_type";
178    protected static final String INTENT_RECONNECT_ALARM_EXTRA_REASON =
179            "reconnect_alarm_extra_reason";
180
181    protected static final String INTENT_RESTART_TRYSETUP_ALARM =
182            "com.android.internal.telephony.data-restart-trysetup";
183    protected static final String INTENT_RESTART_TRYSETUP_ALARM_EXTRA_TYPE =
184            "restart_trysetup_alarm_extra_type";
185
186    protected static final String INTENT_DATA_STALL_ALARM =
187            "com.android.internal.telephony.data-stall";
188
189
190
191    protected static final String DEFALUT_DATA_ON_BOOT_PROP = "net.def_data_on_boot";
192
193    protected DcTesterFailBringUpAll mDcTesterFailBringUpAll;
194    protected DcController mDcc;
195
196    // member variables
197    protected PhoneBase mPhone;
198    protected UiccController mUiccController;
199    protected AtomicReference<IccRecords> mIccRecords = new AtomicReference<IccRecords>();
200    protected DctConstants.Activity mActivity = DctConstants.Activity.NONE;
201    protected DctConstants.State mState = DctConstants.State.IDLE;
202    protected Handler mDataConnectionTracker = null;
203
204    protected long mTxPkts;
205    protected long mRxPkts;
206    protected int mNetStatPollPeriod;
207    protected boolean mNetStatPollEnabled = false;
208
209    protected TxRxSum mDataStallTxRxSum = new TxRxSum(0, 0);
210    // Used to track stale data stall alarms.
211    protected int mDataStallAlarmTag = (int) SystemClock.elapsedRealtime();
212    // The current data stall alarm intent
213    protected PendingIntent mDataStallAlarmIntent = null;
214    // Number of packets sent since the last received packet
215    protected long mSentSinceLastRecv;
216    // Controls when a simple recovery attempt it to be tried
217    protected int mNoRecvPollCount = 0;
218    // Refrence counter for enabling fail fast
219    protected static int sEnableFailFastRefCounter = 0;
220    // True if data stall detection is enabled
221    protected volatile boolean mDataStallDetectionEnabled = true;
222
223    protected volatile boolean mFailFast = false;
224
225    // True when in voice call
226    protected boolean mInVoiceCall = false;
227
228    // wifi connection status will be updated by sticky intent
229    protected boolean mIsWifiConnected = false;
230
231    /** Intent sent when the reconnect alarm fires. */
232    protected PendingIntent mReconnectIntent = null;
233
234    /** CID of active data connection */
235    protected int mCidActive;
236
237    // When false we will not auto attach and manually attaching is required.
238    protected boolean mAutoAttachOnCreationConfig = false;
239    protected AtomicBoolean mAutoAttachOnCreation = new AtomicBoolean(false);
240
241    // State of screen
242    // (TODO: Reconsider tying directly to screen, maybe this is
243    //        really a lower power mode")
244    protected boolean mIsScreenOn = true;
245
246    /** Allows the generation of unique Id's for DataConnection objects */
247    protected AtomicInteger mUniqueIdGenerator = new AtomicInteger(0);
248
249    /** The data connections. */
250    protected HashMap<Integer, DataConnection> mDataConnections =
251        new HashMap<Integer, DataConnection>();
252
253    /** The data connection async channels */
254    protected HashMap<Integer, DcAsyncChannel> mDataConnectionAcHashMap =
255        new HashMap<Integer, DcAsyncChannel>();
256
257    /** Convert an ApnType string to Id (TODO: Use "enumeration" instead of String for ApnType) */
258    protected HashMap<String, Integer> mApnToDataConnectionId =
259                                    new HashMap<String, Integer>();
260
261    /** Phone.APN_TYPE_* ===> ApnContext */
262    protected final ConcurrentHashMap<String, ApnContext> mApnContexts =
263                                    new ConcurrentHashMap<String, ApnContext>();
264
265    /** kept in sync with mApnContexts
266     * Higher numbers are higher priority and sorted so highest priority is first */
267    protected final PriorityQueue<ApnContext>mPrioritySortedApnContexts =
268            new PriorityQueue<ApnContext>(5,
269            new Comparator<ApnContext>() {
270                public int compare(ApnContext c1, ApnContext c2) {
271                    return c2.priority - c1.priority;
272                }
273            } );
274
275    /* Currently active APN */
276    protected ApnSetting mActiveApn;
277
278    /** allApns holds all apns */
279    protected ArrayList<ApnSetting> mAllApnSettings = null;
280
281    /** preferred apn */
282    protected ApnSetting mPreferredApn = null;
283
284    /** Is packet service restricted by network */
285    protected boolean mIsPsRestricted = false;
286
287    /** emergency apn Setting*/
288    protected ApnSetting mEmergencyApn = null;
289
290    /* Once disposed dont handle any messages */
291    protected boolean mIsDisposed = false;
292
293    protected ContentResolver mResolver;
294
295    /* Set to true with CMD_ENABLE_MOBILE_PROVISIONING */
296    protected boolean mIsProvisioning = false;
297
298    /* The Url passed as object parameter in CMD_ENABLE_MOBILE_PROVISIONING */
299    protected String mProvisioningUrl = null;
300
301    /* Intent for the provisioning apn alarm */
302    protected static final String INTENT_PROVISIONING_APN_ALARM =
303            "com.android.internal.telephony.provisioning_apn_alarm";
304
305    /* Tag for tracking stale alarms */
306    protected static final String PROVISIONING_APN_ALARM_TAG_EXTRA = "provisioning.apn.alarm.tag";
307
308    /* Debug property for overriding the PROVISIONING_APN_ALARM_DELAY_IN_MS */
309    protected static final String DEBUG_PROV_APN_ALARM =
310            "persist.debug.prov_apn_alarm";
311
312    /* Default for the provisioning apn alarm timeout */
313    protected static final int PROVISIONING_APN_ALARM_DELAY_IN_MS_DEFAULT = 1000 * 60 * 15;
314
315    /* The provision apn alarm intent used to disable the provisioning apn */
316    protected PendingIntent mProvisioningApnAlarmIntent = null;
317
318    /* Used to track stale provisioning apn alarms */
319    protected int mProvisioningApnAlarmTag = (int) SystemClock.elapsedRealtime();
320
321    protected AsyncChannel mReplyAc = new AsyncChannel();
322
323    protected BroadcastReceiver mIntentReceiver = new BroadcastReceiver ()
324    {
325        @Override
326        public void onReceive(Context context, Intent intent)
327        {
328            String action = intent.getAction();
329            if (DBG) log("onReceive: action=" + action);
330            if (action.equals(Intent.ACTION_SCREEN_ON)) {
331                mIsScreenOn = true;
332                stopNetStatPoll();
333                startNetStatPoll();
334                restartDataStallAlarm();
335            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
336                mIsScreenOn = false;
337                stopNetStatPoll();
338                startNetStatPoll();
339                restartDataStallAlarm();
340            } else if (action.startsWith(INTENT_RECONNECT_ALARM)) {
341                if (DBG) log("Reconnect alarm. Previous state was " + mState);
342                onActionIntentReconnectAlarm(intent);
343            } else if (action.startsWith(INTENT_RESTART_TRYSETUP_ALARM)) {
344                if (DBG) log("Restart trySetup alarm");
345                onActionIntentRestartTrySetupAlarm(intent);
346            } else if (action.equals(INTENT_DATA_STALL_ALARM)) {
347                onActionIntentDataStallAlarm(intent);
348            } else if (action.equals(INTENT_PROVISIONING_APN_ALARM)) {
349                onActionIntentProvisioningApnAlarm(intent);
350            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
351                final android.net.NetworkInfo networkInfo = (NetworkInfo)
352                        intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
353                mIsWifiConnected = (networkInfo != null && networkInfo.isConnected());
354                if (DBG) log("NETWORK_STATE_CHANGED_ACTION: mIsWifiConnected=" + mIsWifiConnected);
355            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
356                final boolean enabled = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
357                        WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_ENABLED;
358
359                if (!enabled) {
360                    // when WiFi got disabled, the NETWORK_STATE_CHANGED_ACTION
361                    // quit and won't report disconnected until next enabling.
362                    mIsWifiConnected = false;
363                }
364                if (DBG) log("WIFI_STATE_CHANGED_ACTION: enabled=" + enabled
365                        + " mIsWifiConnected=" + mIsWifiConnected);
366            }
367        }
368    };
369
370    private Runnable mPollNetStat = new Runnable()
371    {
372        @Override
373        public void run() {
374            updateDataActivity();
375
376            if (mIsScreenOn) {
377                mNetStatPollPeriod = Settings.Global.getInt(mResolver,
378                        Settings.Global.PDP_WATCHDOG_POLL_INTERVAL_MS, POLL_NETSTAT_MILLIS);
379            } else {
380                mNetStatPollPeriod = Settings.Global.getInt(mResolver,
381                        Settings.Global.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS,
382                        POLL_NETSTAT_SCREEN_OFF_MILLIS);
383            }
384
385            if (mNetStatPollEnabled) {
386                mDataConnectionTracker.postDelayed(this, mNetStatPollPeriod);
387            }
388        }
389    };
390
391    private SubscriptionManager mSubscriptionManager;
392    private final OnSubscriptionsChangedListener mOnSubscriptionsChangedListener =
393            new OnSubscriptionsChangedListener() {
394        /**
395         * Callback invoked when there is any change to any SubscriptionInfo. Typically
396         * this method would invoke {@link SubscriptionManager#getActiveSubscriptionInfoList}
397         */
398        @Override
399        public void onSubscriptionsChanged() {
400            if (DBG) log("SubscriptionListener.onSubscriptionInfoChanged");
401            // Set the network type, in case the radio does not restore it.
402            int subId = mPhone.getSubId();
403            if (SubscriptionManager.isValidSubscriptionId(subId)) {
404                if (mDataRoamingSettingObserver != null) {
405                    mDataRoamingSettingObserver.unregister();
406                }
407                // Watch for changes to Settings.Global.DATA_ROAMING
408                mDataRoamingSettingObserver = new DataRoamingSettingObserver(mPhone,
409                        mPhone.getContext());
410                mDataRoamingSettingObserver.register();
411            }
412        }
413    };
414
415    private class DataRoamingSettingObserver extends ContentObserver {
416
417        public DataRoamingSettingObserver(Handler handler, Context context) {
418            super(handler);
419            mResolver = context.getContentResolver();
420        }
421
422        public void register() {
423            String contentUri;
424            if (TelephonyManager.getDefault().getSimCount() == 1) {
425                contentUri = Settings.Global.DATA_ROAMING;
426            } else {
427                contentUri = Settings.Global.DATA_ROAMING + mPhone.getSubId();
428            }
429
430            mResolver.registerContentObserver(Settings.Global.getUriFor(contentUri), false, this);
431        }
432
433        public void unregister() {
434            mResolver.unregisterContentObserver(this);
435        }
436
437        @Override
438        public void onChange(boolean selfChange) {
439            // already running on mPhone handler thread
440            if (mPhone.getServiceState().getDataRoaming()) {
441                sendMessage(obtainMessage(DctConstants.EVENT_ROAMING_ON));
442            }
443        }
444    }
445    private DataRoamingSettingObserver mDataRoamingSettingObserver;
446
447    /**
448     * The Initial MaxRetry sent to a DataConnection as a parameter
449     * to DataConnectionAc.bringUp. This value can be defined at compile
450     * time using the SystemProperty Settings.Global.DCT_INITIAL_MAX_RETRY
451     * and at runtime using gservices to change Settings.Global.DCT_INITIAL_MAX_RETRY.
452     */
453    private static final int DEFAULT_MDC_INITIAL_RETRY = 1;
454    protected int getInitialMaxRetry() {
455        if (mFailFast) {
456            return 0;
457        }
458        // Get default value from system property or use DEFAULT_MDC_INITIAL_RETRY
459        int value = SystemProperties.getInt(
460                Settings.Global.MDC_INITIAL_MAX_RETRY, DEFAULT_MDC_INITIAL_RETRY);
461        if (value == DEFAULT_MDC_INITIAL_RETRY) {
462            value = mPhone.getContext().getResources().getInteger(
463                R.integer.config_mdc_initial_max_retry);
464        }
465
466        // Check if its been overridden
467        return Settings.Global.getInt(mResolver,
468                Settings.Global.MDC_INITIAL_MAX_RETRY, value);
469    }
470
471    /**
472     * Maintain the sum of transmit and receive packets.
473     *
474     * The packet counts are initialized and reset to -1 and
475     * remain -1 until they can be updated.
476     */
477    public class TxRxSum {
478        public long txPkts;
479        public long rxPkts;
480
481        public TxRxSum() {
482            reset();
483        }
484
485        public TxRxSum(long txPkts, long rxPkts) {
486            this.txPkts = txPkts;
487            this.rxPkts = rxPkts;
488        }
489
490        public TxRxSum(TxRxSum sum) {
491            txPkts = sum.txPkts;
492            rxPkts = sum.rxPkts;
493        }
494
495        public void reset() {
496            txPkts = -1;
497            rxPkts = -1;
498        }
499
500        @Override
501        public String toString() {
502            return "{txSum=" + txPkts + " rxSum=" + rxPkts + "}";
503        }
504
505        public void updateTxRxSum() {
506            this.txPkts = TrafficStats.getMobileTcpTxPackets();
507            this.rxPkts = TrafficStats.getMobileTcpRxPackets();
508        }
509    }
510
511    protected void onActionIntentReconnectAlarm(Intent intent) {
512        String reason = intent.getStringExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON);
513        String apnType = intent.getStringExtra(INTENT_RECONNECT_ALARM_EXTRA_TYPE);
514
515        int phoneSubId = mPhone.getSubId();
516        int currSubId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY,
517                SubscriptionManager.INVALID_SUBSCRIPTION_ID);
518        log("onActionIntentReconnectAlarm: currSubId = " + currSubId + " phoneSubId=" + phoneSubId);
519
520        // Stop reconnect if not current subId is not correct.
521        // FIXME STOPSHIP - phoneSubId is coming up as -1 way after boot and failing this?
522        if (!SubscriptionManager.isValidSubscriptionId(currSubId) || (currSubId != phoneSubId)) {
523            log("receive ReconnectAlarm but subId incorrect, ignore");
524            return;
525        }
526
527        ApnContext apnContext = mApnContexts.get(apnType);
528
529        if (DBG) {
530            log("onActionIntentReconnectAlarm: mState=" + mState + " reason=" + reason +
531                    " apnType=" + apnType + " apnContext=" + apnContext +
532                    " mDataConnectionAsyncChannels=" + mDataConnectionAcHashMap);
533        }
534
535        if ((apnContext != null) && (apnContext.isEnabled())) {
536            apnContext.setReason(reason);
537            DctConstants.State apnContextState = apnContext.getState();
538            if (DBG) {
539                log("onActionIntentReconnectAlarm: apnContext state=" + apnContextState);
540            }
541            if ((apnContextState == DctConstants.State.FAILED)
542                    || (apnContextState == DctConstants.State.IDLE)) {
543                if (DBG) {
544                    log("onActionIntentReconnectAlarm: state is FAILED|IDLE, disassociate");
545                }
546                DcAsyncChannel dcac = apnContext.getDcAc();
547                if (dcac != null) {
548                    if (DBG) {
549                        log("onActionIntentReconnectAlarm: tearDown apnContext=" + apnContext);
550                    }
551                    dcac.tearDown(apnContext, "", null);
552                }
553                apnContext.setDataConnectionAc(null);
554                apnContext.setState(DctConstants.State.IDLE);
555            } else {
556                if (DBG) log("onActionIntentReconnectAlarm: keep associated");
557            }
558            // TODO: IF already associated should we send the EVENT_TRY_SETUP_DATA???
559            sendMessage(obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, apnContext));
560
561            apnContext.setReconnectIntent(null);
562        }
563    }
564
565    protected void onActionIntentRestartTrySetupAlarm(Intent intent) {
566        String apnType = intent.getStringExtra(INTENT_RESTART_TRYSETUP_ALARM_EXTRA_TYPE);
567        ApnContext apnContext = mApnContexts.get(apnType);
568        if (DBG) {
569            log("onActionIntentRestartTrySetupAlarm: mState=" + mState +
570                    " apnType=" + apnType + " apnContext=" + apnContext +
571                    " mDataConnectionAsyncChannels=" + mDataConnectionAcHashMap);
572        }
573        sendMessage(obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, apnContext));
574    }
575
576    protected void onActionIntentDataStallAlarm(Intent intent) {
577        if (VDBG_STALL) log("onActionIntentDataStallAlarm: action=" + intent.getAction());
578        Message msg = obtainMessage(DctConstants.EVENT_DATA_STALL_ALARM,
579                intent.getAction());
580        msg.arg1 = intent.getIntExtra(DATA_STALL_ALARM_TAG_EXTRA, 0);
581        sendMessage(msg);
582    }
583
584    ConnectivityManager mCm;
585
586    /**
587     * Default constructor
588     */
589    protected DcTrackerBase(PhoneBase phone) {
590        super();
591        mPhone = phone;
592        if (DBG) log("DCT.constructor");
593        mResolver = mPhone.getContext().getContentResolver();
594        mUiccController = UiccController.getInstance();
595        mUiccController.registerForIccChanged(this, DctConstants.EVENT_ICC_CHANGED, null);
596        mAlarmManager =
597                (AlarmManager) mPhone.getContext().getSystemService(Context.ALARM_SERVICE);
598        mCm = (ConnectivityManager) mPhone.getContext().getSystemService(
599                Context.CONNECTIVITY_SERVICE);
600
601
602        int phoneSubId = mPhone.getSubId();
603        IntentFilter filter = new IntentFilter();
604        filter.addAction(Intent.ACTION_SCREEN_ON);
605        filter.addAction(Intent.ACTION_SCREEN_OFF);
606        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
607        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
608        filter.addAction(INTENT_DATA_STALL_ALARM);
609        filter.addAction(INTENT_PROVISIONING_APN_ALARM);
610
611        mUserDataEnabled = getDataEnabled();
612
613        mPhone.getContext().registerReceiver(mIntentReceiver, filter, null, mPhone);
614
615        // This preference tells us 1) initial condition for "dataEnabled",
616        // and 2) whether the RIL will setup the baseband to auto-PS attach.
617
618        mDataEnabled[DctConstants.APN_DEFAULT_ID] =
619                SystemProperties.getBoolean(DEFALUT_DATA_ON_BOOT_PROP,true);
620        if (mDataEnabled[DctConstants.APN_DEFAULT_ID]) {
621            mEnabledCount++;
622        }
623
624        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mPhone.getContext());
625        mAutoAttachOnCreation.set(sp.getBoolean(PhoneBase.DATA_DISABLED_ON_BOOT_KEY, false));
626
627        mSubscriptionManager = SubscriptionManager.from(mPhone.getContext());
628        mSubscriptionManager
629                .addOnSubscriptionsChangedListener(mOnSubscriptionsChangedListener);
630
631        HandlerThread dcHandlerThread = new HandlerThread("DcHandlerThread");
632        dcHandlerThread.start();
633        Handler dcHandler = new Handler(dcHandlerThread.getLooper());
634        mDcc = DcController.makeDcc(mPhone, this, dcHandler);
635        mDcTesterFailBringUpAll = new DcTesterFailBringUpAll(mPhone, dcHandler);
636    }
637
638    public void dispose() {
639        if (DBG) log("DCT.dispose");
640        for (DcAsyncChannel dcac : mDataConnectionAcHashMap.values()) {
641            dcac.disconnect();
642        }
643        mDataConnectionAcHashMap.clear();
644        mIsDisposed = true;
645        mPhone.getContext().unregisterReceiver(mIntentReceiver);
646        mUiccController.unregisterForIccChanged(this);
647        if (mDataRoamingSettingObserver != null) {
648            mDataRoamingSettingObserver.unregister();
649        }
650        mSubscriptionManager
651                .removeOnSubscriptionsChangedListener(mOnSubscriptionsChangedListener);
652        mDcc.dispose();
653        mDcTesterFailBringUpAll.dispose();
654    }
655
656    public long getSubId() {
657        return mPhone.getSubId();
658    }
659
660    public DctConstants.Activity getActivity() {
661        return mActivity;
662    }
663
664    void setActivity(DctConstants.Activity activity) {
665        log("setActivity = " + activity);
666        mActivity = activity;
667        mPhone.notifyDataActivity();
668    }
669
670    abstract public void incApnRefCount(String name, LocalLog log);
671
672    abstract public void decApnRefCount(String name, LocalLog log);
673
674    public boolean isApnSupported(String name) {
675        return false;
676    }
677
678    public int getApnPriority(String name) {
679        return -1;
680    }
681
682
683    public boolean isApnTypeActive(String type) {
684        // TODO: support simultaneous with List instead
685        if (PhoneConstants.APN_TYPE_DUN.equals(type)) {
686            ApnSetting dunApn = fetchDunApn();
687            if (dunApn != null) {
688                return ((mActiveApn != null) && (dunApn.toString().equals(mActiveApn.toString())));
689            }
690        }
691        return mActiveApn != null && mActiveApn.canHandleType(type);
692    }
693
694    protected ApnSetting fetchDunApn() {
695        if (SystemProperties.getBoolean("net.tethering.noprovisioning", false)) {
696            log("fetchDunApn: net.tethering.noprovisioning=true ret: null");
697            return null;
698        }
699        int bearer = mPhone.getServiceState().getRilDataRadioTechnology();
700        ApnSetting retDunSetting = null;
701        String apnData = Settings.Global.getString(mResolver, Settings.Global.TETHER_DUN_APN);
702        List<ApnSetting> dunSettings = ApnSetting.arrayFromString(apnData);
703        IccRecords r = mIccRecords.get();
704        for (ApnSetting dunSetting : dunSettings) {
705            String operator = (r != null) ? r.getOperatorNumeric() : "";
706            if (!ServiceState.bitmaskHasTech(dunSetting.bearerBitmask, bearer)) continue;
707            if (dunSetting.numeric.equals(operator)) {
708                if (dunSetting.hasMvnoParams()) {
709                    if (r != null && ApnSetting.mvnoMatches(r, dunSetting.mvnoType,
710                            dunSetting.mvnoMatchData)) {
711                        if (VDBG) {
712                            log("fetchDunApn: global TETHER_DUN_APN dunSetting=" + dunSetting);
713                        }
714                        return dunSetting;
715                    }
716                } else {
717                    if (VDBG) log("fetchDunApn: global TETHER_DUN_APN dunSetting=" + dunSetting);
718                    return dunSetting;
719                }
720            }
721        }
722
723        Context c = mPhone.getContext();
724        String[] apnArrayData = c.getResources().getStringArray(R.array.config_tether_apndata);
725        for (String apn : apnArrayData) {
726            ApnSetting dunSetting = ApnSetting.fromString(apn);
727            if (dunSetting != null) {
728                if (!ServiceState.bitmaskHasTech(dunSetting.bearerBitmask, bearer)) continue;
729                if (dunSetting.hasMvnoParams()) {
730                    if (r != null && ApnSetting.mvnoMatches(r, dunSetting.mvnoType,
731                            dunSetting.mvnoMatchData)) {
732                        if (VDBG) {
733                            log("fetchDunApn: config_tether_apndata mvno dunSetting=" + dunSetting);
734                        }
735                        return dunSetting;
736                    }
737                } else {
738                    retDunSetting = dunSetting;
739                }
740            }
741        }
742
743        if (VDBG) log("fetchDunApn: config_tether_apndata dunSetting=" + retDunSetting);
744        return retDunSetting;
745    }
746
747    public boolean hasMatchedTetherApnSetting() {
748        ApnSetting matched = fetchDunApn();
749        log("hasMatchedTetherApnSetting: APN=" + matched);
750        return matched != null;
751    }
752
753    public String[] getActiveApnTypes() {
754        String[] result;
755        if (mActiveApn != null) {
756            result = mActiveApn.types;
757        } else {
758            result = new String[1];
759            result[0] = PhoneConstants.APN_TYPE_DEFAULT;
760        }
761        return result;
762    }
763
764    /** TODO: See if we can remove */
765    public String getActiveApnString(String apnType) {
766        String result = null;
767        if (mActiveApn != null) {
768            result = mActiveApn.apn;
769        }
770        return result;
771    }
772
773    /**
774     * Modify {@link android.provider.Settings.Global#DATA_ROAMING} value.
775     */
776    public void setDataOnRoamingEnabled(boolean enabled) {
777        final int phoneSubId = mPhone.getSubId();
778        if (getDataOnRoamingEnabled() != enabled) {
779            int roaming = enabled ? 1 : 0;
780
781            // For single SIM phones, this is a per phone property.
782            if (TelephonyManager.getDefault().getSimCount() == 1) {
783                Settings.Global.putInt(mResolver, Settings.Global.DATA_ROAMING, roaming);
784            } else {
785                Settings.Global.putInt(mResolver, Settings.Global.DATA_ROAMING + phoneSubId, roaming);
786            }
787
788            mSubscriptionManager.setDataRoaming(roaming, phoneSubId);
789            // will trigger handleDataOnRoamingChange() through observer
790            if (DBG) {
791               log("setDataOnRoamingEnabled: set phoneSubId=" + phoneSubId
792                       + " isRoaming=" + enabled);
793            }
794        } else {
795            if (DBG) {
796                log("setDataOnRoamingEnabled: unchanged phoneSubId=" + phoneSubId
797                        + " isRoaming=" + enabled);
798             }
799        }
800    }
801
802    /**
803     * Return current {@link android.provider.Settings.Global#DATA_ROAMING} value.
804     */
805    public boolean getDataOnRoamingEnabled() {
806        boolean isDataRoamingEnabled = "true".equalsIgnoreCase(SystemProperties.get(
807                "ro.com.android.dataroaming", "false"));
808        final int phoneSubId = mPhone.getSubId();
809
810        try {
811            // For single SIM phones, this is a per phone property.
812            if (TelephonyManager.getDefault().getSimCount() == 1) {
813                isDataRoamingEnabled = Settings.Global.getInt(mResolver,
814                        Settings.Global.DATA_ROAMING, isDataRoamingEnabled ? 1 : 0) != 0;
815            } else {
816                isDataRoamingEnabled = TelephonyManager.getIntWithSubId(mResolver,
817                        Settings.Global.DATA_ROAMING, phoneSubId) != 0;
818            }
819        } catch (SettingNotFoundException snfe) {
820            if (DBG) log("getDataOnRoamingEnabled: SettingNofFoundException snfe=" + snfe);
821        }
822        if (DBG) {
823            log("getDataOnRoamingEnabled: phoneSubId=" + phoneSubId +
824                    " isDataRoamingEnabled=" + isDataRoamingEnabled);
825        }
826        return isDataRoamingEnabled;
827    }
828
829    /**
830     * Modify {@link android.provider.Settings.Global#MOBILE_DATA} value.
831     */
832    public void setDataEnabled(boolean enable) {
833        Message msg = obtainMessage(DctConstants.CMD_SET_USER_DATA_ENABLE);
834        msg.arg1 = enable ? 1 : 0;
835        if (DBG) log("setDataEnabled: sendMessage: enable=" + enable);
836        sendMessage(msg);
837    }
838
839    /**
840     * Return current {@link android.provider.Settings.Global#MOBILE_DATA} value.
841     */
842    public boolean getDataEnabled() {
843        boolean retVal = "true".equalsIgnoreCase(SystemProperties.get(
844                "ro.com.android.mobiledata", "true"));
845        try {
846            if (TelephonyManager.getDefault().getSimCount() == 1) {
847                retVal = Settings.Global.getInt(mResolver, Settings.Global.MOBILE_DATA,
848                        retVal ? 1 : 0) != 0;
849            } else {
850                int phoneSubId = mPhone.getSubId();
851                retVal = TelephonyManager.getIntWithSubId(mResolver, Settings.Global.MOBILE_DATA,
852                        phoneSubId) != 0;
853            }
854            if (DBG) log("getDataEnabled: getIntWithSubId retVal=" + retVal);
855        } catch (SettingNotFoundException snfe) {
856            retVal = "true".equalsIgnoreCase(
857                    SystemProperties.get("ro.com.android.mobiledata", "true"));
858            if (DBG) {
859                log("getDataEnabled: system property ro.com.android.mobiledata retVal=" + retVal);
860            }
861        }
862        return retVal;
863    }
864
865    // abstract methods
866    protected abstract void restartRadio();
867    protected abstract void log(String s);
868    protected abstract void loge(String s);
869    protected abstract boolean isDataAllowed();
870    protected abstract boolean isApnTypeAvailable(String type);
871    public    abstract DctConstants.State getState(String apnType);
872    protected abstract boolean isProvisioningApn(String apnType);
873    protected abstract void setState(DctConstants.State s);
874    protected abstract void gotoIdleAndNotifyDataConnection(String reason);
875
876    protected abstract boolean onTrySetupData(String reason);
877    protected abstract void onRoamingOff();
878    protected abstract void onRoamingOn();
879    protected abstract void onRadioAvailable();
880    protected abstract void onRadioOffOrNotAvailable();
881    protected abstract void onDataSetupComplete(AsyncResult ar);
882    protected abstract void onDataSetupCompleteError(AsyncResult ar);
883    protected abstract void onDisconnectDone(int connId, AsyncResult ar);
884    protected abstract void onDisconnectDcRetrying(int connId, AsyncResult ar);
885    protected abstract void onVoiceCallStarted();
886    protected abstract void onVoiceCallEnded();
887    protected abstract void onCleanUpConnection(boolean tearDown, int apnId, String reason);
888    protected abstract void onCleanUpAllConnections(String cause);
889    public abstract boolean isDataPossible(String apnType);
890    protected abstract void onUpdateIcc();
891    protected abstract void completeConnection(ApnContext apnContext);
892    public abstract void setDataAllowed(boolean enable, Message response);
893    public abstract String[] getPcscfAddress(String apnType);
894    public abstract void setImsRegistrationState(boolean registered);
895    protected abstract boolean isPermanentFail(DcFailCause dcFailCause);
896
897    @Override
898    public void handleMessage(Message msg) {
899        switch (msg.what) {
900            case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
901                log("DISCONNECTED_CONNECTED: msg=" + msg);
902                DcAsyncChannel dcac = (DcAsyncChannel) msg.obj;
903                mDataConnectionAcHashMap.remove(dcac.getDataConnectionIdSync());
904                dcac.disconnected();
905                break;
906            }
907            case DctConstants.EVENT_ENABLE_NEW_APN:
908                onEnableApn(msg.arg1, msg.arg2);
909                break;
910
911            case DctConstants.EVENT_TRY_SETUP_DATA:
912                String reason = null;
913                if (msg.obj instanceof String) {
914                    reason = (String) msg.obj;
915                }
916                onTrySetupData(reason);
917                break;
918
919            case DctConstants.EVENT_DATA_STALL_ALARM:
920                onDataStallAlarm(msg.arg1);
921                break;
922
923            case DctConstants.EVENT_ROAMING_OFF:
924                onRoamingOff();
925                break;
926
927            case DctConstants.EVENT_ROAMING_ON:
928                onRoamingOn();
929                break;
930
931            case DctConstants.EVENT_RADIO_AVAILABLE:
932                onRadioAvailable();
933                break;
934
935            case DctConstants.EVENT_RADIO_OFF_OR_NOT_AVAILABLE:
936                onRadioOffOrNotAvailable();
937                break;
938
939            case DctConstants.EVENT_DATA_SETUP_COMPLETE:
940                mCidActive = msg.arg1;
941                onDataSetupComplete((AsyncResult) msg.obj);
942                break;
943
944            case DctConstants.EVENT_DATA_SETUP_COMPLETE_ERROR:
945                onDataSetupCompleteError((AsyncResult) msg.obj);
946                break;
947
948            case DctConstants.EVENT_DISCONNECT_DONE:
949                log("DataConnectionTracker.handleMessage: EVENT_DISCONNECT_DONE msg=" + msg);
950                onDisconnectDone(msg.arg1, (AsyncResult) msg.obj);
951                break;
952
953            case DctConstants.EVENT_DISCONNECT_DC_RETRYING:
954                log("DataConnectionTracker.handleMessage: EVENT_DISCONNECT_DC_RETRYING msg=" + msg);
955                onDisconnectDcRetrying(msg.arg1, (AsyncResult) msg.obj);
956                break;
957
958            case DctConstants.EVENT_VOICE_CALL_STARTED:
959                onVoiceCallStarted();
960                break;
961
962            case DctConstants.EVENT_VOICE_CALL_ENDED:
963                onVoiceCallEnded();
964                break;
965
966            case DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS: {
967                onCleanUpAllConnections((String) msg.obj);
968                break;
969            }
970            case DctConstants.EVENT_CLEAN_UP_CONNECTION: {
971                boolean tearDown = (msg.arg1 == 0) ? false : true;
972                onCleanUpConnection(tearDown, msg.arg2, (String) msg.obj);
973                break;
974            }
975            case DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE: {
976                boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
977                onSetInternalDataEnabled(enabled);
978                break;
979            }
980            case DctConstants.EVENT_RESET_DONE: {
981                if (DBG) log("EVENT_RESET_DONE");
982                onResetDone((AsyncResult) msg.obj);
983                break;
984            }
985            case DctConstants.CMD_SET_USER_DATA_ENABLE: {
986                final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
987                if (DBG) log("CMD_SET_USER_DATA_ENABLE enabled=" + enabled);
988                onSetUserDataEnabled(enabled);
989                break;
990            }
991            case DctConstants.CMD_SET_DEPENDENCY_MET: {
992                boolean met = (msg.arg1 == DctConstants.ENABLED) ? true : false;
993                if (DBG) log("CMD_SET_DEPENDENCY_MET met=" + met);
994                Bundle bundle = msg.getData();
995                if (bundle != null) {
996                    String apnType = (String)bundle.get(DctConstants.APN_TYPE_KEY);
997                    if (apnType != null) {
998                        onSetDependencyMet(apnType, met);
999                    }
1000                }
1001                break;
1002            }
1003            case DctConstants.CMD_SET_POLICY_DATA_ENABLE: {
1004                final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
1005                onSetPolicyDataEnabled(enabled);
1006                break;
1007            }
1008            case DctConstants.CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: {
1009                sEnableFailFastRefCounter += (msg.arg1 == DctConstants.ENABLED) ? 1 : -1;
1010                if (DBG) {
1011                    log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: "
1012                            + " sEnableFailFastRefCounter=" + sEnableFailFastRefCounter);
1013                }
1014                if (sEnableFailFastRefCounter < 0) {
1015                    final String s = "CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: "
1016                            + "sEnableFailFastRefCounter:" + sEnableFailFastRefCounter + " < 0";
1017                    loge(s);
1018                    sEnableFailFastRefCounter = 0;
1019                }
1020                final boolean enabled = sEnableFailFastRefCounter > 0;
1021                if (DBG) {
1022                    log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: enabled=" + enabled
1023                            + " sEnableFailFastRefCounter=" + sEnableFailFastRefCounter);
1024                }
1025                if (mFailFast != enabled) {
1026                    mFailFast = enabled;
1027                    mDataStallDetectionEnabled = !enabled;
1028                    if (mDataStallDetectionEnabled
1029                            && (getOverallState() == DctConstants.State.CONNECTED)
1030                            && (!mInVoiceCall ||
1031                                    mPhone.getServiceStateTracker()
1032                                        .isConcurrentVoiceAndDataAllowed())) {
1033                        if (DBG) log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: start data stall");
1034                        stopDataStallAlarm();
1035                        startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
1036                    } else {
1037                        if (DBG) log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: stop data stall");
1038                        stopDataStallAlarm();
1039                    }
1040                }
1041
1042                break;
1043            }
1044            case DctConstants.CMD_ENABLE_MOBILE_PROVISIONING: {
1045                Bundle bundle = msg.getData();
1046                if (bundle != null) {
1047                    try {
1048                        mProvisioningUrl = (String)bundle.get(DctConstants.PROVISIONING_URL_KEY);
1049                    } catch(ClassCastException e) {
1050                        loge("CMD_ENABLE_MOBILE_PROVISIONING: provisioning url not a string" + e);
1051                        mProvisioningUrl = null;
1052                    }
1053                }
1054                if (TextUtils.isEmpty(mProvisioningUrl)) {
1055                    loge("CMD_ENABLE_MOBILE_PROVISIONING: provisioning url is empty, ignoring");
1056                    mIsProvisioning = false;
1057                    mProvisioningUrl = null;
1058                } else {
1059                    loge("CMD_ENABLE_MOBILE_PROVISIONING: provisioningUrl=" + mProvisioningUrl);
1060                    mIsProvisioning = true;
1061                    startProvisioningApnAlarm();
1062                }
1063                break;
1064            }
1065            case DctConstants.EVENT_PROVISIONING_APN_ALARM: {
1066                if (DBG) log("EVENT_PROVISIONING_APN_ALARM");
1067                ApnContext apnCtx = mApnContexts.get("default");
1068                if (apnCtx.isProvisioningApn() && apnCtx.isConnectedOrConnecting()) {
1069                    if (mProvisioningApnAlarmTag == msg.arg1) {
1070                        if (DBG) log("EVENT_PROVISIONING_APN_ALARM: Disconnecting");
1071                        mIsProvisioning = false;
1072                        mProvisioningUrl = null;
1073                        stopProvisioningApnAlarm();
1074                        sendCleanUpConnection(true, apnCtx);
1075                    } else {
1076                        if (DBG) {
1077                            log("EVENT_PROVISIONING_APN_ALARM: ignore stale tag,"
1078                                    + " mProvisioningApnAlarmTag:" + mProvisioningApnAlarmTag
1079                                    + " != arg1:" + msg.arg1);
1080                        }
1081                    }
1082                } else {
1083                    if (DBG) log("EVENT_PROVISIONING_APN_ALARM: Not connected ignore");
1084                }
1085                break;
1086            }
1087            case DctConstants.CMD_IS_PROVISIONING_APN: {
1088                if (DBG) log("CMD_IS_PROVISIONING_APN");
1089                boolean isProvApn;
1090                try {
1091                    String apnType = null;
1092                    Bundle bundle = msg.getData();
1093                    if (bundle != null) {
1094                        apnType = (String)bundle.get(DctConstants.APN_TYPE_KEY);
1095                    }
1096                    if (TextUtils.isEmpty(apnType)) {
1097                        loge("CMD_IS_PROVISIONING_APN: apnType is empty");
1098                        isProvApn = false;
1099                    } else {
1100                        isProvApn = isProvisioningApn(apnType);
1101                    }
1102                } catch (ClassCastException e) {
1103                    loge("CMD_IS_PROVISIONING_APN: NO provisioning url ignoring");
1104                    isProvApn = false;
1105                }
1106                if (DBG) log("CMD_IS_PROVISIONING_APN: ret=" + isProvApn);
1107                mReplyAc.replyToMessage(msg, DctConstants.CMD_IS_PROVISIONING_APN,
1108                        isProvApn ? DctConstants.ENABLED : DctConstants.DISABLED);
1109                break;
1110            }
1111            case DctConstants.EVENT_ICC_CHANGED: {
1112                onUpdateIcc();
1113                break;
1114            }
1115            case DctConstants.EVENT_RESTART_RADIO: {
1116                restartRadio();
1117                break;
1118            }
1119            case DctConstants.CMD_NET_STAT_POLL: {
1120                if (msg.arg1 == DctConstants.ENABLED) {
1121                    handleStartNetStatPoll((DctConstants.Activity)msg.obj);
1122                } else if (msg.arg1 == DctConstants.DISABLED) {
1123                    handleStopNetStatPoll((DctConstants.Activity)msg.obj);
1124                }
1125                break;
1126            }
1127            default:
1128                Rlog.e("DATA", "Unidentified event msg=" + msg);
1129                break;
1130        }
1131    }
1132
1133    /**
1134     * Report on whether data connectivity is enabled
1135     *
1136     * @return {@code false} if data connectivity has been explicitly disabled,
1137     *         {@code true} otherwise.
1138     */
1139    public boolean getAnyDataEnabled() {
1140        final boolean result;
1141        synchronized (mDataEnabledLock) {
1142            result = (mInternalDataEnabled && mUserDataEnabled && sPolicyDataEnabled
1143                    && (mEnabledCount != 0));
1144        }
1145        if (!result && DBG) log("getAnyDataEnabled " + result);
1146        return result;
1147    }
1148
1149    protected boolean isEmergency() {
1150        final boolean result;
1151        synchronized (mDataEnabledLock) {
1152            result = mPhone.isInEcm() || mPhone.isInEmergencyCall();
1153        }
1154        log("isEmergency: result=" + result);
1155        return result;
1156    }
1157
1158    protected int apnTypeToId(String type) {
1159        if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DEFAULT)) {
1160            return DctConstants.APN_DEFAULT_ID;
1161        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_MMS)) {
1162            return DctConstants.APN_MMS_ID;
1163        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_SUPL)) {
1164            return DctConstants.APN_SUPL_ID;
1165        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DUN)) {
1166            return DctConstants.APN_DUN_ID;
1167        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_HIPRI)) {
1168            return DctConstants.APN_HIPRI_ID;
1169        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_IMS)) {
1170            return DctConstants.APN_IMS_ID;
1171        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_FOTA)) {
1172            return DctConstants.APN_FOTA_ID;
1173        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_CBS)) {
1174            return DctConstants.APN_CBS_ID;
1175        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_IA)) {
1176            return DctConstants.APN_IA_ID;
1177        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_EMERGENCY)) {
1178            return DctConstants.APN_EMERGENCY_ID;
1179        } else {
1180            return DctConstants.APN_INVALID_ID;
1181        }
1182    }
1183
1184    protected String apnIdToType(int id) {
1185        switch (id) {
1186        case DctConstants.APN_DEFAULT_ID:
1187            return PhoneConstants.APN_TYPE_DEFAULT;
1188        case DctConstants.APN_MMS_ID:
1189            return PhoneConstants.APN_TYPE_MMS;
1190        case DctConstants.APN_SUPL_ID:
1191            return PhoneConstants.APN_TYPE_SUPL;
1192        case DctConstants.APN_DUN_ID:
1193            return PhoneConstants.APN_TYPE_DUN;
1194        case DctConstants.APN_HIPRI_ID:
1195            return PhoneConstants.APN_TYPE_HIPRI;
1196        case DctConstants.APN_IMS_ID:
1197            return PhoneConstants.APN_TYPE_IMS;
1198        case DctConstants.APN_FOTA_ID:
1199            return PhoneConstants.APN_TYPE_FOTA;
1200        case DctConstants.APN_CBS_ID:
1201            return PhoneConstants.APN_TYPE_CBS;
1202        case DctConstants.APN_IA_ID:
1203            return PhoneConstants.APN_TYPE_IA;
1204        case DctConstants.APN_EMERGENCY_ID:
1205            return PhoneConstants.APN_TYPE_EMERGENCY;
1206        default:
1207            log("Unknown id (" + id + ") in apnIdToType");
1208            return PhoneConstants.APN_TYPE_DEFAULT;
1209        }
1210    }
1211
1212    public LinkProperties getLinkProperties(String apnType) {
1213        int id = apnTypeToId(apnType);
1214
1215        if (isApnIdEnabled(id)) {
1216            DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0);
1217            return dcac.getLinkPropertiesSync();
1218        } else {
1219            return new LinkProperties();
1220        }
1221    }
1222
1223    public NetworkCapabilities getNetworkCapabilities(String apnType) {
1224        int id = apnTypeToId(apnType);
1225        if (isApnIdEnabled(id)) {
1226            DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0);
1227            return dcac.getNetworkCapabilitiesSync();
1228        } else {
1229            return new NetworkCapabilities();
1230        }
1231    }
1232
1233    // tell all active apns of the current condition
1234    protected void notifyDataConnection(String reason) {
1235        for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) {
1236            if (mDataEnabled[id]) {
1237                mPhone.notifyDataConnection(reason, apnIdToType(id));
1238            }
1239        }
1240        notifyOffApnsOfAvailability(reason);
1241    }
1242
1243    // a new APN has gone active and needs to send events to catch up with the
1244    // current condition
1245    private void notifyApnIdUpToCurrent(String reason, int apnId) {
1246        switch (mState) {
1247            case IDLE:
1248                break;
1249            case RETRYING:
1250            case CONNECTING:
1251            case SCANNING:
1252                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1253                        PhoneConstants.DataState.CONNECTING);
1254                break;
1255            case CONNECTED:
1256            case DISCONNECTING:
1257                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1258                        PhoneConstants.DataState.CONNECTING);
1259                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1260                        PhoneConstants.DataState.CONNECTED);
1261                break;
1262            default:
1263                // Ignore
1264                break;
1265        }
1266    }
1267
1268    // since we normally don't send info to a disconnected APN, we need to do this specially
1269    private void notifyApnIdDisconnected(String reason, int apnId) {
1270        mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1271                PhoneConstants.DataState.DISCONNECTED);
1272    }
1273
1274    // disabled apn's still need avail/unavail notificiations - send them out
1275    protected void notifyOffApnsOfAvailability(String reason) {
1276        if (DBG) log("notifyOffApnsOfAvailability - reason= " + reason);
1277        for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) {
1278            if (!isApnIdEnabled(id)) {
1279                notifyApnIdDisconnected(reason, id);
1280            }
1281        }
1282    }
1283
1284    public boolean isApnTypeEnabled(String apnType) {
1285        if (apnType == null) {
1286            return false;
1287        } else {
1288            return isApnIdEnabled(apnTypeToId(apnType));
1289        }
1290    }
1291
1292    protected synchronized boolean isApnIdEnabled(int id) {
1293        if (id != DctConstants.APN_INVALID_ID) {
1294            return mDataEnabled[id];
1295        }
1296        return false;
1297    }
1298
1299    protected void setEnabled(int id, boolean enable) {
1300        if (DBG) {
1301            log("setEnabled(" + id + ", " + enable + ") with old state = " + mDataEnabled[id]
1302                    + " and enabledCount = " + mEnabledCount);
1303        }
1304        Message msg = obtainMessage(DctConstants.EVENT_ENABLE_NEW_APN);
1305        msg.arg1 = id;
1306        msg.arg2 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
1307        sendMessage(msg);
1308    }
1309
1310    abstract void onEnableApn(int apnId, int enabled);
1311
1312    /**
1313     * Called when we switch APNs.
1314     *
1315     * mRequestedApnType is set prior to call
1316     * To be overridden.
1317     */
1318    protected void onEnableNewApn() {
1319    }
1320
1321    /**
1322     * Called when EVENT_RESET_DONE is received so goto
1323     * IDLE state and send notifications to those interested.
1324     *
1325     * TODO - currently unused.  Needs to be hooked into DataConnection cleanup
1326     * TODO - needs to pass some notion of which connection is reset..
1327     */
1328    protected void onResetDone(AsyncResult ar) {
1329        if (DBG) log("EVENT_RESET_DONE");
1330        String reason = null;
1331        if (ar.userObj instanceof String) {
1332            reason = (String) ar.userObj;
1333        }
1334        gotoIdleAndNotifyDataConnection(reason);
1335    }
1336
1337    /**
1338     * Prevent mobile data connections from being established, or once again
1339     * allow mobile data connections. If the state toggles, then either tear
1340     * down or set up data, as appropriate to match the new state.
1341     *
1342     * @param enable indicates whether to enable ({@code true}) or disable (
1343     *            {@code false}) data
1344     * @return {@code true} if the operation succeeded
1345     */
1346    public boolean setInternalDataEnabled(boolean enable) {
1347        if (DBG)
1348            log("setInternalDataEnabled(" + enable + ")");
1349
1350        Message msg = obtainMessage(DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE);
1351        msg.arg1 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
1352        sendMessage(msg);
1353        return true;
1354    }
1355
1356    protected void onSetInternalDataEnabled(boolean enabled) {
1357        synchronized (mDataEnabledLock) {
1358            mInternalDataEnabled = enabled;
1359            if (enabled) {
1360                log("onSetInternalDataEnabled: changed to enabled, try to setup data call");
1361                onTrySetupData(Phone.REASON_DATA_ENABLED);
1362            } else {
1363                log("onSetInternalDataEnabled: changed to disabled, cleanUpAllConnections");
1364                cleanUpAllConnections(null);
1365            }
1366        }
1367    }
1368
1369    public void cleanUpAllConnections(String cause) {
1370        Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS);
1371        msg.obj = cause;
1372        sendMessage(msg);
1373    }
1374
1375    public abstract boolean isDisconnected();
1376
1377    protected void onSetUserDataEnabled(boolean enabled) {
1378        synchronized (mDataEnabledLock) {
1379            if (mUserDataEnabled != enabled) {
1380                mUserDataEnabled = enabled;
1381
1382                // For single SIM phones, this is a per phone property.
1383                if (TelephonyManager.getDefault().getSimCount() == 1) {
1384                    Settings.Global.putInt(mResolver, Settings.Global.MOBILE_DATA, enabled ? 1 : 0);
1385                } else {
1386                    int phoneSubId = mPhone.getSubId();
1387                    Settings.Global.putInt(mResolver, Settings.Global.MOBILE_DATA + phoneSubId,
1388                            enabled ? 1 : 0);
1389                }
1390                if (getDataOnRoamingEnabled() == false &&
1391                        mPhone.getServiceState().getDataRoaming() == true) {
1392                    if (enabled) {
1393                        notifyOffApnsOfAvailability(Phone.REASON_ROAMING_ON);
1394                    } else {
1395                        notifyOffApnsOfAvailability(Phone.REASON_DATA_DISABLED);
1396                    }
1397                }
1398
1399                if (enabled) {
1400                    onTrySetupData(Phone.REASON_DATA_ENABLED);
1401                } else {
1402                    onCleanUpAllConnections(Phone.REASON_DATA_SPECIFIC_DISABLED);
1403                }
1404            }
1405        }
1406    }
1407
1408    protected void onSetDependencyMet(String apnType, boolean met) {
1409    }
1410
1411    protected void onSetPolicyDataEnabled(boolean enabled) {
1412        synchronized (mDataEnabledLock) {
1413            final boolean prevEnabled = getAnyDataEnabled();
1414            if (sPolicyDataEnabled != enabled) {
1415                sPolicyDataEnabled = enabled;
1416                if (prevEnabled != getAnyDataEnabled()) {
1417                    if (!prevEnabled) {
1418                        onTrySetupData(Phone.REASON_DATA_ENABLED);
1419                    } else {
1420                        onCleanUpAllConnections(Phone.REASON_DATA_SPECIFIC_DISABLED);
1421                    }
1422                }
1423            }
1424        }
1425    }
1426
1427    protected String getReryConfig(boolean forDefault) {
1428        int nt = mPhone.getServiceState().getNetworkType();
1429
1430        if ((nt == TelephonyManager.NETWORK_TYPE_CDMA) ||
1431            (nt == TelephonyManager.NETWORK_TYPE_1xRTT) ||
1432            (nt == TelephonyManager.NETWORK_TYPE_EVDO_0) ||
1433            (nt == TelephonyManager.NETWORK_TYPE_EVDO_A) ||
1434            (nt == TelephonyManager.NETWORK_TYPE_EVDO_B) ||
1435            (nt == TelephonyManager.NETWORK_TYPE_EHRPD)) {
1436            // CDMA variant
1437            return SystemProperties.get("ro.cdma.data_retry_config");
1438        } else {
1439            // Use GSM varient for all others.
1440            if (forDefault) {
1441                return SystemProperties.get("ro.gsm.data_retry_config");
1442            } else {
1443                return SystemProperties.get("ro.gsm.2nd_data_retry_config");
1444            }
1445        }
1446    }
1447
1448    protected void resetPollStats() {
1449        mTxPkts = -1;
1450        mRxPkts = -1;
1451        mNetStatPollPeriod = POLL_NETSTAT_MILLIS;
1452    }
1453
1454    protected abstract DctConstants.State getOverallState();
1455
1456    void startNetStatPoll() {
1457        if (getOverallState() == DctConstants.State.CONNECTED
1458                && mNetStatPollEnabled == false) {
1459            if (DBG) {
1460                log("startNetStatPoll");
1461            }
1462            resetPollStats();
1463            mNetStatPollEnabled = true;
1464            mPollNetStat.run();
1465        }
1466        if (mPhone != null) {
1467            mPhone.notifyDataActivity();
1468        }
1469    }
1470
1471    void stopNetStatPoll() {
1472        mNetStatPollEnabled = false;
1473        removeCallbacks(mPollNetStat);
1474        if (DBG) {
1475            log("stopNetStatPoll");
1476        }
1477
1478        // To sync data activity icon in the case of switching data connection to send MMS.
1479        if (mPhone != null) {
1480            mPhone.notifyDataActivity();
1481        }
1482    }
1483
1484    public void sendStartNetStatPoll(DctConstants.Activity activity) {
1485        Message msg = obtainMessage(DctConstants.CMD_NET_STAT_POLL);
1486        msg.arg1 = DctConstants.ENABLED;
1487        msg.obj = activity;
1488        sendMessage(msg);
1489    }
1490
1491    protected void handleStartNetStatPoll(DctConstants.Activity activity) {
1492        startNetStatPoll();
1493        startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
1494        setActivity(activity);
1495    }
1496
1497    public void sendStopNetStatPoll(DctConstants.Activity activity) {
1498        Message msg = obtainMessage(DctConstants.CMD_NET_STAT_POLL);
1499        msg.arg1 = DctConstants.DISABLED;
1500        msg.obj = activity;
1501        sendMessage(msg);
1502    }
1503
1504    protected void handleStopNetStatPoll(DctConstants.Activity activity) {
1505        stopNetStatPoll();
1506        stopDataStallAlarm();
1507        setActivity(activity);
1508    }
1509
1510    public void updateDataActivity() {
1511        long sent, received;
1512
1513        DctConstants.Activity newActivity;
1514
1515        TxRxSum preTxRxSum = new TxRxSum(mTxPkts, mRxPkts);
1516        TxRxSum curTxRxSum = new TxRxSum();
1517        curTxRxSum.updateTxRxSum();
1518        mTxPkts = curTxRxSum.txPkts;
1519        mRxPkts = curTxRxSum.rxPkts;
1520
1521        if (VDBG) {
1522            log("updateDataActivity: curTxRxSum=" + curTxRxSum + " preTxRxSum=" + preTxRxSum);
1523        }
1524
1525        if (mNetStatPollEnabled && (preTxRxSum.txPkts > 0 || preTxRxSum.rxPkts > 0)) {
1526            sent = mTxPkts - preTxRxSum.txPkts;
1527            received = mRxPkts - preTxRxSum.rxPkts;
1528
1529            if (VDBG)
1530                log("updateDataActivity: sent=" + sent + " received=" + received);
1531            if (sent > 0 && received > 0) {
1532                newActivity = DctConstants.Activity.DATAINANDOUT;
1533            } else if (sent > 0 && received == 0) {
1534                newActivity = DctConstants.Activity.DATAOUT;
1535            } else if (sent == 0 && received > 0) {
1536                newActivity = DctConstants.Activity.DATAIN;
1537            } else {
1538                newActivity = (mActivity == DctConstants.Activity.DORMANT) ?
1539                        mActivity : DctConstants.Activity.NONE;
1540            }
1541
1542            if (mActivity != newActivity && mIsScreenOn) {
1543                if (VDBG)
1544                    log("updateDataActivity: newActivity=" + newActivity);
1545                mActivity = newActivity;
1546                mPhone.notifyDataActivity();
1547            }
1548        }
1549    }
1550
1551    // Recovery action taken in case of data stall
1552    protected static class RecoveryAction {
1553        public static final int GET_DATA_CALL_LIST      = 0;
1554        public static final int CLEANUP                 = 1;
1555        public static final int REREGISTER              = 2;
1556        public static final int RADIO_RESTART           = 3;
1557        public static final int RADIO_RESTART_WITH_PROP = 4;
1558
1559        private static boolean isAggressiveRecovery(int value) {
1560            return ((value == RecoveryAction.CLEANUP) ||
1561                    (value == RecoveryAction.REREGISTER) ||
1562                    (value == RecoveryAction.RADIO_RESTART) ||
1563                    (value == RecoveryAction.RADIO_RESTART_WITH_PROP));
1564        }
1565    }
1566
1567    public int getRecoveryAction() {
1568        int action = Settings.System.getInt(mResolver,
1569                "radio.data.stall.recovery.action", RecoveryAction.GET_DATA_CALL_LIST);
1570        if (VDBG_STALL) log("getRecoveryAction: " + action);
1571        return action;
1572    }
1573    public void putRecoveryAction(int action) {
1574        Settings.System.putInt(mResolver, "radio.data.stall.recovery.action", action);
1575        if (VDBG_STALL) log("putRecoveryAction: " + action);
1576    }
1577
1578    protected boolean isConnected() {
1579        return false;
1580    }
1581
1582    protected void doRecovery() {
1583        if (getOverallState() == DctConstants.State.CONNECTED) {
1584            // Go through a series of recovery steps, each action transitions to the next action
1585            int recoveryAction = getRecoveryAction();
1586            switch (recoveryAction) {
1587            case RecoveryAction.GET_DATA_CALL_LIST:
1588                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_GET_DATA_CALL_LIST,
1589                        mSentSinceLastRecv);
1590                if (DBG) log("doRecovery() get data call list");
1591                mPhone.mCi.getDataCallList(obtainMessage(DctConstants.EVENT_DATA_STATE_CHANGED));
1592                putRecoveryAction(RecoveryAction.CLEANUP);
1593                break;
1594            case RecoveryAction.CLEANUP:
1595                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_CLEANUP, mSentSinceLastRecv);
1596                if (DBG) log("doRecovery() cleanup all connections");
1597                cleanUpAllConnections(Phone.REASON_PDP_RESET);
1598                putRecoveryAction(RecoveryAction.REREGISTER);
1599                break;
1600            case RecoveryAction.REREGISTER:
1601                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_REREGISTER,
1602                        mSentSinceLastRecv);
1603                if (DBG) log("doRecovery() re-register");
1604                mPhone.getServiceStateTracker().reRegisterNetwork(null);
1605                putRecoveryAction(RecoveryAction.RADIO_RESTART);
1606                break;
1607            case RecoveryAction.RADIO_RESTART:
1608                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART,
1609                        mSentSinceLastRecv);
1610                if (DBG) log("restarting radio");
1611                putRecoveryAction(RecoveryAction.RADIO_RESTART_WITH_PROP);
1612                restartRadio();
1613                break;
1614            case RecoveryAction.RADIO_RESTART_WITH_PROP:
1615                // This is in case radio restart has not recovered the data.
1616                // It will set an additional "gsm.radioreset" property to tell
1617                // RIL or system to take further action.
1618                // The implementation of hard reset recovery action is up to OEM product.
1619                // Once RADIO_RESET property is consumed, it is expected to set back
1620                // to false by RIL.
1621                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART_WITH_PROP, -1);
1622                if (DBG) log("restarting radio with gsm.radioreset to true");
1623                SystemProperties.set(RADIO_RESET_PROPERTY, "true");
1624                // give 1 sec so property change can be notified.
1625                try {
1626                    Thread.sleep(1000);
1627                } catch (InterruptedException e) {}
1628                restartRadio();
1629                putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1630                break;
1631            default:
1632                throw new RuntimeException("doRecovery: Invalid recoveryAction=" +
1633                    recoveryAction);
1634            }
1635            mSentSinceLastRecv = 0;
1636        }
1637    }
1638
1639    private void updateDataStallInfo() {
1640        long sent, received;
1641
1642        TxRxSum preTxRxSum = new TxRxSum(mDataStallTxRxSum);
1643        mDataStallTxRxSum.updateTxRxSum();
1644
1645        if (VDBG_STALL) {
1646            log("updateDataStallInfo: mDataStallTxRxSum=" + mDataStallTxRxSum +
1647                    " preTxRxSum=" + preTxRxSum);
1648        }
1649
1650        sent = mDataStallTxRxSum.txPkts - preTxRxSum.txPkts;
1651        received = mDataStallTxRxSum.rxPkts - preTxRxSum.rxPkts;
1652
1653        if (RADIO_TESTS) {
1654            if (SystemProperties.getBoolean("radio.test.data.stall", false)) {
1655                log("updateDataStallInfo: radio.test.data.stall true received = 0;");
1656                received = 0;
1657            }
1658        }
1659        if ( sent > 0 && received > 0 ) {
1660            if (VDBG_STALL) log("updateDataStallInfo: IN/OUT");
1661            mSentSinceLastRecv = 0;
1662            putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1663        } else if (sent > 0 && received == 0) {
1664            if (mPhone.getState() == PhoneConstants.State.IDLE) {
1665                mSentSinceLastRecv += sent;
1666            } else {
1667                mSentSinceLastRecv = 0;
1668            }
1669            if (DBG) {
1670                log("updateDataStallInfo: OUT sent=" + sent +
1671                        " mSentSinceLastRecv=" + mSentSinceLastRecv);
1672            }
1673        } else if (sent == 0 && received > 0) {
1674            if (VDBG_STALL) log("updateDataStallInfo: IN");
1675            mSentSinceLastRecv = 0;
1676            putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1677        } else {
1678            if (VDBG_STALL) log("updateDataStallInfo: NONE");
1679        }
1680    }
1681
1682    protected void onDataStallAlarm(int tag) {
1683        if (mDataStallAlarmTag != tag) {
1684            if (DBG) {
1685                log("onDataStallAlarm: ignore, tag=" + tag + " expecting " + mDataStallAlarmTag);
1686            }
1687            return;
1688        }
1689        updateDataStallInfo();
1690
1691        int hangWatchdogTrigger = Settings.Global.getInt(mResolver,
1692                Settings.Global.PDP_WATCHDOG_TRIGGER_PACKET_COUNT,
1693                NUMBER_SENT_PACKETS_OF_HANG);
1694
1695        boolean suspectedStall = DATA_STALL_NOT_SUSPECTED;
1696        if (mSentSinceLastRecv >= hangWatchdogTrigger) {
1697            if (DBG) {
1698                log("onDataStallAlarm: tag=" + tag + " do recovery action=" + getRecoveryAction());
1699            }
1700            suspectedStall = DATA_STALL_SUSPECTED;
1701            sendMessage(obtainMessage(DctConstants.EVENT_DO_RECOVERY));
1702        } else {
1703            if (VDBG_STALL) {
1704                log("onDataStallAlarm: tag=" + tag + " Sent " + String.valueOf(mSentSinceLastRecv) +
1705                    " pkts since last received, < watchdogTrigger=" + hangWatchdogTrigger);
1706            }
1707        }
1708        startDataStallAlarm(suspectedStall);
1709    }
1710
1711    protected void startDataStallAlarm(boolean suspectedStall) {
1712        int nextAction = getRecoveryAction();
1713        int delayInMs;
1714
1715        if (mDataStallDetectionEnabled && getOverallState() == DctConstants.State.CONNECTED) {
1716            // If screen is on or data stall is currently suspected, set the alarm
1717            // with an aggresive timeout.
1718            if (mIsScreenOn || suspectedStall || RecoveryAction.isAggressiveRecovery(nextAction)) {
1719                delayInMs = Settings.Global.getInt(mResolver,
1720                        Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS,
1721                        DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS_DEFAULT);
1722            } else {
1723                delayInMs = Settings.Global.getInt(mResolver,
1724                        Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS,
1725                        DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS_DEFAULT);
1726            }
1727
1728            mDataStallAlarmTag += 1;
1729            if (VDBG_STALL) {
1730                log("startDataStallAlarm: tag=" + mDataStallAlarmTag +
1731                        " delay=" + (delayInMs / 1000) + "s");
1732            }
1733            Intent intent = new Intent(INTENT_DATA_STALL_ALARM);
1734            intent.putExtra(DATA_STALL_ALARM_TAG_EXTRA, mDataStallAlarmTag);
1735            mDataStallAlarmIntent = PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
1736                    PendingIntent.FLAG_UPDATE_CURRENT);
1737            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1738                    SystemClock.elapsedRealtime() + delayInMs, mDataStallAlarmIntent);
1739        } else {
1740            if (VDBG_STALL) {
1741                log("startDataStallAlarm: NOT started, no connection tag=" + mDataStallAlarmTag);
1742            }
1743        }
1744    }
1745
1746    protected void stopDataStallAlarm() {
1747        if (VDBG_STALL) {
1748            log("stopDataStallAlarm: current tag=" + mDataStallAlarmTag +
1749                    " mDataStallAlarmIntent=" + mDataStallAlarmIntent);
1750        }
1751        mDataStallAlarmTag += 1;
1752        if (mDataStallAlarmIntent != null) {
1753            mAlarmManager.cancel(mDataStallAlarmIntent);
1754            mDataStallAlarmIntent = null;
1755        }
1756    }
1757
1758    protected void restartDataStallAlarm() {
1759        if (isConnected() == false) return;
1760        // To be called on screen status change.
1761        // Do not cancel the alarm if it is set with aggressive timeout.
1762        int nextAction = getRecoveryAction();
1763
1764        if (RecoveryAction.isAggressiveRecovery(nextAction)) {
1765            if (DBG) log("restartDataStallAlarm: action is pending. not resetting the alarm.");
1766            return;
1767        }
1768        if (VDBG_STALL) log("restartDataStallAlarm: stop then start.");
1769        stopDataStallAlarm();
1770        startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
1771    }
1772
1773    protected void setInitialAttachApn() {
1774        ApnSetting iaApnSetting = null;
1775        ApnSetting defaultApnSetting = null;
1776        ApnSetting firstApnSetting = null;
1777
1778        log("setInitialApn: E mPreferredApn=" + mPreferredApn);
1779
1780        if (mAllApnSettings != null && !mAllApnSettings.isEmpty()) {
1781            firstApnSetting = mAllApnSettings.get(0);
1782            log("setInitialApn: firstApnSetting=" + firstApnSetting);
1783
1784            // Search for Initial APN setting and the first apn that can handle default
1785            for (ApnSetting apn : mAllApnSettings) {
1786                // Can't use apn.canHandleType(), as that returns true for APNs that have no type.
1787                if (ArrayUtils.contains(apn.types, PhoneConstants.APN_TYPE_IA) &&
1788                        apn.carrierEnabled) {
1789                    // The Initial Attach APN is highest priority so use it if there is one
1790                    log("setInitialApn: iaApnSetting=" + apn);
1791                    iaApnSetting = apn;
1792                    break;
1793                } else if ((defaultApnSetting == null)
1794                        && (apn.canHandleType(PhoneConstants.APN_TYPE_DEFAULT))) {
1795                    // Use the first default apn if no better choice
1796                    log("setInitialApn: defaultApnSetting=" + apn);
1797                    defaultApnSetting = apn;
1798                }
1799            }
1800        }
1801
1802        // The priority of apn candidates from highest to lowest is:
1803        //   1) APN_TYPE_IA (Inital Attach)
1804        //   2) mPreferredApn, i.e. the current preferred apn
1805        //   3) The first apn that than handle APN_TYPE_DEFAULT
1806        //   4) The first APN we can find.
1807
1808        ApnSetting initialAttachApnSetting = null;
1809        if (iaApnSetting != null) {
1810            if (DBG) log("setInitialAttachApn: using iaApnSetting");
1811            initialAttachApnSetting = iaApnSetting;
1812        } else if (mPreferredApn != null) {
1813            if (DBG) log("setInitialAttachApn: using mPreferredApn");
1814            initialAttachApnSetting = mPreferredApn;
1815        } else if (defaultApnSetting != null) {
1816            if (DBG) log("setInitialAttachApn: using defaultApnSetting");
1817            initialAttachApnSetting = defaultApnSetting;
1818        } else if (firstApnSetting != null) {
1819            if (DBG) log("setInitialAttachApn: using firstApnSetting");
1820            initialAttachApnSetting = firstApnSetting;
1821        }
1822
1823        if (initialAttachApnSetting == null) {
1824            if (DBG) log("setInitialAttachApn: X There in no available apn");
1825        } else {
1826            if (DBG) log("setInitialAttachApn: X selected Apn=" + initialAttachApnSetting);
1827
1828            mPhone.mCi.setInitialAttachApn(initialAttachApnSetting.apn,
1829                    initialAttachApnSetting.protocol, initialAttachApnSetting.authType,
1830                    initialAttachApnSetting.user, initialAttachApnSetting.password, null);
1831        }
1832    }
1833
1834    protected void setDataProfilesAsNeeded() {
1835        if (DBG) log("setDataProfilesAsNeeded");
1836        if (mAllApnSettings != null && !mAllApnSettings.isEmpty()) {
1837            ArrayList<DataProfile> dps = new ArrayList<DataProfile>();
1838            for (ApnSetting apn : mAllApnSettings) {
1839                if (apn.modemCognitive) {
1840                    DataProfile dp = new DataProfile(apn,
1841                            mPhone.getServiceState().getDataRoaming());
1842                    boolean isDup = false;
1843                    for(DataProfile dpIn : dps) {
1844                        if (dp.equals(dpIn)) {
1845                            isDup = true;
1846                            break;
1847                        }
1848                    }
1849                    if (!isDup) {
1850                        dps.add(dp);
1851                    }
1852                }
1853            }
1854            if(dps.size() > 0) {
1855                mPhone.mCi.setDataProfile(dps.toArray(new DataProfile[0]), null);
1856            }
1857        }
1858    }
1859
1860    protected void onActionIntentProvisioningApnAlarm(Intent intent) {
1861        if (DBG) log("onActionIntentProvisioningApnAlarm: action=" + intent.getAction());
1862        Message msg = obtainMessage(DctConstants.EVENT_PROVISIONING_APN_ALARM,
1863                intent.getAction());
1864        msg.arg1 = intent.getIntExtra(PROVISIONING_APN_ALARM_TAG_EXTRA, 0);
1865        sendMessage(msg);
1866    }
1867
1868    protected void startProvisioningApnAlarm() {
1869        int delayInMs = Settings.Global.getInt(mResolver,
1870                                Settings.Global.PROVISIONING_APN_ALARM_DELAY_IN_MS,
1871                                PROVISIONING_APN_ALARM_DELAY_IN_MS_DEFAULT);
1872        if (Build.IS_DEBUGGABLE) {
1873            // Allow debug code to use a system property to provide another value
1874            String delayInMsStrg = Integer.toString(delayInMs);
1875            delayInMsStrg = System.getProperty(DEBUG_PROV_APN_ALARM, delayInMsStrg);
1876            try {
1877                delayInMs = Integer.parseInt(delayInMsStrg);
1878            } catch (NumberFormatException e) {
1879                loge("startProvisioningApnAlarm: e=" + e);
1880            }
1881        }
1882        mProvisioningApnAlarmTag += 1;
1883        if (DBG) {
1884            log("startProvisioningApnAlarm: tag=" + mProvisioningApnAlarmTag +
1885                    " delay=" + (delayInMs / 1000) + "s");
1886        }
1887        Intent intent = new Intent(INTENT_PROVISIONING_APN_ALARM);
1888        intent.putExtra(PROVISIONING_APN_ALARM_TAG_EXTRA, mProvisioningApnAlarmTag);
1889        mProvisioningApnAlarmIntent = PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
1890                PendingIntent.FLAG_UPDATE_CURRENT);
1891        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1892                SystemClock.elapsedRealtime() + delayInMs, mProvisioningApnAlarmIntent);
1893    }
1894
1895    protected void stopProvisioningApnAlarm() {
1896        if (DBG) {
1897            log("stopProvisioningApnAlarm: current tag=" + mProvisioningApnAlarmTag +
1898                    " mProvsioningApnAlarmIntent=" + mProvisioningApnAlarmIntent);
1899        }
1900        mProvisioningApnAlarmTag += 1;
1901        if (mProvisioningApnAlarmIntent != null) {
1902            mAlarmManager.cancel(mProvisioningApnAlarmIntent);
1903            mProvisioningApnAlarmIntent = null;
1904        }
1905    }
1906
1907    void sendCleanUpConnection(boolean tearDown, ApnContext apnContext) {
1908        if (DBG)log("sendCleanUpConnection: tearDown=" + tearDown + " apnContext=" + apnContext);
1909        Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_CONNECTION);
1910        msg.arg1 = tearDown ? 1 : 0;
1911        msg.arg2 = 0;
1912        msg.obj = apnContext;
1913        sendMessage(msg);
1914    }
1915
1916    void sendRestartRadio() {
1917        if (DBG)log("sendRestartRadio:");
1918        Message msg = obtainMessage(DctConstants.EVENT_RESTART_RADIO);
1919        sendMessage(msg);
1920    }
1921
1922    public boolean getAutoAttachOnCreation() {
1923        return mAutoAttachOnCreation.get();
1924    }
1925
1926    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1927        pw.println("DcTrackerBase:");
1928        pw.println(" RADIO_TESTS=" + RADIO_TESTS);
1929        pw.println(" mInternalDataEnabled=" + mInternalDataEnabled);
1930        pw.println(" mUserDataEnabled=" + mUserDataEnabled);
1931        pw.println(" sPolicyDataEnabed=" + sPolicyDataEnabled);
1932        pw.println(" mDataEnabled:");
1933        for(int i=0; i < mDataEnabled.length; i++) {
1934            pw.printf("  mDataEnabled[%d]=%b\n", i, mDataEnabled[i]);
1935        }
1936        pw.flush();
1937        pw.println(" mEnabledCount=" + mEnabledCount);
1938        pw.println(" mRequestedApnType=" + mRequestedApnType);
1939        pw.println(" mPhone=" + mPhone.getPhoneName());
1940        pw.println(" mActivity=" + mActivity);
1941        pw.println(" mState=" + mState);
1942        pw.println(" mTxPkts=" + mTxPkts);
1943        pw.println(" mRxPkts=" + mRxPkts);
1944        pw.println(" mNetStatPollPeriod=" + mNetStatPollPeriod);
1945        pw.println(" mNetStatPollEnabled=" + mNetStatPollEnabled);
1946        pw.println(" mDataStallTxRxSum=" + mDataStallTxRxSum);
1947        pw.println(" mDataStallAlarmTag=" + mDataStallAlarmTag);
1948        pw.println(" mDataStallDetectionEanbled=" + mDataStallDetectionEnabled);
1949        pw.println(" mSentSinceLastRecv=" + mSentSinceLastRecv);
1950        pw.println(" mNoRecvPollCount=" + mNoRecvPollCount);
1951        pw.println(" mResolver=" + mResolver);
1952        pw.println(" mIsWifiConnected=" + mIsWifiConnected);
1953        pw.println(" mReconnectIntent=" + mReconnectIntent);
1954        pw.println(" mCidActive=" + mCidActive);
1955        pw.println(" mAutoAttachOnCreation=" + mAutoAttachOnCreation.get());
1956        pw.println(" mIsScreenOn=" + mIsScreenOn);
1957        pw.println(" mUniqueIdGenerator=" + mUniqueIdGenerator);
1958        pw.flush();
1959        pw.println(" ***************************************");
1960        DcController dcc = mDcc;
1961        if (dcc != null) {
1962            dcc.dump(fd, pw, args);
1963        } else {
1964            pw.println(" mDcc=null");
1965        }
1966        pw.println(" ***************************************");
1967        HashMap<Integer, DataConnection> dcs = mDataConnections;
1968        if (dcs != null) {
1969            Set<Entry<Integer, DataConnection> > mDcSet = mDataConnections.entrySet();
1970            pw.println(" mDataConnections: count=" + mDcSet.size());
1971            for (Entry<Integer, DataConnection> entry : mDcSet) {
1972                pw.printf(" *** mDataConnection[%d] \n", entry.getKey());
1973                entry.getValue().dump(fd, pw, args);
1974            }
1975        } else {
1976            pw.println("mDataConnections=null");
1977        }
1978        pw.println(" ***************************************");
1979        pw.flush();
1980        HashMap<String, Integer> apnToDcId = mApnToDataConnectionId;
1981        if (apnToDcId != null) {
1982            Set<Entry<String, Integer>> apnToDcIdSet = apnToDcId.entrySet();
1983            pw.println(" mApnToDataConnectonId size=" + apnToDcIdSet.size());
1984            for (Entry<String, Integer> entry : apnToDcIdSet) {
1985                pw.printf(" mApnToDataConnectonId[%s]=%d\n", entry.getKey(), entry.getValue());
1986            }
1987        } else {
1988            pw.println("mApnToDataConnectionId=null");
1989        }
1990        pw.println(" ***************************************");
1991        pw.flush();
1992        ConcurrentHashMap<String, ApnContext> apnCtxs = mApnContexts;
1993        if (apnCtxs != null) {
1994            Set<Entry<String, ApnContext>> apnCtxsSet = apnCtxs.entrySet();
1995            pw.println(" mApnContexts size=" + apnCtxsSet.size());
1996            for (Entry<String, ApnContext> entry : apnCtxsSet) {
1997                entry.getValue().dump(fd, pw, args);
1998            }
1999            pw.println(" ***************************************");
2000        } else {
2001            pw.println(" mApnContexts=null");
2002        }
2003        pw.flush();
2004        pw.println(" mActiveApn=" + mActiveApn);
2005        ArrayList<ApnSetting> apnSettings = mAllApnSettings;
2006        if (apnSettings != null) {
2007            pw.println(" mAllApnSettings size=" + apnSettings.size());
2008            for (int i=0; i < apnSettings.size(); i++) {
2009                pw.printf(" mAllApnSettings[%d]: %s\n", i, apnSettings.get(i));
2010            }
2011            pw.flush();
2012        } else {
2013            pw.println(" mAllApnSettings=null");
2014        }
2015        pw.println(" mPreferredApn=" + mPreferredApn);
2016        pw.println(" mIsPsRestricted=" + mIsPsRestricted);
2017        pw.println(" mIsDisposed=" + mIsDisposed);
2018        pw.println(" mIntentReceiver=" + mIntentReceiver);
2019        pw.println(" mDataRoamingSettingObserver=" + mDataRoamingSettingObserver);
2020        pw.flush();
2021    }
2022}
2023