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