summaryrefslogtreecommitdiffstats
path: root/ipalib/plugins/selinuxusermap.py
blob: 32c55850b7d5b78f39cfae8960b8588a35b30251 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# Authors:
#   Rob Crittenden <rcritten@redhat.com>
#
# Copyright (C) 2011  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from ipalib import api, errors
from ipalib import Str, StrEnum, Bool
from ipalib.plugins.baseldap import *
from ipalib import _, ngettext
from ipalib.plugins.hbacrule import is_all

__doc__ = _("""
SELinux User Mapping

Map IPA users to SELinux users by host.

Hosts, hostgroups, users and groups can be either defined within
the rule or it may point to an existing HBAC rule. When using
--hbacrule option to selinuxusermap-find an exact match is made on the
HBAC rule name, so only one or zero entries will be returned.

EXAMPLES:

 Create a rule, "test1", that sets all users to xguest_u:s0 on the host "server":
   ipa selinuxusermap-add --usercat=all --selinuxuser=xguest_u:s0 test1
   ipa selinuxusermap-add-host --hosts=server.example.com test1

 Create a rule, "test2", that sets all users to guest_u:s0 and uses an existing HBAC rule for users and hosts:
   ipa selinuxusermap-add --usercat=all --hbacrule=webserver --selinuxuser=guest_u:s0 test2

 Display the properties of a rule:
   ipa selinuxusermap-show test2

 Create a rule for a specific user. This sets the SELinux context for
 user john to unconfined_u:s0-s0:c0.c1023 on any machine:
   ipa selinuxusermap-add --hostcat=all --selinuxuser=unconfined_u:s0-s0:c0.c1023 john_unconfined
   ipa selinuxusermap-add-user --users=john john_unconfined

 Disable a rule:
   ipa selinuxusermap-disable test1

 Enable a rule:
   ipa selinuxusermap-enable test1

 Find a rule referencing a specific HBAC rule:
   ipa selinuxusermap-find --hbacrule=allow_some

 Remove a rule:
   ipa selinuxusermap-del john_unconfined

SEEALSO:

 The list controlling the order in which the SELinux user map is applied
 and the default SELinux user are available in the config-show command.
""")

notboth_err = _('HBAC rule and local members cannot both be set')


def validate_selinuxuser(ugettext, user):
    """
    An SELinux user has 3 components: user:MLS:MCS. user and MLS are required.
    user traditionally ends with _u but this is not mandatory.
      The regex is ^[a-zA-Z][a-zA-Z_]*

    The MLS part can only be:
      Level: s[0-15](-s[0-15])

    Then MCS could be c[0-1023].c[0-1023] and/or c[0-1023]-c[0-c0123]
    Meaning
    s0 s0-s1 s0-s15:c0.c1023 s0-s1:c0,c2,c15.c26 s0-s0:c0.c1023

    Returns a message on invalid, returns nothing on valid.
    """
    regex_name = re.compile(r'^[a-zA-Z][a-zA-Z_]*$')
    regex_mls = re.compile(r'^s[0-9][1-5]{0,1}(-s[0-9][1-5]{0,1}){0,1}$')
    regex_mcs = re.compile(r'^c(\d+)([.,-]c(\d+))*?$')

    # If we add in ::: we don't have to check to see if some values are
    # empty
    (name, mls, mcs, ignore) = (user + ':::').split(':', 3)

    if not regex_name.match(name):
        return _('Invalid SELinux user name, only a-Z and _ are allowed')
    if not mls or not regex_mls.match(mls):
        return _('Invalid MLS value, must match s[0-15](-s[0-15])')
    m = regex_mcs.match(mcs)
    if mcs and (not m or (m.group(3) and (int(m.group(3)) > 1023))):
        return _('Invalid MCS value, must match c[0-1023].c[0-1023] '
                 'and/or c[0-1023]-c[0-c0123]')

    return None


def validate_selinuxuser_inlist(ldap, user):
    """
    Ensure the user is in the list of allowed SELinux users.

    Returns nothing if the user is found, raises an exception otherwise.
    """
    config = ldap.get_ipa_config()[1]
    item = config.get('ipaselinuxusermaporder', [])
    if len(item) != 1:
        raise errors.NotFound(reason=_('SELinux user map list not '
                                       'found in configuration'))
    userlist = item[0].split('$')
    if user not in userlist:
        raise errors.NotFound(
            reason=_('SELinux user %(user)s not found in '
                     'ordering list (in config)') % dict(user=user))

    return


