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