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