DcTrackerBase.java revision f1d59f07cc3375134b448e849d33507af0662a1b
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), false, this);
402        }
403
404        public void unregister() {
405            mResolver.unregisterContentObserver(this);
406        }
407
408        @Override
409        public void onChange(boolean selfChange) {
410            // already running on mPhone handler thread
411            if (mPhone.getServiceState().getRoaming()) {
412                sendMessage(obtainMessage(DctConstants.EVENT_ROAMING_ON));
413            }
414        }
415    }
416    private final DataRoamingSettingObserver mDataRoamingSettingObserver;
417
418    /**
419     * The Initial MaxRetry sent to a DataConnection as a parameter
420     * to DataConnectionAc.bringUp. This value can be defined at compile
421     * time using the SystemProperty Settings.Global.DCT_INITIAL_MAX_RETRY
422     * and at runtime using gservices to change Settings.Global.DCT_INITIAL_MAX_RETRY.
423     */
424    private static final int DEFAULT_MDC_INITIAL_RETRY = 1;
425    protected int getInitialMaxRetry() {
426        if (mFailFast) {
427            return 0;
428        }
429        // Get default value from system property or use DEFAULT_MDC_INITIAL_RETRY
430        int value = SystemProperties.getInt(
431                Settings.Global.MDC_INITIAL_MAX_RETRY, DEFAULT_MDC_INITIAL_RETRY);
432
433        // Check if its been overridden
434        return Settings.Global.getInt(mResolver,
435                Settings.Global.MDC_INITIAL_MAX_RETRY, value);
436    }
437
438    /**
439     * Maintain the sum of transmit and receive packets.
440     *
441     * The packet counts are initialized and reset to -1 and
442     * remain -1 until they can be updated.
443     */
444    public class TxRxSum {
445        public long txPkts;
446        public long rxPkts;
447
448        public TxRxSum() {
449            reset();
450        }
451
452        public TxRxSum(long txPkts, long rxPkts) {
453            this.txPkts = txPkts;
454            this.rxPkts = rxPkts;
455        }
456
457        public TxRxSum(TxRxSum sum) {
458            txPkts = sum.txPkts;
459            rxPkts = sum.rxPkts;
460        }
461
462        public void reset() {
463            txPkts = -1;
464            rxPkts = -1;
465        }
466
467        @Override
468        public String toString() {
469            return "{txSum=" + txPkts + " rxSum=" + rxPkts + "}";
470        }
471
472        public void updateTxRxSum() {
473            this.txPkts = TrafficStats.getMobileTcpTxPackets();
474            this.rxPkts = TrafficStats.getMobileTcpRxPackets();
475        }
476    }
477
478    protected void onActionIntentReconnectAlarm(Intent intent) {
479        String reason = intent.getStringExtra(INTENT_RECONNECT_ALARM_EXTRA_REASON);
480        String apnType = intent.getStringExtra(INTENT_RECONNECT_ALARM_EXTRA_TYPE);
481
482        int phoneSubId = mPhone.getSubId();
483        int currSubId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY,
484                SubscriptionManager.INVALID_SUB_ID);
485        log("onActionIntentReconnectAlarm: currSubId = " + currSubId + " phoneSubId=" + phoneSubId);
486
487        // Stop reconnect if not current subId is not correct.
488        // FIXME STOPSHIP - phoneSubId is coming up as -1 way after boot and failing this?
489        if (!SubscriptionManager.isValidSubId(currSubId) || (currSubId != phoneSubId)) {
490            log("receive ReconnectAlarm but subId incorrect, ignore");
491            return;
492        }
493
494        ApnContext apnContext = mApnContexts.get(apnType);
495
496        if (DBG) {
497            log("onActionIntentReconnectAlarm: mState=" + mState + " reason=" + reason +
498                    " apnType=" + apnType + " apnContext=" + apnContext +
499                    " mDataConnectionAsyncChannels=" + mDataConnectionAcHashMap);
500        }
501
502        if ((apnContext != null) && (apnContext.isEnabled())) {
503            apnContext.setReason(reason);
504            DctConstants.State apnContextState = apnContext.getState();
505            if (DBG) {
506                log("onActionIntentReconnectAlarm: apnContext state=" + apnContextState);
507            }
508            if ((apnContextState == DctConstants.State.FAILED)
509                    || (apnContextState == DctConstants.State.IDLE)) {
510                if (DBG) {
511                    log("onActionIntentReconnectAlarm: state is FAILED|IDLE, disassociate");
512                }
513                DcAsyncChannel dcac = apnContext.getDcAc();
514                if (dcac != null) {
515                    dcac.tearDown(apnContext, "", null);
516                }
517                apnContext.setDataConnectionAc(null);
518                apnContext.setState(DctConstants.State.IDLE);
519            } else {
520                if (DBG) log("onActionIntentReconnectAlarm: keep associated");
521            }
522            // TODO: IF already associated should we send the EVENT_TRY_SETUP_DATA???
523            sendMessage(obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, apnContext));
524
525            apnContext.setReconnectIntent(null);
526        }
527    }
528
529    protected void onActionIntentRestartTrySetupAlarm(Intent intent) {
530        String apnType = intent.getStringExtra(INTENT_RESTART_TRYSETUP_ALARM_EXTRA_TYPE);
531        ApnContext apnContext = mApnContexts.get(apnType);
532        if (DBG) {
533            log("onActionIntentRestartTrySetupAlarm: mState=" + mState +
534                    " apnType=" + apnType + " apnContext=" + apnContext +
535                    " mDataConnectionAsyncChannels=" + mDataConnectionAcHashMap);
536        }
537        sendMessage(obtainMessage(DctConstants.EVENT_TRY_SETUP_DATA, apnContext));
538    }
539
540    protected void onActionIntentDataStallAlarm(Intent intent) {
541        if (VDBG_STALL) log("onActionIntentDataStallAlarm: action=" + intent.getAction());
542        Message msg = obtainMessage(DctConstants.EVENT_DATA_STALL_ALARM,
543                intent.getAction());
544        msg.arg1 = intent.getIntExtra(DATA_STALL_ALARM_TAG_EXTRA, 0);
545        sendMessage(msg);
546    }
547
548    ConnectivityManager mCm;
549
550    /**
551     * Default constructor
552     */
553    protected DcTrackerBase(PhoneBase phone) {
554        super();
555        mPhone = phone;
556        if (DBG) log("DCT.constructor");
557        mResolver = mPhone.getContext().getContentResolver();
558        mUiccController = UiccController.getInstance();
559        mUiccController.registerForIccChanged(this, DctConstants.EVENT_ICC_CHANGED, null);
560        mAlarmManager =
561                (AlarmManager) mPhone.getContext().getSystemService(Context.ALARM_SERVICE);
562        mCm = (ConnectivityManager) mPhone.getContext().getSystemService(
563                Context.CONNECTIVITY_SERVICE);
564
565
566        IntentFilter filter = new IntentFilter();
567        filter.addAction(Intent.ACTION_SCREEN_ON);
568        filter.addAction(Intent.ACTION_SCREEN_OFF);
569        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
570        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
571        filter.addAction(INTENT_DATA_STALL_ALARM);
572        filter.addAction(INTENT_PROVISIONING_APN_ALARM);
573
574        mUserDataEnabled = Settings.Global.getInt(
575                mPhone.getContext().getContentResolver(), Settings.Global.MOBILE_DATA, 1) == 1;
576
577        mPhone.getContext().registerReceiver(mIntentReceiver, filter, null, mPhone);
578
579        // This preference tells us 1) initial condition for "dataEnabled",
580        // and 2) whether the RIL will setup the baseband to auto-PS attach.
581
582        mDataEnabled[DctConstants.APN_DEFAULT_ID] =
583                SystemProperties.getBoolean(DEFALUT_DATA_ON_BOOT_PROP,true);
584        if (mDataEnabled[DctConstants.APN_DEFAULT_ID]) {
585            mEnabledCount++;
586        }
587
588        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mPhone.getContext());
589        mAutoAttachOnCreation = sp.getBoolean(PhoneBase.DATA_DISABLED_ON_BOOT_KEY, false);
590
591        // Watch for changes to Settings.Global.DATA_ROAMING
592        mDataRoamingSettingObserver = new DataRoamingSettingObserver(mPhone, mPhone.getContext());
593        mDataRoamingSettingObserver.register();
594
595        HandlerThread dcHandlerThread = new HandlerThread("DcHandlerThread");
596        dcHandlerThread.start();
597        Handler dcHandler = new Handler(dcHandlerThread.getLooper());
598        mDcc = DcController.makeDcc(mPhone, this, dcHandler);
599        mDcTesterFailBringUpAll = new DcTesterFailBringUpAll(mPhone, dcHandler);
600    }
601
602    public void dispose() {
603        if (DBG) log("DCT.dispose");
604        for (DcAsyncChannel dcac : mDataConnectionAcHashMap.values()) {
605            dcac.disconnect();
606        }
607        mDataConnectionAcHashMap.clear();
608        mIsDisposed = true;
609        mPhone.getContext().unregisterReceiver(mIntentReceiver);
610        mUiccController.unregisterForIccChanged(this);
611        mDataRoamingSettingObserver.unregister();
612        mDcc.dispose();
613        mDcTesterFailBringUpAll.dispose();
614    }
615
616    public long getSubId() {
617        return mPhone.getSubId();
618    }
619
620    public DctConstants.Activity getActivity() {
621        return mActivity;
622    }
623
624    void setActivity(DctConstants.Activity activity) {
625        log("setActivity = " + activity);
626        mActivity = activity;
627        mPhone.notifyDataActivity();
628    }
629
630    public void incApnRefCount(String name) {
631
632    }
633
634    public void decApnRefCount(String name) {
635
636    }
637
638    public boolean isApnSupported(String name) {
639        return false;
640    }
641
642    public int getApnPriority(String name) {
643        return -1;
644    }
645
646
647    public boolean isApnTypeActive(String type) {
648        // TODO: support simultaneous with List instead
649        if (PhoneConstants.APN_TYPE_DUN.equals(type)) {
650            ApnSetting dunApn = fetchDunApn();
651            if (dunApn != null) {
652                return ((mActiveApn != null) && (dunApn.toString().equals(mActiveApn.toString())));
653            }
654        }
655        return mActiveApn != null && mActiveApn.canHandleType(type);
656    }
657
658    protected ApnSetting fetchDunApn() {
659        if (SystemProperties.getBoolean("net.tethering.noprovisioning", false)) {
660            log("fetchDunApn: net.tethering.noprovisioning=true ret: null");
661            return null;
662        }
663        int bearer = -1;
664        ApnSetting retDunSetting = null;
665        Context c = mPhone.getContext();
666        String apnData = Settings.Global.getString(c.getContentResolver(),
667                Settings.Global.TETHER_DUN_APN);
668        List<ApnSetting> dunSettings = ApnSetting.arrayFromString(apnData);
669        IccRecords r = mIccRecords.get();
670        for (ApnSetting dunSetting : dunSettings) {
671            String operator = (r != null) ? r.getOperatorNumeric() : "";
672            if (dunSetting.bearer != 0) {
673                if (bearer == -1) bearer = mPhone.getServiceState().getRilDataRadioTechnology();
674                if (dunSetting.bearer != bearer) continue;
675            }
676            if (dunSetting.numeric.equals(operator)) {
677                if (dunSetting.hasMvnoParams()) {
678                    if (r != null &&
679                            mvnoMatches(r, dunSetting.mvnoType, dunSetting.mvnoMatchData)) {
680                        if (VDBG) {
681                            log("fetchDunApn: global TETHER_DUN_APN dunSetting=" + dunSetting);
682                        }
683                        return dunSetting;
684                    }
685                } else {
686                    if (VDBG) log("fetchDunApn: global TETHER_DUN_APN dunSetting=" + dunSetting);
687                    return dunSetting;
688                }
689            }
690        }
691
692        String[] apnArrayData = c.getResources().getStringArray(R.array.config_tether_apndata);
693        for (String apn : apnArrayData) {
694            ApnSetting dunSetting = ApnSetting.fromString(apn);
695            if (dunSetting != null) {
696                if (dunSetting.bearer != 0) {
697                    if (bearer == -1) bearer = mPhone.getServiceState().getRilDataRadioTechnology();
698                    if (dunSetting.bearer != bearer) continue;
699                }
700                if (dunSetting.hasMvnoParams()) {
701                    if (r != null &&
702                            mvnoMatches(r, dunSetting.mvnoType, dunSetting.mvnoMatchData)) {
703                        if (VDBG) log("fetchDunApn: config_tether_apndata mvno dunSetting="
704                                + dunSetting);
705                        return dunSetting;
706                    }
707                } else {
708                    retDunSetting = dunSetting;
709                }
710            }
711        }
712
713        if (VDBG) log("fetchDunApn: config_tether_apndata dunSetting=" + retDunSetting);
714        return retDunSetting;
715    }
716
717    public String[] getActiveApnTypes() {
718        String[] result;
719        if (mActiveApn != null) {
720            result = mActiveApn.types;
721        } else {
722            result = new String[1];
723            result[0] = PhoneConstants.APN_TYPE_DEFAULT;
724        }
725        return result;
726    }
727
728    /** TODO: See if we can remove */
729    public String getActiveApnString(String apnType) {
730        String result = null;
731        if (mActiveApn != null) {
732            result = mActiveApn.apn;
733        }
734        return result;
735    }
736
737    /**
738     * Modify {@link android.provider.Settings.Global#DATA_ROAMING} value.
739     */
740    public void setDataOnRoamingEnabled(boolean enabled) {
741        if (getDataOnRoamingEnabled() != enabled) {
742            final ContentResolver resolver = mPhone.getContext().getContentResolver();
743            Settings.Global.putInt(resolver, Settings.Global.DATA_ROAMING, enabled ? 1 : 0);
744            // will trigger handleDataOnRoamingChange() through observer
745        }
746    }
747
748    /**
749     * Return current {@link android.provider.Settings.Global#DATA_ROAMING} value.
750     */
751    public boolean getDataOnRoamingEnabled() {
752        try {
753            final ContentResolver resolver = mPhone.getContext().getContentResolver();
754            return Settings.Global.getInt(resolver, Settings.Global.DATA_ROAMING) != 0;
755        } catch (SettingNotFoundException snfe) {
756            return false;
757        }
758    }
759
760    /**
761     * Modify {@link android.provider.Settings.Global#MOBILE_DATA} value.
762     */
763    public void setDataEnabled(boolean enable) {
764        Message msg = obtainMessage(DctConstants.CMD_SET_USER_DATA_ENABLE);
765        msg.arg1 = enable ? 1 : 0;
766        sendMessage(msg);
767    }
768
769    /**
770     * Return current {@link android.provider.Settings.Global#MOBILE_DATA} value.
771     */
772    public boolean getDataEnabled() {
773        try {
774            final ContentResolver resolver = mPhone.getContext().getContentResolver();
775            return Settings.Global.getInt(resolver, Settings.Global.MOBILE_DATA) != 0;
776        } catch (SettingNotFoundException snfe) {
777            return false;
778        }
779    }
780
781    // abstract methods
782    protected abstract void restartRadio();
783    protected abstract void log(String s);
784    protected abstract void loge(String s);
785    protected abstract boolean isDataAllowed();
786    protected abstract boolean isApnTypeAvailable(String type);
787    public    abstract DctConstants.State getState(String apnType);
788    protected abstract boolean isProvisioningApn(String apnType);
789    protected abstract void setState(DctConstants.State s);
790    protected abstract void gotoIdleAndNotifyDataConnection(String reason);
791
792    protected abstract boolean onTrySetupData(String reason);
793    protected abstract void onRoamingOff();
794    protected abstract void onRoamingOn();
795    protected abstract void onRadioAvailable();
796    protected abstract void onRadioOffOrNotAvailable();
797    protected abstract void onDataSetupComplete(AsyncResult ar);
798    protected abstract void onDataSetupCompleteError(AsyncResult ar);
799    protected abstract void onDisconnectDone(int connId, AsyncResult ar);
800    protected abstract void onDisconnectDcRetrying(int connId, AsyncResult ar);
801    protected abstract void onVoiceCallStarted();
802    protected abstract void onVoiceCallEnded();
803    protected abstract void onCleanUpConnection(boolean tearDown, int apnId, String reason);
804    protected abstract void onCleanUpAllConnections(String cause);
805    public abstract boolean isDataPossible(String apnType);
806    protected abstract void onUpdateIcc();
807    protected abstract void completeConnection(ApnContext apnContext);
808    public abstract void setDataAllowed(boolean enable, Message response);
809    public abstract String[] getPcscfAddress(String apnType);
810    public abstract void setImsRegistrationState(boolean registered);
811    protected abstract boolean mvnoMatches(IccRecords r, String mvno_type, String mvno_match_data);
812    protected abstract boolean isPermanentFail(DcFailCause dcFailCause);
813
814    @Override
815    public void handleMessage(Message msg) {
816        switch (msg.what) {
817            case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
818                log("DISCONNECTED_CONNECTED: msg=" + msg);
819                DcAsyncChannel dcac = (DcAsyncChannel) msg.obj;
820                mDataConnectionAcHashMap.remove(dcac.getDataConnectionIdSync());
821                dcac.disconnected();
822                break;
823            }
824            case DctConstants.EVENT_ENABLE_NEW_APN:
825                onEnableApn(msg.arg1, msg.arg2);
826                break;
827
828            case DctConstants.EVENT_TRY_SETUP_DATA:
829                String reason = null;
830                if (msg.obj instanceof String) {
831                    reason = (String) msg.obj;
832                }
833                onTrySetupData(reason);
834                break;
835
836            case DctConstants.EVENT_DATA_STALL_ALARM:
837                onDataStallAlarm(msg.arg1);
838                break;
839
840            case DctConstants.EVENT_ROAMING_OFF:
841                onRoamingOff();
842                break;
843
844            case DctConstants.EVENT_ROAMING_ON:
845                onRoamingOn();
846                break;
847
848            case DctConstants.EVENT_RADIO_AVAILABLE:
849                onRadioAvailable();
850                break;
851
852            case DctConstants.EVENT_RADIO_OFF_OR_NOT_AVAILABLE:
853                onRadioOffOrNotAvailable();
854                break;
855
856            case DctConstants.EVENT_DATA_SETUP_COMPLETE:
857                mCidActive = msg.arg1;
858                onDataSetupComplete((AsyncResult) msg.obj);
859                break;
860
861            case DctConstants.EVENT_DATA_SETUP_COMPLETE_ERROR:
862                onDataSetupCompleteError((AsyncResult) msg.obj);
863                break;
864
865            case DctConstants.EVENT_DISCONNECT_DONE:
866                log("DataConnectionTracker.handleMessage: EVENT_DISCONNECT_DONE msg=" + msg);
867                onDisconnectDone(msg.arg1, (AsyncResult) msg.obj);
868                break;
869
870            case DctConstants.EVENT_DISCONNECT_DC_RETRYING:
871                log("DataConnectionTracker.handleMessage: EVENT_DISCONNECT_DC_RETRYING msg=" + msg);
872                onDisconnectDcRetrying(msg.arg1, (AsyncResult) msg.obj);
873                break;
874
875            case DctConstants.EVENT_VOICE_CALL_STARTED:
876                onVoiceCallStarted();
877                break;
878
879            case DctConstants.EVENT_VOICE_CALL_ENDED:
880                onVoiceCallEnded();
881                break;
882
883            case DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS: {
884                onCleanUpAllConnections((String) msg.obj);
885                break;
886            }
887            case DctConstants.EVENT_CLEAN_UP_CONNECTION: {
888                boolean tearDown = (msg.arg1 == 0) ? false : true;
889                onCleanUpConnection(tearDown, msg.arg2, (String) msg.obj);
890                break;
891            }
892            case DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE: {
893                boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
894                onSetInternalDataEnabled(enabled);
895                break;
896            }
897            case DctConstants.EVENT_RESET_DONE: {
898                if (DBG) log("EVENT_RESET_DONE");
899                onResetDone((AsyncResult) msg.obj);
900                break;
901            }
902            case DctConstants.CMD_SET_USER_DATA_ENABLE: {
903                final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
904                if (DBG) log("CMD_SET_USER_DATA_ENABLE enabled=" + enabled);
905                onSetUserDataEnabled(enabled);
906                break;
907            }
908            case DctConstants.CMD_SET_DEPENDENCY_MET: {
909                boolean met = (msg.arg1 == DctConstants.ENABLED) ? true : false;
910                if (DBG) log("CMD_SET_DEPENDENCY_MET met=" + met);
911                Bundle bundle = msg.getData();
912                if (bundle != null) {
913                    String apnType = (String)bundle.get(DctConstants.APN_TYPE_KEY);
914                    if (apnType != null) {
915                        onSetDependencyMet(apnType, met);
916                    }
917                }
918                break;
919            }
920            case DctConstants.CMD_SET_POLICY_DATA_ENABLE: {
921                final boolean enabled = (msg.arg1 == DctConstants.ENABLED) ? true : false;
922                onSetPolicyDataEnabled(enabled);
923                break;
924            }
925            case DctConstants.CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: {
926                sEnableFailFastRefCounter += (msg.arg1 == DctConstants.ENABLED) ? 1 : -1;
927                if (DBG) {
928                    log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: "
929                            + " sEnableFailFastRefCounter=" + sEnableFailFastRefCounter);
930                }
931                if (sEnableFailFastRefCounter < 0) {
932                    final String s = "CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: "
933                            + "sEnableFailFastRefCounter:" + sEnableFailFastRefCounter + " < 0";
934                    loge(s);
935                    sEnableFailFastRefCounter = 0;
936                }
937                final boolean enabled = sEnableFailFastRefCounter > 0;
938                if (DBG) {
939                    log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: enabled=" + enabled
940                            + " sEnableFailFastRefCounter=" + sEnableFailFastRefCounter);
941                }
942                if (mFailFast != enabled) {
943                    mFailFast = enabled;
944                    mDataStallDetectionEnabled = !enabled;
945                    if (mDataStallDetectionEnabled
946                            && (getOverallState() == DctConstants.State.CONNECTED)
947                            && (!mInVoiceCall ||
948                                    mPhone.getServiceStateTracker()
949                                        .isConcurrentVoiceAndDataAllowed())) {
950                        if (DBG) log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: start data stall");
951                        stopDataStallAlarm();
952                        startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
953                    } else {
954                        if (DBG) log("CMD_SET_ENABLE_FAIL_FAST_MOBILE_DATA: stop data stall");
955                        stopDataStallAlarm();
956                    }
957                }
958
959                break;
960            }
961            case DctConstants.CMD_ENABLE_MOBILE_PROVISIONING: {
962                Bundle bundle = msg.getData();
963                if (bundle != null) {
964                    try {
965                        mProvisioningUrl = (String)bundle.get(DctConstants.PROVISIONING_URL_KEY);
966                    } catch(ClassCastException e) {
967                        loge("CMD_ENABLE_MOBILE_PROVISIONING: provisioning url not a string" + e);
968                        mProvisioningUrl = null;
969                    }
970                }
971                if (TextUtils.isEmpty(mProvisioningUrl)) {
972                    loge("CMD_ENABLE_MOBILE_PROVISIONING: provisioning url is empty, ignoring");
973                    mIsProvisioning = false;
974                    mProvisioningUrl = null;
975                } else {
976                    loge("CMD_ENABLE_MOBILE_PROVISIONING: provisioningUrl=" + mProvisioningUrl);
977                    mIsProvisioning = true;
978                    startProvisioningApnAlarm();
979                }
980                break;
981            }
982            case DctConstants.EVENT_PROVISIONING_APN_ALARM: {
983                if (DBG) log("EVENT_PROVISIONING_APN_ALARM");
984                ApnContext apnCtx = mApnContexts.get("default");
985                if (apnCtx.isProvisioningApn() && apnCtx.isConnectedOrConnecting()) {
986                    if (mProvisioningApnAlarmTag == msg.arg1) {
987                        if (DBG) log("EVENT_PROVISIONING_APN_ALARM: Disconnecting");
988                        mIsProvisioning = false;
989                        mProvisioningUrl = null;
990                        stopProvisioningApnAlarm();
991                        sendCleanUpConnection(true, apnCtx);
992                    } else {
993                        if (DBG) {
994                            log("EVENT_PROVISIONING_APN_ALARM: ignore stale tag,"
995                                    + " mProvisioningApnAlarmTag:" + mProvisioningApnAlarmTag
996                                    + " != arg1:" + msg.arg1);
997                        }
998                    }
999                } else {
1000                    if (DBG) log("EVENT_PROVISIONING_APN_ALARM: Not connected ignore");
1001                }
1002                break;
1003            }
1004            case DctConstants.CMD_IS_PROVISIONING_APN: {
1005                if (DBG) log("CMD_IS_PROVISIONING_APN");
1006                boolean isProvApn;
1007                try {
1008                    String apnType = null;
1009                    Bundle bundle = msg.getData();
1010                    if (bundle != null) {
1011                        apnType = (String)bundle.get(DctConstants.APN_TYPE_KEY);
1012                    }
1013                    if (TextUtils.isEmpty(apnType)) {
1014                        loge("CMD_IS_PROVISIONING_APN: apnType is empty");
1015                        isProvApn = false;
1016                    } else {
1017                        isProvApn = isProvisioningApn(apnType);
1018                    }
1019                } catch (ClassCastException e) {
1020                    loge("CMD_IS_PROVISIONING_APN: NO provisioning url ignoring");
1021                    isProvApn = false;
1022                }
1023                if (DBG) log("CMD_IS_PROVISIONING_APN: ret=" + isProvApn);
1024                mReplyAc.replyToMessage(msg, DctConstants.CMD_IS_PROVISIONING_APN,
1025                        isProvApn ? DctConstants.ENABLED : DctConstants.DISABLED);
1026                break;
1027            }
1028            case DctConstants.EVENT_ICC_CHANGED: {
1029                onUpdateIcc();
1030                break;
1031            }
1032            case DctConstants.EVENT_RESTART_RADIO: {
1033                restartRadio();
1034                break;
1035            }
1036            case DctConstants.CMD_NET_STAT_POLL: {
1037                if (msg.arg1 == DctConstants.ENABLED) {
1038                    handleStartNetStatPoll((DctConstants.Activity)msg.obj);
1039                } else if (msg.arg1 == DctConstants.DISABLED) {
1040                    handleStopNetStatPoll((DctConstants.Activity)msg.obj);
1041                }
1042                break;
1043            }
1044            default:
1045                Rlog.e("DATA", "Unidentified event msg=" + msg);
1046                break;
1047        }
1048    }
1049
1050    /**
1051     * Report on whether data connectivity is enabled
1052     *
1053     * @return {@code false} if data connectivity has been explicitly disabled,
1054     *         {@code true} otherwise.
1055     */
1056    public boolean getAnyDataEnabled() {
1057        final boolean result;
1058        synchronized (mDataEnabledLock) {
1059            result = (mInternalDataEnabled && mUserDataEnabled && sPolicyDataEnabled
1060                    && (mEnabledCount != 0));
1061        }
1062        if (!result && DBG) log("getAnyDataEnabled " + result);
1063        return result;
1064    }
1065
1066    protected boolean isEmergency() {
1067        final boolean result;
1068        synchronized (mDataEnabledLock) {
1069            result = mPhone.isInEcm() || mPhone.isInEmergencyCall();
1070        }
1071        log("isEmergency: result=" + result);
1072        return result;
1073    }
1074
1075    protected int apnTypeToId(String type) {
1076        if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DEFAULT)) {
1077            return DctConstants.APN_DEFAULT_ID;
1078        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_MMS)) {
1079            return DctConstants.APN_MMS_ID;
1080        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_SUPL)) {
1081            return DctConstants.APN_SUPL_ID;
1082        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_DUN)) {
1083            return DctConstants.APN_DUN_ID;
1084        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_HIPRI)) {
1085            return DctConstants.APN_HIPRI_ID;
1086        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_IMS)) {
1087            return DctConstants.APN_IMS_ID;
1088        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_FOTA)) {
1089            return DctConstants.APN_FOTA_ID;
1090        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_CBS)) {
1091            return DctConstants.APN_CBS_ID;
1092        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_IA)) {
1093            return DctConstants.APN_IA_ID;
1094        } else if (TextUtils.equals(type, PhoneConstants.APN_TYPE_EMERGENCY)) {
1095            return DctConstants.APN_EMERGENCY_ID;
1096        } else {
1097            return DctConstants.APN_INVALID_ID;
1098        }
1099    }
1100
1101    protected String apnIdToType(int id) {
1102        switch (id) {
1103        case DctConstants.APN_DEFAULT_ID:
1104            return PhoneConstants.APN_TYPE_DEFAULT;
1105        case DctConstants.APN_MMS_ID:
1106            return PhoneConstants.APN_TYPE_MMS;
1107        case DctConstants.APN_SUPL_ID:
1108            return PhoneConstants.APN_TYPE_SUPL;
1109        case DctConstants.APN_DUN_ID:
1110            return PhoneConstants.APN_TYPE_DUN;
1111        case DctConstants.APN_HIPRI_ID:
1112            return PhoneConstants.APN_TYPE_HIPRI;
1113        case DctConstants.APN_IMS_ID:
1114            return PhoneConstants.APN_TYPE_IMS;
1115        case DctConstants.APN_FOTA_ID:
1116            return PhoneConstants.APN_TYPE_FOTA;
1117        case DctConstants.APN_CBS_ID:
1118            return PhoneConstants.APN_TYPE_CBS;
1119        case DctConstants.APN_IA_ID:
1120            return PhoneConstants.APN_TYPE_IA;
1121        case DctConstants.APN_EMERGENCY_ID:
1122            return PhoneConstants.APN_TYPE_EMERGENCY;
1123        default:
1124            log("Unknown id (" + id + ") in apnIdToType");
1125            return PhoneConstants.APN_TYPE_DEFAULT;
1126        }
1127    }
1128
1129    public LinkProperties getLinkProperties(String apnType) {
1130        int id = apnTypeToId(apnType);
1131
1132        if (isApnIdEnabled(id)) {
1133            DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0);
1134            return dcac.getLinkPropertiesSync();
1135        } else {
1136            return new LinkProperties();
1137        }
1138    }
1139
1140    public NetworkCapabilities getNetworkCapabilities(String apnType) {
1141        int id = apnTypeToId(apnType);
1142        if (isApnIdEnabled(id)) {
1143            DcAsyncChannel dcac = mDataConnectionAcHashMap.get(0);
1144            return dcac.getNetworkCapabilitiesSync();
1145        } else {
1146            return new NetworkCapabilities();
1147        }
1148    }
1149
1150    // tell all active apns of the current condition
1151    protected void notifyDataConnection(String reason) {
1152        for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) {
1153            if (mDataEnabled[id]) {
1154                mPhone.notifyDataConnection(reason, apnIdToType(id));
1155            }
1156        }
1157        notifyOffApnsOfAvailability(reason);
1158    }
1159
1160    // a new APN has gone active and needs to send events to catch up with the
1161    // current condition
1162    private void notifyApnIdUpToCurrent(String reason, int apnId) {
1163        switch (mState) {
1164            case IDLE:
1165                break;
1166            case RETRYING:
1167            case CONNECTING:
1168            case SCANNING:
1169                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1170                        PhoneConstants.DataState.CONNECTING);
1171                break;
1172            case CONNECTED:
1173            case DISCONNECTING:
1174                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1175                        PhoneConstants.DataState.CONNECTING);
1176                mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1177                        PhoneConstants.DataState.CONNECTED);
1178                break;
1179            default:
1180                // Ignore
1181                break;
1182        }
1183    }
1184
1185    // since we normally don't send info to a disconnected APN, we need to do this specially
1186    private void notifyApnIdDisconnected(String reason, int apnId) {
1187        mPhone.notifyDataConnection(reason, apnIdToType(apnId),
1188                PhoneConstants.DataState.DISCONNECTED);
1189    }
1190
1191    // disabled apn's still need avail/unavail notificiations - send them out
1192    protected void notifyOffApnsOfAvailability(String reason) {
1193        if (DBG) log("notifyOffApnsOfAvailability - reason= " + reason);
1194        for (int id = 0; id < DctConstants.APN_NUM_TYPES; id++) {
1195            if (!isApnIdEnabled(id)) {
1196                notifyApnIdDisconnected(reason, id);
1197            }
1198        }
1199    }
1200
1201    public boolean isApnTypeEnabled(String apnType) {
1202        if (apnType == null) {
1203            return false;
1204        } else {
1205            return isApnIdEnabled(apnTypeToId(apnType));
1206        }
1207    }
1208
1209    protected synchronized boolean isApnIdEnabled(int id) {
1210        if (id != DctConstants.APN_INVALID_ID) {
1211            return mDataEnabled[id];
1212        }
1213        return false;
1214    }
1215
1216    protected void setEnabled(int id, boolean enable) {
1217        if (DBG) {
1218            log("setEnabled(" + id + ", " + enable + ") with old state = " + mDataEnabled[id]
1219                    + " and enabledCount = " + mEnabledCount);
1220        }
1221        Message msg = obtainMessage(DctConstants.EVENT_ENABLE_NEW_APN);
1222        msg.arg1 = id;
1223        msg.arg2 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
1224        sendMessage(msg);
1225    }
1226
1227    protected void onEnableApn(int apnId, int enabled) {
1228        if (DBG) {
1229            log("EVENT_APN_ENABLE_REQUEST apnId=" + apnId + ", apnType=" + apnIdToType(apnId) +
1230                    ", enabled=" + enabled + ", dataEnabled = " + mDataEnabled[apnId] +
1231                    ", enabledCount = " + mEnabledCount + ", isApnTypeActive = " +
1232                    isApnTypeActive(apnIdToType(apnId)));
1233        }
1234        if (enabled == DctConstants.ENABLED) {
1235            synchronized (this) {
1236                if (!mDataEnabled[apnId]) {
1237                    mDataEnabled[apnId] = true;
1238                    mEnabledCount++;
1239                }
1240            }
1241            String type = apnIdToType(apnId);
1242            if (!isApnTypeActive(type)) {
1243                mRequestedApnType = type;
1244                onEnableNewApn();
1245            } else {
1246                notifyApnIdUpToCurrent(Phone.REASON_APN_SWITCHED, apnId);
1247            }
1248        } else {
1249            // disable
1250            boolean didDisable = false;
1251            synchronized (this) {
1252                if (mDataEnabled[apnId]) {
1253                    mDataEnabled[apnId] = false;
1254                    mEnabledCount--;
1255                    didDisable = true;
1256                }
1257            }
1258            if (didDisable) {
1259                if ((mEnabledCount == 0) || (apnId == DctConstants.APN_DUN_ID)) {
1260                    mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
1261                    onCleanUpConnection(true, apnId, Phone.REASON_DATA_DISABLED);
1262                }
1263
1264                // send the disconnect msg manually, since the normal route wont send
1265                // it (it's not enabled)
1266                notifyApnIdDisconnected(Phone.REASON_DATA_DISABLED, apnId);
1267                if (mDataEnabled[DctConstants.APN_DEFAULT_ID] == true
1268                        && !isApnTypeActive(PhoneConstants.APN_TYPE_DEFAULT)) {
1269                    // TODO - this is an ugly way to restore the default conn - should be done
1270                    // by a real contention manager and policy that disconnects the lower pri
1271                    // stuff as enable requests come in and pops them back on as we disable back
1272                    // down to the lower pri stuff
1273                    mRequestedApnType = PhoneConstants.APN_TYPE_DEFAULT;
1274                    onEnableNewApn();
1275                }
1276            }
1277        }
1278    }
1279
1280    /**
1281     * Called when we switch APNs.
1282     *
1283     * mRequestedApnType is set prior to call
1284     * To be overridden.
1285     */
1286    protected void onEnableNewApn() {
1287    }
1288
1289    /**
1290     * Called when EVENT_RESET_DONE is received so goto
1291     * IDLE state and send notifications to those interested.
1292     *
1293     * TODO - currently unused.  Needs to be hooked into DataConnection cleanup
1294     * TODO - needs to pass some notion of which connection is reset..
1295     */
1296    protected void onResetDone(AsyncResult ar) {
1297        if (DBG) log("EVENT_RESET_DONE");
1298        String reason = null;
1299        if (ar.userObj instanceof String) {
1300            reason = (String) ar.userObj;
1301        }
1302        gotoIdleAndNotifyDataConnection(reason);
1303    }
1304
1305    /**
1306     * Prevent mobile data connections from being established, or once again
1307     * allow mobile data connections. If the state toggles, then either tear
1308     * down or set up data, as appropriate to match the new state.
1309     *
1310     * @param enable indicates whether to enable ({@code true}) or disable (
1311     *            {@code false}) data
1312     * @return {@code true} if the operation succeeded
1313     */
1314    public boolean setInternalDataEnabled(boolean enable) {
1315        if (DBG)
1316            log("setInternalDataEnabled(" + enable + ")");
1317
1318        Message msg = obtainMessage(DctConstants.EVENT_SET_INTERNAL_DATA_ENABLE);
1319        msg.arg1 = (enable ? DctConstants.ENABLED : DctConstants.DISABLED);
1320        sendMessage(msg);
1321        return true;
1322    }
1323
1324    protected void onSetInternalDataEnabled(boolean enabled) {
1325        synchronized (mDataEnabledLock) {
1326            mInternalDataEnabled = enabled;
1327            if (enabled) {
1328                log("onSetInternalDataEnabled: changed to enabled, try to setup data call");
1329                onTrySetupData(Phone.REASON_DATA_ENABLED);
1330            } else {
1331                log("onSetInternalDataEnabled: changed to disabled, cleanUpAllConnections");
1332                cleanUpAllConnections(null);
1333            }
1334        }
1335    }
1336
1337    public void cleanUpAllConnections(String cause) {
1338        Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_ALL_CONNECTIONS);
1339        msg.obj = cause;
1340        sendMessage(msg);
1341    }
1342
1343    public abstract boolean isDisconnected();
1344
1345    protected void onSetUserDataEnabled(boolean enabled) {
1346        synchronized (mDataEnabledLock) {
1347            if (mUserDataEnabled != enabled) {
1348                mUserDataEnabled = enabled;
1349                Settings.Global.putInt(mPhone.getContext().getContentResolver(),
1350                        Settings.Global.MOBILE_DATA, enabled ? 1 : 0);
1351                if (getDataOnRoamingEnabled() == false &&
1352                        mPhone.getServiceState().getRoaming() == true) {
1353                    if (enabled) {
1354                        notifyOffApnsOfAvailability(Phone.REASON_ROAMING_ON);
1355                    } else {
1356                        notifyOffApnsOfAvailability(Phone.REASON_DATA_DISABLED);
1357                    }
1358                }
1359
1360                if (enabled) {
1361                    onTrySetupData(Phone.REASON_DATA_ENABLED);
1362                } else {
1363                    onCleanUpAllConnections(Phone.REASON_DATA_SPECIFIC_DISABLED);
1364                }
1365            }
1366        }
1367    }
1368
1369    protected void onSetDependencyMet(String apnType, boolean met) {
1370    }
1371
1372    protected void onSetPolicyDataEnabled(boolean enabled) {
1373        synchronized (mDataEnabledLock) {
1374            final boolean prevEnabled = getAnyDataEnabled();
1375            if (sPolicyDataEnabled != enabled) {
1376                sPolicyDataEnabled = enabled;
1377                if (prevEnabled != getAnyDataEnabled()) {
1378                    if (!prevEnabled) {
1379                        onTrySetupData(Phone.REASON_DATA_ENABLED);
1380                    } else {
1381                        onCleanUpAllConnections(Phone.REASON_DATA_SPECIFIC_DISABLED);
1382                    }
1383                }
1384            }
1385        }
1386    }
1387
1388    protected String getReryConfig(boolean forDefault) {
1389        int nt = mPhone.getServiceState().getNetworkType();
1390
1391        if ((nt == TelephonyManager.NETWORK_TYPE_CDMA) ||
1392            (nt == TelephonyManager.NETWORK_TYPE_1xRTT) ||
1393            (nt == TelephonyManager.NETWORK_TYPE_EVDO_0) ||
1394            (nt == TelephonyManager.NETWORK_TYPE_EVDO_A) ||
1395            (nt == TelephonyManager.NETWORK_TYPE_EVDO_B) ||
1396            (nt == TelephonyManager.NETWORK_TYPE_EHRPD)) {
1397            // CDMA variant
1398            return SystemProperties.get("ro.cdma.data_retry_config");
1399        } else {
1400            // Use GSM varient for all others.
1401            if (forDefault) {
1402                return SystemProperties.get("ro.gsm.data_retry_config");
1403            } else {
1404                return SystemProperties.get("ro.gsm.2nd_data_retry_config");
1405            }
1406        }
1407    }
1408
1409    protected void resetPollStats() {
1410        mTxPkts = -1;
1411        mRxPkts = -1;
1412        mNetStatPollPeriod = POLL_NETSTAT_MILLIS;
1413    }
1414
1415    protected abstract DctConstants.State getOverallState();
1416
1417    void startNetStatPoll() {
1418        if (getOverallState() == DctConstants.State.CONNECTED
1419                && mNetStatPollEnabled == false) {
1420            if (DBG) {
1421                log("startNetStatPoll");
1422            }
1423            resetPollStats();
1424            mNetStatPollEnabled = true;
1425            mPollNetStat.run();
1426        }
1427        if (mPhone != null) {
1428            mPhone.notifyDataActivity();
1429        }
1430    }
1431
1432    void stopNetStatPoll() {
1433        mNetStatPollEnabled = false;
1434        removeCallbacks(mPollNetStat);
1435        if (DBG) {
1436            log("stopNetStatPoll");
1437        }
1438
1439        // To sync data activity icon in the case of switching data connection to send MMS.
1440        if (mPhone != null) {
1441            mPhone.notifyDataActivity();
1442        }
1443    }
1444
1445    public void sendStartNetStatPoll(DctConstants.Activity activity) {
1446        Message msg = obtainMessage(DctConstants.CMD_NET_STAT_POLL);
1447        msg.arg1 = DctConstants.ENABLED;
1448        msg.obj = activity;
1449        sendMessage(msg);
1450    }
1451
1452    protected void handleStartNetStatPoll(DctConstants.Activity activity) {
1453        startNetStatPoll();
1454        startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
1455        setActivity(activity);
1456    }
1457
1458    public void sendStopNetStatPoll(DctConstants.Activity activity) {
1459        Message msg = obtainMessage(DctConstants.CMD_NET_STAT_POLL);
1460        msg.arg1 = DctConstants.DISABLED;
1461        msg.obj = activity;
1462        sendMessage(msg);
1463    }
1464
1465    protected void handleStopNetStatPoll(DctConstants.Activity activity) {
1466        stopNetStatPoll();
1467        stopDataStallAlarm();
1468        setActivity(activity);
1469    }
1470
1471    public void updateDataActivity() {
1472        long sent, received;
1473
1474        DctConstants.Activity newActivity;
1475
1476        TxRxSum preTxRxSum = new TxRxSum(mTxPkts, mRxPkts);
1477        TxRxSum curTxRxSum = new TxRxSum();
1478        curTxRxSum.updateTxRxSum();
1479        mTxPkts = curTxRxSum.txPkts;
1480        mRxPkts = curTxRxSum.rxPkts;
1481
1482        if (VDBG) {
1483            log("updateDataActivity: curTxRxSum=" + curTxRxSum + " preTxRxSum=" + preTxRxSum);
1484        }
1485
1486        if (mNetStatPollEnabled && (preTxRxSum.txPkts > 0 || preTxRxSum.rxPkts > 0)) {
1487            sent = mTxPkts - preTxRxSum.txPkts;
1488            received = mRxPkts - preTxRxSum.rxPkts;
1489
1490            if (VDBG)
1491                log("updateDataActivity: sent=" + sent + " received=" + received);
1492            if (sent > 0 && received > 0) {
1493                newActivity = DctConstants.Activity.DATAINANDOUT;
1494            } else if (sent > 0 && received == 0) {
1495                newActivity = DctConstants.Activity.DATAOUT;
1496            } else if (sent == 0 && received > 0) {
1497                newActivity = DctConstants.Activity.DATAIN;
1498            } else {
1499                newActivity = (mActivity == DctConstants.Activity.DORMANT) ?
1500                        mActivity : DctConstants.Activity.NONE;
1501            }
1502
1503            if (mActivity != newActivity && mIsScreenOn) {
1504                if (VDBG)
1505                    log("updateDataActivity: newActivity=" + newActivity);
1506                mActivity = newActivity;
1507                mPhone.notifyDataActivity();
1508            }
1509        }
1510    }
1511
1512    // Recovery action taken in case of data stall
1513    protected static class RecoveryAction {
1514        public static final int GET_DATA_CALL_LIST      = 0;
1515        public static final int CLEANUP                 = 1;
1516        public static final int REREGISTER              = 2;
1517        public static final int RADIO_RESTART           = 3;
1518        public static final int RADIO_RESTART_WITH_PROP = 4;
1519
1520        private static boolean isAggressiveRecovery(int value) {
1521            return ((value == RecoveryAction.CLEANUP) ||
1522                    (value == RecoveryAction.REREGISTER) ||
1523                    (value == RecoveryAction.RADIO_RESTART) ||
1524                    (value == RecoveryAction.RADIO_RESTART_WITH_PROP));
1525        }
1526    }
1527
1528    public int getRecoveryAction() {
1529        int action = Settings.System.getInt(mPhone.getContext().getContentResolver(),
1530                "radio.data.stall.recovery.action", RecoveryAction.GET_DATA_CALL_LIST);
1531        if (VDBG_STALL) log("getRecoveryAction: " + action);
1532        return action;
1533    }
1534    public void putRecoveryAction(int action) {
1535        Settings.System.putInt(mPhone.getContext().getContentResolver(),
1536                "radio.data.stall.recovery.action", action);
1537        if (VDBG_STALL) log("putRecoveryAction: " + action);
1538    }
1539
1540    protected boolean isConnected() {
1541        return false;
1542    }
1543
1544    protected void doRecovery() {
1545        if (getOverallState() == DctConstants.State.CONNECTED) {
1546            // Go through a series of recovery steps, each action transitions to the next action
1547            int recoveryAction = getRecoveryAction();
1548            switch (recoveryAction) {
1549            case RecoveryAction.GET_DATA_CALL_LIST:
1550                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_GET_DATA_CALL_LIST,
1551                        mSentSinceLastRecv);
1552                if (DBG) log("doRecovery() get data call list");
1553                mPhone.mCi.getDataCallList(obtainMessage(DctConstants.EVENT_DATA_STATE_CHANGED));
1554                putRecoveryAction(RecoveryAction.CLEANUP);
1555                break;
1556            case RecoveryAction.CLEANUP:
1557                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_CLEANUP, mSentSinceLastRecv);
1558                if (DBG) log("doRecovery() cleanup all connections");
1559                cleanUpAllConnections(Phone.REASON_PDP_RESET);
1560                putRecoveryAction(RecoveryAction.REREGISTER);
1561                break;
1562            case RecoveryAction.REREGISTER:
1563                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_REREGISTER,
1564                        mSentSinceLastRecv);
1565                if (DBG) log("doRecovery() re-register");
1566                mPhone.getServiceStateTracker().reRegisterNetwork(null);
1567                putRecoveryAction(RecoveryAction.RADIO_RESTART);
1568                break;
1569            case RecoveryAction.RADIO_RESTART:
1570                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART,
1571                        mSentSinceLastRecv);
1572                if (DBG) log("restarting radio");
1573                putRecoveryAction(RecoveryAction.RADIO_RESTART_WITH_PROP);
1574                restartRadio();
1575                break;
1576            case RecoveryAction.RADIO_RESTART_WITH_PROP:
1577                // This is in case radio restart has not recovered the data.
1578                // It will set an additional "gsm.radioreset" property to tell
1579                // RIL or system to take further action.
1580                // The implementation of hard reset recovery action is up to OEM product.
1581                // Once RADIO_RESET property is consumed, it is expected to set back
1582                // to false by RIL.
1583                EventLog.writeEvent(EventLogTags.DATA_STALL_RECOVERY_RADIO_RESTART_WITH_PROP, -1);
1584                if (DBG) log("restarting radio with gsm.radioreset to true");
1585                SystemProperties.set(RADIO_RESET_PROPERTY, "true");
1586                // give 1 sec so property change can be notified.
1587                try {
1588                    Thread.sleep(1000);
1589                } catch (InterruptedException e) {}
1590                restartRadio();
1591                putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1592                break;
1593            default:
1594                throw new RuntimeException("doRecovery: Invalid recoveryAction=" +
1595                    recoveryAction);
1596            }
1597            mSentSinceLastRecv = 0;
1598        }
1599    }
1600
1601    private void updateDataStallInfo() {
1602        long sent, received;
1603
1604        TxRxSum preTxRxSum = new TxRxSum(mDataStallTxRxSum);
1605        mDataStallTxRxSum.updateTxRxSum();
1606
1607        if (VDBG_STALL) {
1608            log("updateDataStallInfo: mDataStallTxRxSum=" + mDataStallTxRxSum +
1609                    " preTxRxSum=" + preTxRxSum);
1610        }
1611
1612        sent = mDataStallTxRxSum.txPkts - preTxRxSum.txPkts;
1613        received = mDataStallTxRxSum.rxPkts - preTxRxSum.rxPkts;
1614
1615        if (RADIO_TESTS) {
1616            if (SystemProperties.getBoolean("radio.test.data.stall", false)) {
1617                log("updateDataStallInfo: radio.test.data.stall true received = 0;");
1618                received = 0;
1619            }
1620        }
1621        if ( sent > 0 && received > 0 ) {
1622            if (VDBG_STALL) log("updateDataStallInfo: IN/OUT");
1623            mSentSinceLastRecv = 0;
1624            putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1625        } else if (sent > 0 && received == 0) {
1626            if (mPhone.getState() == PhoneConstants.State.IDLE) {
1627                mSentSinceLastRecv += sent;
1628            } else {
1629                mSentSinceLastRecv = 0;
1630            }
1631            if (DBG) {
1632                log("updateDataStallInfo: OUT sent=" + sent +
1633                        " mSentSinceLastRecv=" + mSentSinceLastRecv);
1634            }
1635        } else if (sent == 0 && received > 0) {
1636            if (VDBG_STALL) log("updateDataStallInfo: IN");
1637            mSentSinceLastRecv = 0;
1638            putRecoveryAction(RecoveryAction.GET_DATA_CALL_LIST);
1639        } else {
1640            if (VDBG_STALL) log("updateDataStallInfo: NONE");
1641        }
1642    }
1643
1644    protected void onDataStallAlarm(int tag) {
1645        if (mDataStallAlarmTag != tag) {
1646            if (DBG) {
1647                log("onDataStallAlarm: ignore, tag=" + tag + " expecting " + mDataStallAlarmTag);
1648            }
1649            return;
1650        }
1651        updateDataStallInfo();
1652
1653        int hangWatchdogTrigger = Settings.Global.getInt(mResolver,
1654                Settings.Global.PDP_WATCHDOG_TRIGGER_PACKET_COUNT,
1655                NUMBER_SENT_PACKETS_OF_HANG);
1656
1657        boolean suspectedStall = DATA_STALL_NOT_SUSPECTED;
1658        if (mSentSinceLastRecv >= hangWatchdogTrigger) {
1659            if (DBG) {
1660                log("onDataStallAlarm: tag=" + tag + " do recovery action=" + getRecoveryAction());
1661            }
1662            suspectedStall = DATA_STALL_SUSPECTED;
1663            sendMessage(obtainMessage(DctConstants.EVENT_DO_RECOVERY));
1664        } else {
1665            if (VDBG_STALL) {
1666                log("onDataStallAlarm: tag=" + tag + " Sent " + String.valueOf(mSentSinceLastRecv) +
1667                    " pkts since last received, < watchdogTrigger=" + hangWatchdogTrigger);
1668            }
1669        }
1670        startDataStallAlarm(suspectedStall);
1671    }
1672
1673    protected void startDataStallAlarm(boolean suspectedStall) {
1674        int nextAction = getRecoveryAction();
1675        int delayInMs;
1676
1677        if (mDataStallDetectionEnabled && getOverallState() == DctConstants.State.CONNECTED) {
1678            // If screen is on or data stall is currently suspected, set the alarm
1679            // with an aggresive timeout.
1680            if (mIsScreenOn || suspectedStall || RecoveryAction.isAggressiveRecovery(nextAction)) {
1681                delayInMs = Settings.Global.getInt(mResolver,
1682                        Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS,
1683                        DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS_DEFAULT);
1684            } else {
1685                delayInMs = Settings.Global.getInt(mResolver,
1686                        Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS,
1687                        DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS_DEFAULT);
1688            }
1689
1690            mDataStallAlarmTag += 1;
1691            if (VDBG_STALL) {
1692                log("startDataStallAlarm: tag=" + mDataStallAlarmTag +
1693                        " delay=" + (delayInMs / 1000) + "s");
1694            }
1695            Intent intent = new Intent(INTENT_DATA_STALL_ALARM);
1696            intent.putExtra(DATA_STALL_ALARM_TAG_EXTRA, mDataStallAlarmTag);
1697            mDataStallAlarmIntent = PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
1698                    PendingIntent.FLAG_UPDATE_CURRENT);
1699            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1700                    SystemClock.elapsedRealtime() + delayInMs, mDataStallAlarmIntent);
1701        } else {
1702            if (VDBG_STALL) {
1703                log("startDataStallAlarm: NOT started, no connection tag=" + mDataStallAlarmTag);
1704            }
1705        }
1706    }
1707
1708    protected void stopDataStallAlarm() {
1709        if (VDBG_STALL) {
1710            log("stopDataStallAlarm: current tag=" + mDataStallAlarmTag +
1711                    " mDataStallAlarmIntent=" + mDataStallAlarmIntent);
1712        }
1713        mDataStallAlarmTag += 1;
1714        if (mDataStallAlarmIntent != null) {
1715            mAlarmManager.cancel(mDataStallAlarmIntent);
1716            mDataStallAlarmIntent = null;
1717        }
1718    }
1719
1720    protected void restartDataStallAlarm() {
1721        if (isConnected() == false) return;
1722        // To be called on screen status change.
1723        // Do not cancel the alarm if it is set with aggressive timeout.
1724        int nextAction = getRecoveryAction();
1725
1726        if (RecoveryAction.isAggressiveRecovery(nextAction)) {
1727            if (DBG) log("restartDataStallAlarm: action is pending. not resetting the alarm.");
1728            return;
1729        }
1730        if (VDBG_STALL) log("restartDataStallAlarm: stop then start.");
1731        stopDataStallAlarm();
1732        startDataStallAlarm(DATA_STALL_NOT_SUSPECTED);
1733    }
1734
1735    protected void setInitialAttachApn() {
1736        ApnSetting iaApnSetting = null;
1737        ApnSetting defaultApnSetting = null;
1738        ApnSetting firstApnSetting = null;
1739
1740        log("setInitialApn: E mPreferredApn=" + mPreferredApn);
1741
1742        if (mAllApnSettings != null && !mAllApnSettings.isEmpty()) {
1743            firstApnSetting = mAllApnSettings.get(0);
1744            log("setInitialApn: firstApnSetting=" + firstApnSetting);
1745
1746            // Search for Initial APN setting and the first apn that can handle default
1747            for (ApnSetting apn : mAllApnSettings) {
1748                // Can't use apn.canHandleType(), as that returns true for APNs that have no type.
1749                if (ArrayUtils.contains(apn.types, PhoneConstants.APN_TYPE_IA) &&
1750                        apn.carrierEnabled) {
1751                    // The Initial Attach APN is highest priority so use it if there is one
1752                    log("setInitialApn: iaApnSetting=" + apn);
1753                    iaApnSetting = apn;
1754                    break;
1755                } else if ((defaultApnSetting == null)
1756                        && (apn.canHandleType(PhoneConstants.APN_TYPE_DEFAULT))) {
1757                    // Use the first default apn if no better choice
1758                    log("setInitialApn: defaultApnSetting=" + apn);
1759                    defaultApnSetting = apn;
1760                }
1761            }
1762        }
1763
1764        // The priority of apn candidates from highest to lowest is:
1765        //   1) APN_TYPE_IA (Inital Attach)
1766        //   2) mPreferredApn, i.e. the current preferred apn
1767        //   3) The first apn that than handle APN_TYPE_DEFAULT
1768        //   4) The first APN we can find.
1769
1770        ApnSetting initialAttachApnSetting = null;
1771        if (iaApnSetting != null) {
1772            if (DBG) log("setInitialAttachApn: using iaApnSetting");
1773            initialAttachApnSetting = iaApnSetting;
1774        } else if (mPreferredApn != null) {
1775            if (DBG) log("setInitialAttachApn: using mPreferredApn");
1776            initialAttachApnSetting = mPreferredApn;
1777        } else if (defaultApnSetting != null) {
1778            if (DBG) log("setInitialAttachApn: using defaultApnSetting");
1779            initialAttachApnSetting = defaultApnSetting;
1780        } else if (firstApnSetting != null) {
1781            if (DBG) log("setInitialAttachApn: using firstApnSetting");
1782            initialAttachApnSetting = firstApnSetting;
1783        }
1784
1785        if (initialAttachApnSetting == null) {
1786            if (DBG) log("setInitialAttachApn: X There in no available apn");
1787        } else {
1788            if (DBG) log("setInitialAttachApn: X selected Apn=" + initialAttachApnSetting);
1789
1790            mPhone.mCi.setInitialAttachApn(initialAttachApnSetting.apn,
1791                    initialAttachApnSetting.protocol, initialAttachApnSetting.authType,
1792                    initialAttachApnSetting.user, initialAttachApnSetting.password, null);
1793        }
1794    }
1795
1796    protected void setDataProfilesAsNeeded() {
1797        if (DBG) log("setDataProfilesAsNeeded");
1798        if (mAllApnSettings != null && !mAllApnSettings.isEmpty()) {
1799            ArrayList<DataProfile> dps = new ArrayList<DataProfile>();
1800            for (ApnSetting apn : mAllApnSettings) {
1801                if (apn.modemCognitive) {
1802                    DataProfile dp = new DataProfile(apn,
1803                            mPhone.getServiceState().getRoaming());
1804                    boolean isDup = false;
1805                    for(DataProfile dpIn : dps) {
1806                        if (dp.equals(dpIn)) {
1807                            isDup = true;
1808                            break;
1809                        }
1810                    }
1811                    if (!isDup) {
1812                        dps.add(dp);
1813                    }
1814                }
1815            }
1816            if(dps.size() > 0) {
1817                mPhone.mCi.setDataProfile(dps.toArray(new DataProfile[0]), null);
1818            }
1819        }
1820    }
1821
1822    protected void onActionIntentProvisioningApnAlarm(Intent intent) {
1823        if (DBG) log("onActionIntentProvisioningApnAlarm: action=" + intent.getAction());
1824        Message msg = obtainMessage(DctConstants.EVENT_PROVISIONING_APN_ALARM,
1825                intent.getAction());
1826        msg.arg1 = intent.getIntExtra(PROVISIONING_APN_ALARM_TAG_EXTRA, 0);
1827        sendMessage(msg);
1828    }
1829
1830    protected void startProvisioningApnAlarm() {
1831        int delayInMs = Settings.Global.getInt(mResolver,
1832                                Settings.Global.PROVISIONING_APN_ALARM_DELAY_IN_MS,
1833                                PROVISIONING_APN_ALARM_DELAY_IN_MS_DEFAULT);
1834        if (Build.IS_DEBUGGABLE) {
1835            // Allow debug code to use a system property to provide another value
1836            String delayInMsStrg = Integer.toString(delayInMs);
1837            delayInMsStrg = System.getProperty(DEBUG_PROV_APN_ALARM, delayInMsStrg);
1838            try {
1839                delayInMs = Integer.parseInt(delayInMsStrg);
1840            } catch (NumberFormatException e) {
1841                loge("startProvisioningApnAlarm: e=" + e);
1842            }
1843        }
1844        mProvisioningApnAlarmTag += 1;
1845        if (DBG) {
1846            log("startProvisioningApnAlarm: tag=" + mProvisioningApnAlarmTag +
1847                    " delay=" + (delayInMs / 1000) + "s");
1848        }
1849        Intent intent = new Intent(INTENT_PROVISIONING_APN_ALARM);
1850        intent.putExtra(PROVISIONING_APN_ALARM_TAG_EXTRA, mProvisioningApnAlarmTag);
1851        mProvisioningApnAlarmIntent = PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
1852                PendingIntent.FLAG_UPDATE_CURRENT);
1853        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1854                SystemClock.elapsedRealtime() + delayInMs, mProvisioningApnAlarmIntent);
1855    }
1856
1857    protected void stopProvisioningApnAlarm() {
1858        if (DBG) {
1859            log("stopProvisioningApnAlarm: current tag=" + mProvisioningApnAlarmTag +
1860                    " mProvsioningApnAlarmIntent=" + mProvisioningApnAlarmIntent);
1861        }
1862        mProvisioningApnAlarmTag += 1;
1863        if (mProvisioningApnAlarmIntent != null) {
1864            mAlarmManager.cancel(mProvisioningApnAlarmIntent);
1865            mProvisioningApnAlarmIntent = null;
1866        }
1867    }
1868
1869    void sendCleanUpConnection(boolean tearDown, ApnContext apnContext) {
1870        if (DBG)log("sendCleanUpConnection: tearDown=" + tearDown + " apnContext=" + apnContext);
1871        Message msg = obtainMessage(DctConstants.EVENT_CLEAN_UP_CONNECTION);
1872        msg.arg1 = tearDown ? 1 : 0;
1873        msg.arg2 = 0;
1874        msg.obj = apnContext;
1875        sendMessage(msg);
1876    }
1877
1878    void sendRestartRadio() {
1879        if (DBG)log("sendRestartRadio:");
1880        Message msg = obtainMessage(DctConstants.EVENT_RESTART_RADIO);
1881        sendMessage(msg);
1882    }
1883
1884    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1885        pw.println("DcTrackerBase:");
1886        pw.println(" RADIO_TESTS=" + RADIO_TESTS);
1887        pw.println(" mInternalDataEnabled=" + mInternalDataEnabled);
1888        pw.println(" mUserDataEnabled=" + mUserDataEnabled);
1889        pw.println(" sPolicyDataEnabed=" + sPolicyDataEnabled);
1890        pw.println(" mDataEnabled:");
1891        for(int i=0; i < mDataEnabled.length; i++) {
1892            pw.printf("  mDataEnabled[%d]=%b\n", i, mDataEnabled[i]);
1893        }
1894        pw.flush();
1895        pw.println(" mEnabledCount=" + mEnabledCount);
1896        pw.println(" mRequestedApnType=" + mRequestedApnType);
1897        pw.println(" mPhone=" + mPhone.getPhoneName());
1898        pw.println(" mActivity=" + mActivity);
1899        pw.println(" mState=" + mState);
1900        pw.println(" mTxPkts=" + mTxPkts);
1901        pw.println(" mRxPkts=" + mRxPkts);
1902        pw.println(" mNetStatPollPeriod=" + mNetStatPollPeriod);
1903        pw.println(" mNetStatPollEnabled=" + mNetStatPollEnabled);
1904        pw.println(" mDataStallTxRxSum=" + mDataStallTxRxSum);
1905        pw.println(" mDataStallAlarmTag=" + mDataStallAlarmTag);
1906        pw.println(" mDataStallDetectionEanbled=" + mDataStallDetectionEnabled);
1907        pw.println(" mSentSinceLastRecv=" + mSentSinceLastRecv);
1908        pw.println(" mNoRecvPollCount=" + mNoRecvPollCount);
1909        pw.println(" mResolver=" + mResolver);
1910        pw.println(" mIsWifiConnected=" + mIsWifiConnected);
1911        pw.println(" mReconnectIntent=" + mReconnectIntent);
1912        pw.println(" mCidActive=" + mCidActive);
1913        pw.println(" mAutoAttachOnCreation=" + mAutoAttachOnCreation);
1914        pw.println(" mIsScreenOn=" + mIsScreenOn);
1915        pw.println(" mUniqueIdGenerator=" + mUniqueIdGenerator);
1916        pw.flush();
1917        pw.println(" ***************************************");
1918        DcController dcc = mDcc;
1919        if (dcc != null) {
1920            dcc.dump(fd, pw, args);
1921        } else {
1922            pw.println(" mDcc=null");
1923        }
1924        pw.println(" ***************************************");
1925        HashMap<Integer, DataConnection> dcs = mDataConnections;
1926        if (dcs != null) {
1927            Set<Entry<Integer, DataConnection> > mDcSet = mDataConnections.entrySet();
1928            pw.println(" mDataConnections: count=" + mDcSet.size());
1929            for (Entry<Integer, DataConnection> entry : mDcSet) {
1930                pw.printf(" *** mDataConnection[%d] \n", entry.getKey());
1931                entry.getValue().dump(fd, pw, args);
1932            }
1933        } else {
1934            pw.println("mDataConnections=null");
1935        }
1936        pw.println(" ***************************************");
1937        pw.flush();
1938        HashMap<String, Integer> apnToDcId = mApnToDataConnectionId;
1939        if (apnToDcId != null) {
1940            Set<Entry<String, Integer>> apnToDcIdSet = apnToDcId.entrySet();
1941            pw.println(" mApnToDataConnectonId size=" + apnToDcIdSet.size());
1942            for (Entry<String, Integer> entry : apnToDcIdSet) {
1943                pw.printf(" mApnToDataConnectonId[%s]=%d\n", entry.getKey(), entry.getValue());
1944            }
1945        } else {
1946            pw.println("mApnToDataConnectionId=null");
1947        }
1948        pw.println(" ***************************************");
1949        pw.flush();
1950        ConcurrentHashMap<String, ApnContext> apnCtxs = mApnContexts;
1951        if (apnCtxs != null) {
1952            Set<Entry<String, ApnContext>> apnCtxsSet = apnCtxs.entrySet();
1953            pw.println(" mApnContexts size=" + apnCtxsSet.size());
1954            for (Entry<String, ApnContext> entry : apnCtxsSet) {
1955                entry.getValue().dump(fd, pw, args);
1956            }
1957            pw.println(" ***************************************");
1958        } else {
1959            pw.println(" mApnContexts=null");
1960        }
1961        pw.flush();
1962        pw.println(" mActiveApn=" + mActiveApn);
1963        ArrayList<ApnSetting> apnSettings = mAllApnSettings;
1964        if (apnSettings != null) {
1965            pw.println(" mAllApnSettings size=" + apnSettings.size());
1966            for (int i=0; i < apnSettings.size(); i++) {
1967                pw.printf(" mAllApnSettings[%d]: %s\n", i, apnSettings.get(i));
1968            }
1969            pw.flush();
1970        } else {
1971            pw.println(" mAllApnSettings=null");
1972        }
1973        pw.println(" mPreferredApn=" + mPreferredApn);
1974        pw.println(" mIsPsRestricted=" + mIsPsRestricted);
1975        pw.println(" mIsDisposed=" + mIsDisposed);
1976        pw.println(" mIntentReceiver=" + mIntentReceiver);
1977        pw.println(" mDataRoamingSettingObserver=" + mDataRoamingSettingObserver);
1978        pw.flush();
1979    }
1980}
1981