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