class selinuxusermap(LDAPObject):
    """
    SELinux User Map object.
    """
    container_dn = api.env.container_selinux
    object_name = _('SELinux User Map rule')
    object_name_plural = _('SELinux User Map rules')
    object_class = ['ipaassociation', 'ipaselinuxusermap']
    default_attributes = [
        'cn', 'ipaenabledflag',
        'description', 'usercategory', 'hostcategory',
        'ipaenabledflag', 'memberuser', 'memberhost',
        'memberhostgroup', 'seealso', 'ipaselinuxuser',
    ]
    uuid_attribute = 'ipauniqueid'
    rdn_attribute = 'ipauniqueid'
    attribute_members = {
        'memberuser': ['user', 'group'],
        'memberhost': ['host', 'hostgroup'],
    }

    # These maps will not show as members of other entries

    label = _('SELinux User Maps')
    label_singular = _('SELinux User Map')

    takes_params = (
        Str('cn',
            cli_name='name',
            label=_('Rule name'),
            primary_key=True,
        ),
        Str('ipaselinuxuser', validate_selinuxuser,
            cli_name='selinuxuser',
            label=_('SELinux User'),
        ),
        Str('seealso?',
            cli_name='hbacrule',
            label=_('HBAC Rule'),
            doc=_('HBAC Rule that defines the users, groups and hostgroups'),
        ),
        StrEnum('usercategory?',
            cli_name='usercat',
            label=_('User category'),
            doc=_('User category the rule applies to'),
            values=(u'all', ),
        ),
        StrEnum('hostcategory?',
            cli_name='hostcat',
            label=_('Host category'),
            doc=_('Host category the rule applies to'),
            values=(u'all', ),
        ),
        Str('description?',
            cli_name='desc',
            label=_('Description'),
        ),
        Bool('ipaenabledflag?',
             label=_('Enabled'),
             flags=['no_option'],
        ),
        Str('memberuser_user?',
            label=_('Users'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str('memberuser_group?',
            label=_('User Groups'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str('memberhost_host?',
            label=_('Hosts'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str('memberhost_hostgroup?',
            label=_('Host Groups'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
    )

    def _normalize_seealso(self, seealso):
        """
        Given a HBAC rule name verify its existence and return the dn.
        """
        if not seealso:
            return None

        try:
            dn = DN(seealso)
            return str(dn)
        except ValueError:
            try:
                (dn, entry_attrs) = self.backend.find_entry_by_attr(
                    self.api.Object['hbacrule'].primary_key.name,
                    seealso,
                    self.api.Object['hbacrule'].object_class,
                    [''],
                    self.api.Object['hbacrule'].container_dn)
                seealso = dn
            except errors.NotFound:
                raise errors.NotFound(reason=_('HBAC rule %(rule)s not found') % dict(rule=seealso))

        return seealso

    def _convert_seealso(self, ldap, entry_attrs, **options):
        """
        Convert an HBAC rule dn into a name
        """
        if options.get('raw', False):
            return

        if 'seealso' in entry_attrs:
            (hbac_dn, hbac_attrs) = ldap.get_entry(entry_attrs['seealso'][0], ['cn'])
            entry_attrs['seealso'] = hbac_attrs['cn'][0]

api.register(selinuxusermap)


class selinuxusermap_add(LDAPCreate):
    __doc__ = _('Create a new SELinux User Map.')

    msg_summary = _('Added SELinux User Map "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        # rules are enabled by default
        entry_attrs['ipaenabledflag'] = 'TRUE'
        validate_selinuxuser_inlist(ldap, entry_attrs['ipaselinuxuser'])

        # hbacrule is not allowed when usercat or hostcat is set
        is_to_be_set = lambda x: x in entry_attrs and entry_attrs[x] != None

        are_local_members_to_be_set = any(is_to_be_set(attr)
                                          for attr in ('usercategory',
                                                       'hostcategory'))

        is_hbacrule_to_be_set = is_to_be_set('seealso')

        if is_hbacrule_to_be_set and are_local_members_to_be_set:
            raise errors.MutuallyExclusiveError(reason=notboth_err)

        if is_hbacrule_to_be_set:
            entry_attrs['seealso'] = self.obj._normalize_seealso(entry_attrs['seealso'])

        return dn

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        self.obj._convert_seealso(ldap, entry_attrs, **options)

        return dn

api.register(selinuxusermap_add)


class selinuxusermap_del(LDAPDelete):
    __doc__ = _('Delete a SELinux User Map.')

    msg_summary = _('Deleted SELinux User Map "%(value)s"')

api.register(selinuxusermap_del)


class selinuxusermap_mod(LDAPUpdate):
    __doc__ = _('Modify a SELinux User Map.')

    msg_summary = _('Modified SELinux User Map "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        try:
            (_dn, _entry_attrs) = ldap.get_entry(dn, attrs_list)
        except errors.NotFound:
            self.obj.handle_not_found(*keys)

        is_to_be_deleted = lambda x: (x in _entry_attrs and x in entry_attrs) and \
                                     entry_attrs[x] == None

        # makes sure the local members and hbacrule is not set at the same time
        # memberuser or memberhost could have been set using --setattr
        is_to_be_set = lambda x: ((x in _entry_attrs and _entry_attrs[x] != None) or \
                                 (x in entry_attrs and entry_attrs[x] != None)) and \
                                 not is_to_be_deleted(x)

        are_local_members_to_be_set = any(is_to_be_set(attr)
                                          for attr in ('usercategory',
                                                       'hostcategory',
                                                       'memberuser',
                                                       'memberhost'))

        is_hbacrule_to_be_set = is_to_be_set('seealso')

        # this can disable all modifications if hbacrule and local members were
        # set at the same time bypassing this commad, e.g. using ldapmodify
        if are_local_members_to_be_set and is_hbacrule_to_be_set:
            raise errors.MutuallyExclusiveError(reason=notboth_err)

        if is_all(entry_attrs, 'usercategory') and 'memberuser' in entry_attrs:
            raise errors.MutuallyExclusiveError(reason="user category "
                 "cannot be set to 'all' while there are allowed users")
        if is_all(entry_attrs, 'hostcategory') and 'memberhost' in entry_attrs:
            raise errors.MutuallyExclusiveError(reason="host category "
                 "cannot be set to 'all' while there are allowed hosts")

        if 'ipaselinuxuser' in entry_attrs:
            validate_selinuxuser_inlist(ldap, entry_attrs['ipaselinuxuser'])

        if 'seealso' in entry_attrs:
            entry_attrs['seealso'] = self.obj._normalize_seealso(entry_attrs['seealso'])
        return dn

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        self.obj._convert_seealso(ldap, entry_attrs, **options)
        return dn

api.register(selinuxusermap_mod)


class selinuxusermap_find(LDAPSearch):
    __doc__ = _('Search for SELinux User Maps.')

    msg_summary = ngettext(
        '%(count)d SELinux User Map matched', '%(count)d SELinux User Maps matched', 0
    )

    def execute(self, *args, **options):
        # If searching on hbacrule we need to find the uuid to search on
        if options.get('seealso'):
            hbacrule = options['seealso']

            try:
                hbac = api.Command['hbacrule_show'](hbacrule,
all=True)['result']
                dn = hbac['dn']
            except errors.NotFound:
                return dict(count=0, result=[], truncated=False)
            options['seealso'] = dn

        return super(selinuxusermap_find, self).execute(*args, **options)

    def post_callback(self, ldap, entries, truncated, *args, **options):
        if options.get('pkey_only', False):
            return truncated
        for entry in entries:
            (dn, attrs) = entry
            self.obj._convert_seealso(ldap, attrs, **options)
        return truncated

api.register(selinuxusermap_find)


class selinuxusermap_show(LDAPRetrieve):
    __doc__ = _('Display the properties of a SELinux User Map rule.')

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        self.obj._convert_seealso(ldap, entry_attrs, **options)
        return dn

api.register(selinuxusermap_show)


class selinuxusermap_enable(LDAPQuery):
    __doc__ = _('Enable an SELinux User Map rule.')

    msg_summary = _('Enabled SELinux User Map "%(value)s"')
    has_output = output.standard_value

    def execute(self, cn):
        ldap = self.obj.backend

        dn = self.obj.get_dn(cn)
        entry_attrs = {'ipaenabledflag': 'TRUE'}

        try:
            ldap.update_entry(dn, entry_attrs)
        except errors.EmptyModlist:
            raise errors.AlreadyActive()
        except errors.NotFound:
            self.obj.handle_not_found(cn)

        return dict(
            result=True,
            value=cn,
        )

api.register(selinuxusermap_enable)


class selinuxusermap_disable(LDAPQuery):
    __doc__ = _('Disable an SELinux User Map rule.')

    msg_summary = _('Disabled SELinux User Map "%(value)s"')
    has_output = output.standard_value

    def execute(self, cn):
        ldap = self.obj.backend

        dn = self.obj.get_dn(cn)
        entry_attrs = {'ipaenabledflag': 'FALSE'}

        try:
            ldap.update_entry(dn, entry_attrs)
        except errors.EmptyModlist:
            raise errors.AlreadyInactive()
        except errors.NotFound:
            self.obj.handle_not_found(cn)

        return dict(
            result=True,
            value=cn,
        )

api.register(selinuxusermap_disable)


class selinuxusermap_add_user(LDAPAddMember):
    __doc__ = _('Add users and groups to an SELinux User Map rule.')

    member_attributes = ['memberuser']
    member_count_out = ('%i object added.', '%i objects added.')

    def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
        assert isinstance(dn, DN)
        try:
            (dn, entry_attrs) = ldap.get_entry(dn, self.obj.default_attributes)
        except errors.NotFound:
            self.obj.handle_not_found(*keys)
        if 'usercategory' in entry_attrs and \
            entry_attrs['usercategory'][0].lower() == 'all':
            raise errors.MutuallyExclusiveError(
                reason=_("users cannot be added when user category='all'"))
        if 'seealso' in entry_attrs:
            raise errors.MutuallyExclusiveError(reason=notboth_err)
        return dn

api.register(selinuxusermap_add_user)


class selinuxusermap_remove_user(LDAPRemoveMember):
    __doc__ = _('Remove users and groups from an SELinux User Map rule.')

    member_attributes = ['memberuser']
    member_count_out = ('%i object removed.', '%i objects removed.')

api.register(selinuxusermap_remove_user)


class selinuxusermap_add_host(LDAPAddMember):
    __doc__ = _('Add target hosts and hostgroups to an SELinux User Map rule.')

    member_attributes = ['memberhost']
    member_count_out = ('%i object added.', '%i objects added.')

    def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
        assert isinstance(dn, DN)
        try:
            (dn, entry_attrs) = ldap.get_entry(dn, self.obj.default_attributes)
        except errors.NotFound:
            self.obj.handle_not_found(*keys)
        if 'hostcategory' in entry_attrs and \
            entry_attrs['hostcategory'][0].lower() == 'all':
            raise errors.MutuallyExclusiveError(
                reason=_("hosts cannot be added when host category='all'"))
        if 'seealso' in entry_attrs:
            raise errors.MutuallyExclusiveError(reason=notboth_err)
        return dn

api.register(selinuxusermap_add_host)


class selinuxusermap_remove_host(LDAPRemoveMember):
    __doc__ = _('Remove target hosts and hostgroups from an SELinux User Map rule.')

    member_attributes = ['memberhost']
    member_count_out = ('%i object removed.', '%i objects removed.')

api.register(selinuxusermap_remove_host)
ass="hl opt">); static int i596_start_xmit(struct sk_buff *skb, struct net_device *dev); static irqreturn_t i596_interrupt(int irq, void *dev_id); static int i596_close(struct net_device *dev); static struct net_device_stats *i596_get_stats(struct net_device *dev); static void i596_add_cmd(struct net_device *dev, struct i596_cmd *cmd); static void print_eth(char *); static void set_multicast_list(struct net_device *dev); static void i596_tx_timeout(struct net_device *dev); static int i596_timeout(struct net_device *dev, char *msg, int ct) { struct i596_private *lp; int boguscnt = ct; lp = (struct i596_private *) dev->priv; while (lp->scb.command) { if (--boguscnt == 0) { printk("%s: %s timed out - stat %4.4x, cmd %4.4x\n", dev->name, msg, lp->scb.status, lp->scb.command); return 1; } udelay(5); barrier(); } return 0; } static inline int init_rx_bufs(struct net_device *dev, int num) { struct i596_private *lp; struct i596_rfd *rfd; int i; // struct i596_rbd *rbd; lp = (struct i596_private *) dev->priv; lp->scb.pa_rfd = I596_NULL; for (i = 0; i < num; i++) { rfd = kmalloc(sizeof(struct i596_rfd), GFP_KERNEL); if (rfd == NULL) break; rfd->stat = 0; rfd->pa_rbd = I596_NULL; rfd->count = 0; rfd->size = 1532; if (i == 0) { rfd->cmd = CMD_EOL; lp->rx_tail = rfd; } else { rfd->cmd = 0; } rfd->pa_next = lp->scb.pa_rfd; lp->scb.pa_rfd = va_to_pa(rfd); lp->rx_tail->pa_next = lp->scb.pa_rfd; } #if 0 for (i = 0; i<RX_RBD_SIZE; i++) { rbd = kmalloc(sizeof(struct i596_rbd), GFP_KERNEL); if (rbd) { rbd->pad = 0; rbd->count = 0; rbd->skb = dev_alloc_skb(RX_SKBSIZE); if (!rbd->skb) { printk("dev_alloc_skb failed"); } rbd->next = rfd->rbd; if (i) { rfd->rbd->prev = rbd; rbd->size = RX_SKBSIZE; } else { rbd->size = (RX_SKBSIZE | RBD_EL); lp->rbd_tail = rbd; } rfd->rbd = rbd; } else { printk("Could not kmalloc rbd\n"); } } lp->rbd_tail->next = rfd->rbd; #endif return (i); } static inline void remove_rx_bufs(struct net_device *dev) { struct i596_private *lp; struct i596_rfd *rfd; lp = (struct i596_private *) dev->priv; lp->rx_tail->pa_next = I596_NULL; do { rfd = pa_to_va(lp->scb.pa_rfd); lp->scb.pa_rfd = rfd->pa_next; kfree(rfd); } while (rfd != lp->rx_tail); lp->rx_tail = NULL; #if 0 for (lp->rbd_list) { } #endif } #define PORT_RESET 0x00 /* reset 82596 */ #define PORT_SELFTEST 0x01 /* selftest */ #define PORT_ALTSCP 0x02 /* alternate SCB address */ #define PORT_DUMP 0x03 /* dump */ #define IOADDR 0xcb0 /* real constant */ #define IRQ 10 /* default IRQ - can be changed by ECU */ /* The 82596 requires two 16-bit write cycles for a port command */ static inline void PORT(phys_addr a, unsigned int cmd) { if (a & 0xf) printk("lp486e.c: PORT: address not aligned\n"); outw(((a & 0xffff) | cmd), IOADDR); outw(((a>>16) & 0xffff), IOADDR+2); } static inline void CA(void) { outb(0, IOADDR+4); udelay(8); } static inline void CLEAR_INT(void) { outb(0, IOADDR+8); } #define SIZE(x) (sizeof(x)/sizeof((x)[0])) #if 0 /* selftest or dump */ static void i596_port_do(struct net_device *dev, int portcmd, char *cmdname) { struct i596_private *lp = dev->priv; u16 *outp; int i, m; memset((void *)&(lp->dump), 0, sizeof(struct i596_dump)); outp = &(lp->dump.dump[0]); PORT(va_to_pa(outp), portcmd); mdelay(30); /* random, unmotivated */ printk("lp486e i82596 %s result:\n", cmdname); for (m = SIZE(lp->dump.dump); m && lp->dump.dump[m-1] == 0; m--) ; for (i = 0; i < m; i++) { printk(" %04x", lp->dump.dump[i]); if (i%8 == 7) printk("\n"); } printk("\n"); } #endif static int i596_scp_setup(struct net_device *dev) { struct i596_private *lp = dev->priv; int boguscnt; /* Setup SCP, ISCP, SCB */ /* * sysbus bits: * only a single byte is significant - here 0x44 * 0x80: big endian mode (details depend on stepping) * 0x40: 1 * 0x20: interrupt pin is active low * 0x10: lock function disabled * 0x08: external triggering of bus throttle timers * 0x06: 00: 82586 compat mode, 01: segmented mode, 10: linear mode * 0x01: unused */ lp->scp.sysbus = 0x00440000; /* linear mode */ lp->scp.pad = 0; /* must be zero */ lp->scp.pa_iscp = va_to_pa(&(lp->iscp)); /* * The CPU sets the ISCP to 1 before it gives the first CA() */ lp->iscp.busy = 0x0001; lp->iscp.pa_scb = va_to_pa(&(lp->scb)); lp->scb.command = 0; lp->scb.status = 0; lp->scb.pa_cmd = I596_NULL; /* lp->scb.pa_rfd has been initialised already */ lp->last_cmd = jiffies; lp->cmd_backlog = 0; lp->cmd_head = NULL; /* * Reset the 82596. * We need to wait 10 systemclock cycles, and * 5 serial clock cycles. */ PORT(0, PORT_RESET); /* address part ignored */ udelay(100); /* * Before the CA signal is asserted, the default SCP address * (0x00fffff4) can be changed to a 16-byte aligned value */ PORT(va_to_pa(&lp->scp), PORT_ALTSCP); /* change the scp address */ /* * The initialization procedure begins when a * Channel Attention signal is asserted after a reset. */ CA(); /* * The ISCP busy is cleared by the 82596 after the SCB address is read. */ boguscnt = 100; while (lp->iscp.busy) { if (--boguscnt == 0) { /* No i82596 present? */ printk("%s: i82596 initialization timed out\n", dev->name); return 1; } udelay(5); barrier(); } /* I find here boguscnt==100, so no delay was required. */ return 0; } static int init_i596(struct net_device *dev) { struct i596_private *lp; if (i596_scp_setup(dev)) return 1; lp = (struct i596_private *) dev->priv; lp->scb.command = 0; memcpy ((void *)lp->i596_config, init_setup, 14); lp->set_conf.command = CmdConfigure; i596_add_cmd(dev, (void *)&lp->set_conf); memcpy ((void *)lp->eth_addr, dev->dev_addr, 6); lp->set_add.command = CmdIASetup; i596_add_cmd(dev, (struct i596_cmd *)&lp->set_add); lp->tdr.command = CmdTDR; i596_add_cmd(dev, (struct i596_cmd *)&lp->tdr); if (lp->scb.command && i596_timeout(dev, "i82596 init", 200)) return 1; lp->scb.command = RX_START; CA(); barrier(); if (lp->scb.command && i596_timeout(dev, "Receive Unit start", 100)) return 1; return 0; } /* Receive a single frame */ static inline int i596_rx_one(struct net_device *dev, struct i596_private *lp, struct i596_rfd *rfd, int *frames) { if (rfd->stat & RFD_STAT_OK) { /* a good frame */ int pkt_len = (rfd->count & 0x3fff); struct sk_buff *skb = dev_alloc_skb(pkt_len); (*frames)++; if (rfd->cmd & CMD_EOL) printk("Received on EOL\n"); if (skb == NULL) { printk ("%s: i596_rx Memory squeeze, " "dropping packet.\n", dev->name); lp->stats.rx_dropped++; return 1; } skb->dev = dev; memcpy(skb_put(skb,pkt_len), rfd->data, pkt_len); skb->protocol = eth_type_trans(skb,dev); netif_rx(skb); dev->last_rx = jiffies; lp->stats.rx_packets++; } else { #if 0 printk("Frame reception error status %04x\n", rfd->stat); #endif lp->stats.rx_errors++; if (rfd->stat & RFD_COLLISION) lp->stats.collisions++; if (rfd->stat & RFD_SHORT_FRAME_ERR) lp->stats.rx_length_errors++; if (rfd->stat & RFD_DMA_ERR) lp->stats.rx_over_errors++; if (rfd->stat & RFD_NOBUFS_ERR) lp->stats.rx_fifo_errors++; if (rfd->stat & RFD_ALIGN_ERR) lp->stats.rx_frame_errors++; if (rfd->stat & RFD_CRC_ERR) lp->stats.rx_crc_errors++; if (rfd->stat & RFD_LENGTH_ERR) lp->stats.rx_length_errors++; } rfd->stat = rfd->count = 0; return 0; } static int i596_rx(struct net_device *dev) { struct i596_private *lp = (struct i596_private *) dev->priv; struct i596_rfd *rfd; int frames = 0; while (1) { rfd = pa_to_va(lp->scb.pa_rfd); if (!rfd) { printk(KERN_ERR "i596_rx: NULL rfd?\n"); return 0; } #if 1 if (rfd->stat && !(rfd->stat & (RFD_STAT_C | RFD_STAT_B))) printk("SF:%p-%04x\n", rfd, rfd->stat); #endif if (!(rfd->stat & RFD_STAT_C)) break; /* next one not ready */ if (i596_rx_one(dev, lp, rfd, &frames)) break; /* out of memory */ rfd->cmd = CMD_EOL; lp->rx_tail->cmd = 0; lp->rx_tail = rfd; lp->scb.pa_rfd = rfd->pa_next; barrier(); } return frames; } static void i596_cleanup_cmd(struct net_device *dev) { struct i596_private *lp; struct i596_cmd *cmd; lp = (struct i596_private *) dev->priv; while (lp->cmd_head) { cmd = (struct i596_cmd *)lp->cmd_head; lp->cmd_head = pa_to_va(lp->cmd_head->pa_next); lp->cmd_backlog--; switch ((cmd->command) & 0x7) { case CmdTx: { struct tx_cmd *tx_cmd = (struct tx_cmd *) cmd; struct i596_tbd * tx_cmd_tbd; tx_cmd_tbd = pa_to_va(tx_cmd->pa_tbd); dev_kfree_skb_any(tx_cmd_tbd->skb); lp->stats.tx_errors++; lp->stats.tx_aborted_errors++; cmd->pa_next = I596_NULL; kfree((unsigned char *)tx_cmd); netif_wake_queue(dev); break; } case CmdMulticastList: { // unsigned short count = *((unsigned short *) (ptr + 1)); cmd->pa_next = I596_NULL; kfree((unsigned char *)cmd); break; } default: { cmd->pa_next = I596_NULL; break; } } barrier(); } if (lp->scb.command && i596_timeout(dev, "i596_cleanup_cmd", 100)) ; lp->scb.pa_cmd = va_to_pa(lp->cmd_head); } static void i596_reset(struct net_device *dev, struct i596_private *lp, int ioaddr) { if (lp->scb.command && i596_timeout(dev, "i596_reset", 100)) ; netif_stop_queue(dev); lp->scb.command = CUC_ABORT | RX_ABORT; CA(); barrier(); /* wait for shutdown */ if (lp->scb.command && i596_timeout(dev, "i596_reset(2)", 400)) ; i596_cleanup_cmd(dev); i596_rx(dev); netif_start_queue(dev); /*dev_kfree_skb(skb, FREE_WRITE);*/ init_i596(dev); } static void i596_add_cmd(struct net_device *dev, struct i596_cmd *cmd) { struct i596_private *lp = dev->priv; int ioaddr = dev->base_addr; unsigned long flags; cmd->status = 0; cmd->command |= (CMD_EOL | CMD_INTR); cmd->pa_next = I596_NULL; spin_lock_irqsave(&lp->cmd_lock, flags); if (lp->cmd_head) { lp->cmd_tail->pa_next = va_to_pa(cmd); } else { lp->cmd_head = cmd; if (lp->scb.command && i596_timeout(dev, "i596_add_cmd", 100)) ; lp->scb.pa_cmd = va_to_pa(cmd); lp->scb.command = CUC_START; CA(); } lp->cmd_tail = cmd; lp->cmd_backlog++; lp->cmd_head = pa_to_va(lp->scb.pa_cmd); spin_unlock_irqrestore(&lp->cmd_lock, flags); if (lp->cmd_backlog > 16) { int tickssofar = jiffies - lp->last_cmd; if (tickssofar < HZ/4) return; printk(KERN_WARNING "%s: command unit timed out, status resetting.\n", dev->name); i596_reset(dev, lp, ioaddr); } } static int i596_open(struct net_device *dev) { int i; i = request_irq(dev->irq, &i596_interrupt, IRQF_SHARED, dev->name, dev); if (i) { printk(KERN_ERR "%s: IRQ %d not free\n", dev->name, dev->irq); return i; } if ((i = init_rx_bufs(dev, RX_RING_SIZE)) < RX_RING_SIZE) printk(KERN_ERR "%s: only able to allocate %d receive buffers\n", dev->name, i); if (i < 4) { free_irq(dev->irq, dev); return -EAGAIN; } netif_start_queue(dev); init_i596(dev); return 0; /* Always succeed */ } static int i596_start_xmit (struct sk_buff *skb, struct net_device *dev) { struct i596_private *lp = dev->priv; struct tx_cmd *tx_cmd; short length; length = skb->len; if (length < ETH_ZLEN) { if (skb_padto(skb, ETH_ZLEN)) return 0; length = ETH_ZLEN; } dev->trans_start = jiffies; tx_cmd = (struct tx_cmd *) kmalloc ((sizeof (struct tx_cmd) + sizeof (struct i596_tbd)), GFP_ATOMIC); if (tx_cmd == NULL) { printk(KERN_WARNING "%s: i596_xmit Memory squeeze, dropping packet.\n", dev->name); lp->stats.tx_dropped++; dev_kfree_skb (skb); } else { struct i596_tbd *tx_cmd_tbd; tx_cmd_tbd = (struct i596_tbd *) (tx_cmd + 1); tx_cmd->pa_tbd = va_to_pa (tx_cmd_tbd); tx_cmd_tbd->pa_next = I596_NULL; tx_cmd->cmd.command = (CMD_FLEX | CmdTx); tx_cmd->pad = 0; tx_cmd->size = 0; tx_cmd_tbd->pad = 0; tx_cmd_tbd->size = (EOF | length); tx_cmd_tbd->pa_data = va_to_pa (skb->data); tx_cmd_tbd->skb = skb; if (i596_debug & LOG_SRCDST) print_eth (skb->data); i596_add_cmd (dev, (struct i596_cmd *) tx_cmd); lp->stats.tx_packets++; } return 0; } static void i596_tx_timeout (struct net_device *dev) { struct i596_private *lp = dev->priv; int ioaddr = dev->base_addr; /* Transmitter timeout, serious problems. */ printk(KERN_WARNING "%s: transmit timed out, status resetting.\n", dev->name); lp->stats.tx_errors++; /* Try to restart the adaptor */ if (lp->last_restart == lp->stats.tx_packets) { printk ("Resetting board.\n"); /* Shutdown and restart */ i596_reset (dev, lp, ioaddr); } else { /* Issue a channel attention signal */ printk ("Kicking board.\n"); lp->scb.command = (CUC_START | RX_START); CA(); lp->last_restart = lp->stats.tx_packets; } netif_wake_queue(dev); } static void print_eth(char *add) { int i; printk ("Dest "); for (i = 0; i < 6; i++) printk(" %2.2X", (unsigned char) add[i]); printk ("\n"); printk ("Source"); for (i = 0; i < 6; i++) printk(" %2.2X", (unsigned char) add[i+6]); printk ("\n"); printk ("type %2.2X%2.2X\n", (unsigned char) add[12], (unsigned char) add[13]); } static int __init lp486e_probe(struct net_device *dev) { struct i596_private *lp; unsigned char eth_addr[6] = { 0, 0xaa, 0, 0, 0, 0 }; unsigned char *bios; int i, j; int ret = -ENOMEM; static int probed; if (probed) return -ENODEV; probed++; if (!request_region(IOADDR, LP486E_TOTAL_SIZE, DRV_NAME)) { printk(KERN_ERR "lp486e: IO address 0x%x in use\n", IOADDR); return -EBUSY; } lp = (struct i596_private *) dev->priv; spin_lock_init(&lp->cmd_lock); /* * Do we really have this thing? */ if (i596_scp_setup(dev)) { ret = -ENODEV; goto err_out_kfree; } dev->base_addr = IOADDR; dev->irq = IRQ; /* * How do we find the ethernet address? I don't know. * One possibility is to look at the EISA configuration area * [0xe8000-0xe9fff]. This contains the ethernet address * but not at a fixed address - things depend on setup options. * * If we find no address, or the wrong address, use * ifconfig eth0 hw ether a1:a2:a3:a4:a5:a6 * with the value found in the BIOS setup. */ bios = bus_to_virt(0xe8000); for (j = 0; j < 0x2000; j++) { if (bios[j] == 0 && bios[j+1] == 0xaa && bios[j+2] == 0) { printk("%s: maybe address at BIOS 0x%x:", dev->name, 0xe8000+j); for (i = 0; i < 6; i++) { eth_addr[i] = bios[i+j]; printk(" %2.2X", eth_addr[i]); } printk("\n"); } } printk("%s: lp486e 82596 at %#3lx, IRQ %d,", dev->name, dev->base_addr, dev->irq); for (i = 0; i < 6; i++) printk(" %2.2X", dev->dev_addr[i] = eth_addr[i]); printk("\n"); /* The LP486E-specific entries in the device structure. */ dev->open = &i596_open; dev->stop = &i596_close; dev->hard_start_xmit = &i596_start_xmit; dev->get_stats = &i596_get_stats; dev->set_multicast_list = &set_multicast_list; dev->watchdog_timeo = 5*HZ; dev->tx_timeout = i596_tx_timeout; #if 0 /* selftest reports 0x320925ae - don't know what that means */ i596_port_do(dev, PORT_SELFTEST, "selftest"); i596_port_do(dev, PORT_DUMP, "dump"); #endif return 0; err_out_kfree: release_region(IOADDR, LP486E_TOTAL_SIZE); return ret; } static inline void i596_handle_CU_completion(struct net_device *dev, struct i596_private *lp, unsigned short status, unsigned short *ack_cmdp) { struct i596_cmd *cmd; int frames_out = 0; int commands_done = 0; int cmd_val; unsigned long flags; spin_lock_irqsave(&lp->cmd_lock, flags); cmd = lp->cmd_head; while (lp->cmd_head && (lp->cmd_head->status & CMD_STAT_C)) { cmd = lp->cmd_head; lp->cmd_head = pa_to_va(lp->cmd_head->pa_next); lp->cmd_backlog--; commands_done++; cmd_val = cmd->command & 0x7; #if 0 printk("finished CU %s command (%d)\n", CUcmdnames[cmd_val], cmd_val); #endif switch (cmd_val) { case CmdTx: { struct tx_cmd *tx_cmd; struct i596_tbd *tx_cmd_tbd; tx_cmd = (struct tx_cmd *) cmd; tx_cmd_tbd = pa_to_va(tx_cmd->pa_tbd); frames_out++; if (cmd->status & CMD_STAT_OK) { if (i596_debug) print_eth(pa_to_va(tx_cmd_tbd->pa_data)); } else { lp->stats.tx_errors++; if (i596_debug) printk("transmission failure:%04x\n", cmd->status); if (cmd->status & 0x0020) lp->stats.collisions++; if (!(cmd->status & 0x0040)) lp->stats.tx_heartbeat_errors++; if (cmd->status & 0x0400) lp->stats.tx_carrier_errors++; if (cmd->status & 0x0800) lp->stats.collisions++; if (cmd->status & 0x1000) lp->stats.tx_aborted_errors++; } dev_kfree_skb_irq(tx_cmd_tbd->skb); cmd->pa_next = I596_NULL; kfree((unsigned char *)tx_cmd); netif_wake_queue(dev); break; } case CmdMulticastList: cmd->pa_next = I596_NULL; kfree((unsigned char *)cmd); break; case CmdTDR: { unsigned long status = *((unsigned long *) (cmd + 1)); if (status & 0x8000) { if (i596_debug) printk("%s: link ok.\n", dev->name); } else { if (status & 0x4000) printk("%s: Transceiver problem.\n", dev->name); if (status & 0x2000) printk("%s: Termination problem.\n", dev->name); if (status & 0x1000) printk("%s: Short circuit.\n", dev->name); printk("%s: Time %ld.\n", dev->name, status & 0x07ff); } } default: cmd->pa_next = I596_NULL; lp->last_cmd = jiffies; } barrier(); } cmd = lp->cmd_head; while (cmd && (cmd != lp->cmd_tail)) { cmd->command &= 0x1fff; cmd = pa_to_va(cmd->pa_next); barrier(); } if (lp->cmd_head) *ack_cmdp |= CUC_START; lp->scb.pa_cmd = va_to_pa(lp->cmd_head); spin_unlock_irqrestore(&lp->cmd_lock, flags); } static irqreturn_t i596_interrupt (int irq, void *dev_instance) { struct net_device *dev = (struct net_device *) dev_instance; struct i596_private *lp; unsigned short status, ack_cmd = 0; int frames_in = 0; lp = (struct i596_private *) dev->priv; /* * The 82596 examines the command, performs the required action, * and then clears the SCB command word. */ if (lp->scb.command && i596_timeout(dev, "interrupt", 40)) ; /* * The status word indicates the status of the 82596. * It is modified only by the 82596. * * [So, we must not clear it. I find often status 0xffff, * which is not one of the values allowed by the docs.] */ status = lp->scb.status; #if 0 if (i596_debug) { printk("%s: i596 interrupt, ", dev->name); i596_out_status(status); } #endif /* Impossible, but it happens - perhaps when we get a receive interrupt but scb.pa_rfd is I596_NULL. */ if (status == 0xffff) { printk("%s: i596_interrupt: got status 0xffff\n", dev->name); goto out; } ack_cmd = (status & STAT_ACK); if (status & (STAT_CX | STAT_CNA)) i596_handle_CU_completion(dev, lp, status, &ack_cmd); if (status & (STAT_FR | STAT_RNR)) { /* Restart the receive unit when it got inactive somehow */ if ((status & STAT_RNR) && netif_running(dev)) ack_cmd |= RX_START; if (status & STAT_FR) { frames_in = i596_rx(dev); if (!frames_in) printk("receive frame reported, but no frames\n"); } } /* acknowledge the interrupt */ /* if ((lp->scb.pa_cmd != I596_NULL) && netif_running(dev)) ack_cmd |= CUC_START; */ if (lp->scb.command && i596_timeout(dev, "i596 interrupt", 100)) ; lp->scb.command = ack_cmd; CLEAR_INT(); CA(); out: return IRQ_HANDLED; } static int i596_close(struct net_device *dev) { struct i596_private *lp = dev->priv; netif_stop_queue(dev); if (i596_debug) printk("%s: Shutting down ethercard, status was %4.4x.\n", dev->name, lp->scb.status); lp->scb.command = (CUC_ABORT | RX_ABORT); CA(); i596_cleanup_cmd(dev); if (lp->scb.command && i596_timeout(dev, "i596_close", 200)) ; free_irq(dev->irq, dev); remove_rx_bufs(dev); return 0; } static struct net_device_stats * i596_get_stats(struct net_device *dev) { struct i596_private *lp = dev->priv; return &lp->stats; } /* * Set or clear the multicast filter for this adaptor. */ static void set_multicast_list(struct net_device *dev) { struct i596_private *lp = dev->priv; struct i596_cmd *cmd; if (i596_debug > 1) printk ("%s: set multicast list %d\n", dev->name, dev->mc_count); if (dev->mc_count > 0) { struct dev_mc_list *dmi; char *cp; cmd = (struct i596_cmd *)kmalloc(sizeof(struct i596_cmd)+2+dev->mc_count*6, GFP_ATOMIC); if (cmd == NULL) { printk (KERN_ERR "%s: set_multicast Memory squeeze.\n", dev->name); return; } cmd->command = CmdMulticastList; *((unsigned short *) (cmd + 1)) = dev->mc_count * 6; cp = ((char *)(cmd + 1))+2; for (dmi = dev->mc_list; dmi != NULL; dmi = dmi->next) { memcpy(cp, dmi,6); cp += 6; } if (i596_debug & LOG_SRCDST) print_eth (((char *)(cmd + 1)) + 2); i596_add_cmd(dev, cmd); } else { if (lp->set_conf.pa_next != I596_NULL) { return; } if (dev->mc_count == 0 && !(dev->flags & (IFF_PROMISC | IFF_ALLMULTI))) { if (dev->flags & IFF_ALLMULTI) dev->flags |= IFF_PROMISC; lp->i596_config[8] &= ~0x01; } else { lp->i596_config[8] |= 0x01; } i596_add_cmd(dev, (struct i596_cmd *) &lp->set_conf); } } MODULE_AUTHOR("Ard van Breemen <ard@cstmel.nl.eu.org>"); MODULE_DESCRIPTION("Intel Panther onboard i82596 driver"); MODULE_LICENSE("GPL"); static struct net_device *dev_lp486e; static int full_duplex; static int options; static int io = IOADDR; static int irq = IRQ; module_param(debug, int, 0); //module_param(max_interrupt_work, int, 0); //module_param(reverse_probe, int, 0); //module_param(rx_copybreak, int, 0); module_param(options, int, 0); module_param(full_duplex, int, 0); static int __init lp486e_init_module(void) { int err; struct net_device *dev = alloc_etherdev(sizeof(struct i596_private)); if (!dev) return -ENOMEM; dev->irq = irq; dev->base_addr = io; err = lp486e_probe(dev); if (err) { free_netdev(dev); return err; } err = register_netdev(dev); if (err) { release_region(dev->base_addr, LP486E_TOTAL_SIZE); free_netdev(dev); return err; } dev_lp486e = dev; full_duplex = 0; options = 0; return 0; } static void __exit lp486e_cleanup_module(void) { unregister_netdev(dev_lp486e); release_region(dev_lp486e->base_addr, LP486E_TOTAL_SIZE); free_netdev(dev_lp486e); } module_init(lp486e_init_module); module_exit(lp486e_cleanup_module);