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