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