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